![](/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.