View Javadoc
1   /*
2    * Copyright 2002-2015 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 java.util.Collections;
20  import java.util.Map;
21  import javax.servlet.ServletRequest;
22  
23  import org.springframework.core.MethodParameter;
24  import org.springframework.core.convert.ConversionService;
25  import org.springframework.core.convert.TypeDescriptor;
26  import org.springframework.core.convert.converter.Converter;
27  import org.springframework.util.StringUtils;
28  import org.springframework.validation.DataBinder;
29  import org.springframework.web.bind.ServletRequestDataBinder;
30  import org.springframework.web.bind.WebDataBinder;
31  import org.springframework.web.bind.support.WebDataBinderFactory;
32  import org.springframework.web.context.request.NativeWebRequest;
33  import org.springframework.web.context.request.RequestAttributes;
34  import org.springframework.web.method.annotation.ModelAttributeMethodProcessor;
35  import org.springframework.web.servlet.HandlerMapping;
36  
37  /**
38   * A Servlet-specific {@link ModelAttributeMethodProcessor} that applies data
39   * binding through a WebDataBinder of type {@link ServletRequestDataBinder}.
40   *
41   * <p>Also adds a fall-back strategy to instantiate the model attribute from a
42   * URI template variable or from a request parameter if the name matches the
43   * model attribute name and there is an appropriate type conversion strategy.
44   *
45   * @author Rossen Stoyanchev
46   * @since 3.1
47   */
48  public class ServletModelAttributeMethodProcessor extends ModelAttributeMethodProcessor {
49  
50  	/**
51  	 * @param annotationNotRequired if "true", non-simple method arguments and
52  	 * return values are considered model attributes with or without a
53  	 * {@code @ModelAttribute} annotation
54  	 */
55  	public ServletModelAttributeMethodProcessor(boolean annotationNotRequired) {
56  		super(annotationNotRequired);
57  	}
58  
59  
60  	/**
61  	 * Instantiate the model attribute from a URI template variable or from a
62  	 * request parameter if the name matches to the model attribute name and
63  	 * if there is an appropriate type conversion strategy. If none of these
64  	 * are true delegate back to the base class.
65  	 * @see #createAttributeFromRequestValue
66  	 */
67  	@Override
68  	protected final Object createAttribute(String attributeName, MethodParameter methodParam,
69  			WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
70  
71  		String value = getRequestValueForAttribute(attributeName, request);
72  		if (value != null) {
73  			Object attribute = createAttributeFromRequestValue(
74  					value, attributeName, methodParam, binderFactory, request);
75  			if (attribute != null) {
76  				return attribute;
77  			}
78  		}
79  
80  		return super.createAttribute(attributeName, methodParam, binderFactory, request);
81  	}
82  
83  	/**
84  	 * Obtain a value from the request that may be used to instantiate the
85  	 * model attribute through type conversion from String to the target type.
86  	 * <p>The default implementation looks for the attribute name to match
87  	 * a URI variable first and then a request parameter.
88  	 * @param attributeName the model attribute name
89  	 * @param request the current request
90  	 * @return the request value to try to convert or {@code null}
91  	 */
92  	protected String getRequestValueForAttribute(String attributeName, NativeWebRequest request) {
93  		Map<String, String> variables = getUriTemplateVariables(request);
94  		if (StringUtils.hasText(variables.get(attributeName))) {
95  			return variables.get(attributeName);
96  		}
97  		else if (StringUtils.hasText(request.getParameter(attributeName))) {
98  			return request.getParameter(attributeName);
99  		}
100 		else {
101 			return null;
102 		}
103 	}
104 
105 	@SuppressWarnings("unchecked")
106 	protected final Map<String, String> getUriTemplateVariables(NativeWebRequest request) {
107 		Map<String, String> variables = (Map<String, String>) request.getAttribute(
108 				HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
109 		return (variables != null ? variables : Collections.<String, String>emptyMap());
110 	}
111 
112 	/**
113 	 * Create a model attribute from a String request value (e.g. URI template
114 	 * variable, request parameter) using type conversion.
115 	 * <p>The default implementation converts only if there a registered
116 	 * {@link Converter} that can perform the conversion.
117 	 * @param sourceValue the source value to create the model attribute from
118 	 * @param attributeName the name of the attribute, never {@code null}
119 	 * @param methodParam the method parameter
120 	 * @param binderFactory for creating WebDataBinder instance
121 	 * @param request the current request
122 	 * @return the created model attribute, or {@code null}
123 	 * @throws Exception
124 	 */
125 	protected Object createAttributeFromRequestValue(String sourceValue, String attributeName,
126 			MethodParameter methodParam, WebDataBinderFactory binderFactory, NativeWebRequest request)
127 			throws Exception {
128 
129 		DataBinder binder = binderFactory.createBinder(request, null, attributeName);
130 		ConversionService conversionService = binder.getConversionService();
131 		if (conversionService != null) {
132 			TypeDescriptor source = TypeDescriptor.valueOf(String.class);
133 			TypeDescriptor target = new TypeDescriptor(methodParam);
134 			if (conversionService.canConvert(source, target)) {
135 				return binder.convertIfNecessary(sourceValue, methodParam.getParameterType(), methodParam);
136 			}
137 		}
138 		return null;
139 	}
140 
141 	/**
142 	 * This implementation downcasts {@link WebDataBinder} to
143 	 * {@link ServletRequestDataBinder} before binding.
144 	 * @see ServletRequestDataBinderFactory
145 	 */
146 	@Override
147 	protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {
148 		ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class);
149 		ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
150 		servletBinder.bind(servletRequest);
151 	}
152 
153 }