@RequestAttribute注解用法
@RequestAttribute用在方法入參上,作用:從request中取對應的值,至於request中是怎么存在該屬性的,方式多種多樣,攔截器中預存、ModelAttribute注解預存、請求轉發帶過來的;
該注解出現自Spring4.3版本
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface RequestAttribute { /** * Alias for {@link #name}. */ @AliasFor("name") String value() default ""; /** * The name of the request attribute to bind to. * <p>The default name is inferred from the method parameter name. */ @AliasFor("value") String name() default ""; /** * Whether the request attribute is required. * <p>Defaults to {@code true}, leading to an exception being thrown if * the attribute is missing. Switch this to {@code false} if you prefer * a {@code null} or Java 8 {@code java.util.Optional} if the attribute * doesn't exist. */ boolean required() default true; }
嘗試訪問一個request中不存在的值時,@RequestAttribute拋出異常:
@RequestMapping("/demo1") public String demo1(@RequestAttribute String name){ System.out.println(name); return "test"; }
請求request中預存屬性的方式:
方式一.ModelAttribute注解
@ModelAttribute public void storeEarly(HttpServletRequest request){ request.setAttribute("name","lvbinbin"); }
方式二.攔截器中request.setAttribute()
public class SimpleInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(" Simple Interceptor preHandle"); request.setAttribute("name",24); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(" Simple Interceptor postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(" Simple Interceptor afterCompletion"); } }
方式三.請求轉發,轉發過來的請求屬性中存在;
@RequestAttribute解析流程
SpringMvc中對於方法入參解析采用HandlerMethodArgumentResolver接口,而@RequestAttribute采用RequestAttributeMethodArgumentResolver解析:
其中name屬性默認為 @RequestAttribute中name/value值,如果不存在就去方法入參的名字!
@RequestAttribute屬性required默認為true, request.getAttribute獲取不到參數就會拋出異常 ServletRequestBindingException ;
required設置為false,即使沒有從request中獲取到就忽略跳過,賦值為null;