View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.web.servlet.mvc.method.annotation;
18  
19  import org.springframework.core.MethodParameter;
20  import org.springframework.web.context.request.NativeWebRequest;
21  import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
22  import org.springframework.web.method.support.ModelAndViewContainer;
23  import org.springframework.web.servlet.RequestToViewNameTranslator;
24  import org.springframework.web.servlet.SmartView;
25  import org.springframework.web.servlet.View;
26  
27  /**
28   * Handles return values that are of type {@link View}.
29   *
30   * <p>A {@code null} return value is left as-is leaving it to the configured
31   * {@link RequestToViewNameTranslator} to select a view name by convention.
32   *
33   * <p>A {@link View} return type has a set purpose. Therefore this handler
34   * should be configured ahead of handlers that support any return value type
35   * annotated with {@code @ModelAttribute} or {@code @ResponseBody} to ensure
36   * they don't take over.
37   *
38   * @author Rossen Stoyanchev
39   * @since 3.1
40   */
41  public class ViewMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
42  
43  	@Override
44  	public boolean supportsReturnType(MethodParameter returnType) {
45  		return View.class.isAssignableFrom(returnType.getParameterType());
46  	}
47  
48  	@Override
49  	public void handleReturnValue(Object returnValue, MethodParameter returnType,
50  			ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
51  
52  		if (returnValue == null) {
53  			return;
54  		}
55  		else if (returnValue instanceof View){
56  			View view = (View) returnValue;
57  			mavContainer.setView(view);
58  			if (view instanceof SmartView) {
59  				if (((SmartView) view).isRedirectView()) {
60  					mavContainer.setRedirectModelScenario(true);
61  				}
62  			}
63  		}
64  		else {
65  			// should not happen
66  			throw new UnsupportedOperationException("Unexpected return type: " +
67  					returnType.getParameterType().getName() + " in method: " + returnType.getMethod());
68  		}
69  	}
70  
71  }