Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何检查使用@SessionAttributes创建的会话是否存在(Spring MVC)_Java_Spring Mvc_Session - Fatal编程技术网

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–错误请求?