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