001/*
002 * Copyright 2002-2016 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.bind.annotation;
018
019import java.lang.annotation.Documented;
020import java.lang.annotation.ElementType;
021import java.lang.annotation.Retention;
022import java.lang.annotation.RetentionPolicy;
023import java.lang.annotation.Target;
024
025import org.springframework.core.annotation.AliasFor;
026
027/**
028 * Annotation to bind a method parameter to a session attribute.
029 *
030 * <p>The main motivation is to provide convenient access to existing, permanent
031 * session attributes (e.g. user authentication object) with an optional/required
032 * check and a cast to the target method parameter type.
033 *
034 * <p>For use cases that require adding or removing session attributes consider
035 * injecting {@code org.springframework.web.context.request.WebRequest} or
036 * {@code javax.servlet.http.HttpSession} into the controller method.
037 *
038 * <p>For temporary storage of model attributes in the session as part of the
039 * workflow for a controller, consider using {@link SessionAttributes} instead.
040 *
041 * @author Rossen Stoyanchev
042 * @since 4.3
043 * @see RequestMapping
044 * @see SessionAttributes
045 * @see RequestAttribute
046 */
047@Target(ElementType.PARAMETER)
048@Retention(RetentionPolicy.RUNTIME)
049@Documented
050public @interface SessionAttribute {
051
052        /**
053         * Alias for {@link #name}.
054         */
055        @AliasFor("name")
056        String value() default "";
057
058        /**
059         * The name of the session attribute to bind to.
060         * <p>The default name is inferred from the method parameter name.
061         */
062        @AliasFor("value")
063        String name() default "";
064
065        /**
066         * Whether the session attribute is required.
067         * <p>Defaults to {@code true}, leading to an exception being thrown
068         * if the attribute is missing in the session or there is no session.
069         * Switch this to {@code false} if you prefer a {@code null} or Java 8
070         * {@code java.util.Optional} if the attribute doesn't exist.
071         */
072        boolean required() default true;
073
074}