@SessionAttributes 注解

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

    1. SessionAttributes 的作用 

   
一般而言ModelAndView中的属性作用域都是request级别,即本次请求结束,属性也随之销毁。
如果想要实现多个请求共享其某个属性,需将其保存至session

@SessionAttributes能自动捕获到当前controller中ModelAndView的指定属性,并转存为session

@SessionAttributes({"a", "b"}) 保存多个session


    2. 通过使用 @SessionAttributes("user") 快速得到user

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/info")
@SessionAttributes("user")  //要在方法中直接注解user必须要这一步
public class InfoController {
    private Logger logger = LoggerFactory.getLogger(InfoController.class);
    
    @RequestMapping("")
    public ModelAndView view(@ModelAttribute User user,) {
        ModelAndView modelView = new ModelAndView("/info/view");
        logger.info(user.toString());
        return modelView;
    } 
}



转载于:https://my.oschina.net/u/239075/blog/472283

你可能感兴趣的:(@SessionAttributes 注解)