首页 > 解决方案 > 如何检查使用@SessionAttributes 创建的会话是否存在(Spring MVC)

问题描述

看看这段代码:

@Controller
@RequestMapping
@SessionAttributes("address")
public class HomeController {

    @RequestMapping("/home")
    public String welcome(Model model) {        
            Address address = new Address();            
            model.addAttribute("address", address);         
            return "welcome";           
    }   

}

每次我到达 url“ /home ”时,都会调用welcome()方法,创建一个新对象Address,添加到模型中并保存在session中,名称为address

检查会话“地址”是否已经存在的最佳方法是什么,以避免执行这行代码?

  Address address = new Address();          
  model.addAttribute("address", address);

我使用这种方法,但我认为使用Spring features有更好和更具体的方法。

@RequestMapping
public String welcome(Model model, HttpServletRequest httpServletRequest) {
   Address vecchioAddress = (Address)httpServletRequest.getSession().getAttribute("address");
   if(vecchioAddress == null) {
            Address address = new Address();                
            model.addAttribute("address", address);
   }    

}

谢谢

标签: javaspring-mvcsession

解决方案


尝试使用@SessionAttribute注释从会话中检索现有属性。

@RequestMapping
public String welcome(@SessionAttribute("address") Address address) {
  // something....
}

推荐阅读