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 javax.servlet.ServletException; 020 021import org.springframework.core.MethodParameter; 022import org.springframework.web.bind.ServletRequestBindingException; 023import org.springframework.web.bind.annotation.SessionAttribute; 024import org.springframework.web.bind.annotation.ValueConstants; 025import org.springframework.web.context.request.NativeWebRequest; 026import org.springframework.web.context.request.RequestAttributes; 027import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver; 028 029/** 030 * Resolves method arguments annotated with an @{@link SessionAttribute}. 031 * 032 * @author Rossen Stoyanchev 033 * @since 4.3 034 */ 035public class SessionAttributeMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver { 036 037 @Override 038 public boolean supportsParameter(MethodParameter parameter) { 039 return parameter.hasParameterAnnotation(SessionAttribute.class); 040 } 041 042 @Override 043 protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { 044 SessionAttribute ann = parameter.getParameterAnnotation(SessionAttribute.class); 045 return new NamedValueInfo(ann.name(), ann.required(), ValueConstants.DEFAULT_NONE); 046 } 047 048 @Override 049 protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request){ 050 return request.getAttribute(name, RequestAttributes.SCOPE_SESSION); 051 } 052 053 @Override 054 protected void handleMissingValue(String name, MethodParameter parameter) throws ServletException { 055 throw new ServletRequestBindingException("Missing session attribute '" + name + 056 "' of type " + parameter.getNestedParameterType().getSimpleName()); 057 } 058 059}