001/* 002 * Copyright 2002-2019 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.servlet.mvc.method.annotation; 018 019import org.springframework.core.MethodParameter; 020import org.springframework.lang.Nullable; 021import org.springframework.web.context.request.NativeWebRequest; 022import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 023import org.springframework.web.method.support.ModelAndViewContainer; 024import org.springframework.web.servlet.RequestToViewNameTranslator; 025import org.springframework.web.servlet.SmartView; 026import org.springframework.web.servlet.View; 027 028/** 029 * Handles return values that are of type {@link View}. 030 * 031 * <p>A {@code null} return value is left as-is leaving it to the configured 032 * {@link RequestToViewNameTranslator} to select a view name by convention. 033 * 034 * <p>A {@link View} return type has a set purpose. Therefore this handler 035 * should be configured ahead of handlers that support any return value type 036 * annotated with {@code @ModelAttribute} or {@code @ResponseBody} to ensure 037 * they don't take over. 038 * 039 * @author Rossen Stoyanchev 040 * @since 3.1 041 */ 042public class ViewMethodReturnValueHandler implements HandlerMethodReturnValueHandler { 043 044 @Override 045 public boolean supportsReturnType(MethodParameter returnType) { 046 return View.class.isAssignableFrom(returnType.getParameterType()); 047 } 048 049 @Override 050 public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, 051 ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 052 053 if (returnValue instanceof View) { 054 View view = (View) returnValue; 055 mavContainer.setView(view); 056 if (view instanceof SmartView && ((SmartView) view).isRedirectView()) { 057 mavContainer.setRedirectModelScenario(true); 058 } 059 } 060 else if (returnValue != null) { 061 // should not happen 062 throw new UnsupportedOperationException("Unexpected return type: " + 063 returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); 064 } 065 } 066 067}