Java 如何检查使用@SessionAttributes创建的会话是否存在(Spring MVC)
请看下面的代码:Java 如何检查使用@SessionAttributes创建的会话是否存在(Spring MVC),java,spring-mvc,session,Java,Spring Mvc,Session,请看下面的代码: @Controller @RequestMapping @SessionAttributes("address") public class HomeController { @RequestMapping("/home") public String welcome(Model model) { Address address = new Address(); model
@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”时,就会调用欢迎()方法,创建一个新对象地址,将其添加到模型中,并将其保存在名为地址的会话中
@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);
}
检查会话“地址”是否已经存在以避免执行这行代码的最佳方法是什么
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);
}
}
谢谢尝试使用注释从会话检索现有属性
@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";
}
如果那个会话还不存在呢?有没有办法防止该方法返回错误:HTTP状态400–错误请求?我想您应该检查一下。如果(!model.containsAttribute(“address”){…}这个会话还不存在怎么办?有没有办法防止该方法返回错误:HTTP状态400–错误请求?