![](/img/trans.png)
[英]How to update @SessionAttributes without using the HttpServletRequest session, using Spring MVC
[英]How to check if a session created with @SessionAttributes exists (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 ,将其添加到模型中,并以name address的名称保存在会话中 。
为了避免执行此代码行,检查会话“地址”是否已存在的最佳方法是什么?
Address address = new Address();
model.addAttribute("address", address);
我使用了这种方法,但我想有一种使用Spring功能更好,更具体的方法。
@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);
}
}
谢谢
尝试使用@SessionAttribute批注从会话中检索现有属性。
@RequestMapping
public String welcome(@SessionAttribute("address") Address address) {
// something....
}
您可以使用@SessionAttribute
。
public String welcome(Model model, @SessionAttribute("address") Address addres) {
if(address == null){
Address address = new Address();
model.addAttribute("address", address);
}
return "welcome";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.