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.web.context.request.NativeWebRequest; 021import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 022import org.springframework.web.method.support.ModelAndViewContainer; 023import org.springframework.web.servlet.RequestToViewNameTranslator; 024import org.springframework.web.servlet.SmartView; 025import org.springframework.web.servlet.View; 026 027/** 028 * Handles return values that are of type {@link View}. 029 * 030 * <p>A {@code null} return value is left as-is leaving it to the configured 031 * {@link RequestToViewNameTranslator} to select a view name by convention. 032 * 033 * <p>A {@link View} return type has a set purpose. Therefore this handler 034 * should be configured ahead of handlers that support any return value type 035 * annotated with {@code @ModelAttribute} or {@code @ResponseBody} to ensure 036 * they don't take over. 037 * 038 * @author Rossen Stoyanchev 039 * @since 3.1 040 */ 041public class ViewMethodReturnValueHandler implements HandlerMethodReturnValueHandler { 042 043 @Override 044 public boolean supportsReturnType(MethodParameter returnType) { 045 return View.class.isAssignableFrom(returnType.getParameterType()); 046 } 047 048 @Override 049 public void handleReturnValue(Object returnValue, MethodParameter returnType, 050 ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 051 052 if (returnValue == null) { 053 return; 054 } 055 else if (returnValue instanceof View) { 056 View view = (View) returnValue; 057 mavContainer.setView(view); 058 if (view instanceof SmartView) { 059 if (((SmartView) view).isRedirectView()) { 060 mavContainer.setRedirectModelScenario(true); 061 } 062 } 063 } 064 else { 065 // should not happen 066 throw new UnsupportedOperationException("Unexpected return type: " + 067 returnType.getParameterType().getName() + " in method: " + returnType.getMethod()); 068 } 069 } 070 071}