SpringMVC中的@SessionAttribute

1.@SessionAttribute概念

      用在处理器的类上,用于在多个请求之间传递参数,类似于Session的Attribute,但不完全一样,一般来说@SessionAttribute设置的参数只用于暂时的传递,而不是长期的保存,想身份证信息需要长期保存的参数还是应该通过Session#setAttribute设置到Session中。

  通过@SessionAttribute注释的参数有3类用法:

  • 在视图中通过request.getAttribute或者session.getAttribute获取;
  • 在后面请求的视图中通过session.getAttribute或者从Model中获取;
  • 自动将参数设置到后面请求所对应处理器的Model(ModelMap)类型参数或者有@ModelAttribute注释的参数里面

将参数设置到SessionAttribute中需要满足的条件:

  • 在@SessionAttibute注释中设置了参数的名字或者类型
  • 在处理器中将参数设置到了model中

清除SessionAttribute中的数据

   采用SessionStatus.setComplete清除,这种只是清除了SessionAttribute中参数,而不会影响Session中的参数,SessionStatus可以定义在处理器方法的参数中,RequestMappingHandlerAdapter会自动设置进去

注意点:

   @SessionAttribute只能作用在类上使用,不能作用在方法上

2.例子    

     如下所示会把所有key为book和description还有Double类型的参数都设置到SessionAttributes中,用于多个请求共享,在使用SessionStatus调用了setComplete方法后就清除了里面的值了。

@Controller
@RequestMapping("/book")
@SessionAttributes(value = {"book","description"},types = {Double.class})
public class BookController {
    
    private final Log logger = LogFactory.getLog(BookController.class);
    
    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("book","Visonws");
        model.addAttribute("description","学习SpringMVC");
        model.addAttribute("price",new Double("100.00"));
        return "redirect:get";
    }
    @RequestMapping("/get")
    public String getBySessionAttributes(@ModelAttribute("book") String book, ModelMap model, SessionStatus sessionStatus){
        logger.info("-----getBySessionAttributes--------");
        logger.info("get By @ModelAttribute:"+book); //这里会正常显示上面设置的值 Visonws
        //下面这个也会正常打出日志get By ModelMap:Visonws学习SpringMVC100.00
        logger.info("get By ModelMap:"+model.get("book")+model.get("description")+model.get("price")); 
        sessionStatus.setComplete(); //当执行了这个方法,那么就会清除SessionAttribute中的值了,后面访问就是空
        return "redirect:complete";
    }
    @RequestMapping("/complete")
    public String afterComplete(ModelMap model){
        logger.info("-------afterComplete--------");
        //下面显示就是nullnullnull
        logger.info(""+model.get("book")+model.get("description")+model.get("price"));
        return "index.jsp";
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40792878/article/details/81951115