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 javax.servlet.http.Cookie;
20  import javax.servlet.http.HttpServletRequest;
21  
22  import org.springframework.beans.factory.config.ConfigurableBeanFactory;
23  import org.springframework.core.MethodParameter;
24  import org.springframework.web.context.request.NativeWebRequest;
25  import org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver;
26  import org.springframework.web.util.UrlPathHelper;
27  import org.springframework.web.util.WebUtils;
28  
29  /**
30   * An {@link org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver}
31   * that resolves cookie values from an {@link HttpServletRequest}.
32   *
33   * @author Rossen Stoyanchev
34   * @since 3.1
35   */
36  public class ServletCookieValueMethodArgumentResolver extends AbstractCookieValueMethodArgumentResolver {
37  
38  	private UrlPathHelper urlPathHelper = new UrlPathHelper();
39  
40  
41  	public ServletCookieValueMethodArgumentResolver(ConfigurableBeanFactory beanFactory) {
42  		super(beanFactory);
43  	}
44  
45  
46  	public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
47  		this.urlPathHelper = urlPathHelper;
48  	}
49  
50  
51  	@Override
52  	protected Object resolveName(String cookieName, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
53  		HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
54  		Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName);
55  		if (Cookie.class.isAssignableFrom(parameter.getParameterType())) {
56  			return cookieValue;
57  		}
58  		else if (cookieValue != null) {
59  			return this.urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue());
60  		}
61  		else {
62  			return null;
63  		}
64  	}
65  
66  }