001/* 002 * Copyright 2002-2020 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 javax.servlet.http.Cookie; 020import javax.servlet.http.HttpServletRequest; 021 022import org.springframework.beans.factory.config.ConfigurableBeanFactory; 023import org.springframework.core.MethodParameter; 024import org.springframework.web.context.request.NativeWebRequest; 025import org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver; 026import org.springframework.web.util.UrlPathHelper; 027import org.springframework.web.util.WebUtils; 028 029/** 030 * An {@link org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver} 031 * that resolves cookie values from an {@link HttpServletRequest}. 032 * 033 * @author Rossen Stoyanchev 034 * @since 3.1 035 */ 036public class ServletCookieValueMethodArgumentResolver extends AbstractCookieValueMethodArgumentResolver { 037 038 private UrlPathHelper urlPathHelper = UrlPathHelper.defaultInstance; 039 040 041 public ServletCookieValueMethodArgumentResolver(ConfigurableBeanFactory beanFactory) { 042 super(beanFactory); 043 } 044 045 046 public void setUrlPathHelper(UrlPathHelper urlPathHelper) { 047 this.urlPathHelper = urlPathHelper; 048 } 049 050 051 @Override 052 protected Object resolveName(String cookieName, MethodParameter parameter, NativeWebRequest webRequest) throws Exception { 053 HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); 054 Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName); 055 if (Cookie.class.isAssignableFrom(parameter.getNestedParameterType())) { 056 return cookieValue; 057 } 058 else if (cookieValue != null) { 059 return this.urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue()); 060 } 061 else { 062 return null; 063 } 064 } 065 066}