我正在开发一个 Spring 3 项目,并始终检查 @ModelAttribute 是否为空,如果是,我将用户重定向到错误页面。
@Controller
@SessionAttributes({"myCommand"})
public class MyController {
@ModelAttribute("myCommand")
public MyCommand populate(HttpServletRequest request) {
return new MyCommand();
}
@RequestMapping(value="/user/saveFoo", method=RequestMethod.POST)
public String saveFoo(HttpServletRequest request, @ModelAttribute("myCommand") MyCommand myCommand) {
if(myCommand == null) {
// Add invalid session error here.
return "error.htm";
}
...
...
}
}
我想知道的是这个检查是否有必要。该命令是一个 session 属性,它是在必要时使用 Controller 的填充方法创建的。因此,只要 session 处于 Activity 状态,命令就永远不会为空。
我不知道 session 过期时会发生什么。 Controller 是否再次创建模型属性?如果是这样,那么无论 session 状态如何,命令对象都不能为空。
感谢您的帮助。
最佳答案
Spring MVC
为所有方法参数创建新实例,最大限度地减少 Controller 方法中出现空指针异常的潜在风险!
但请注意,这不适用于具有自定义 HandlerMethodArgumentResolver
的包装器类型和类它可以产生 null 作为返回值。
为了回答您的问题,即使 session 已过期,Spring MVC
也会实例化您的模型类的一个新实例。它永远不能为空!
引自 ModelAttributeMethodProcessor
文档:
Model attributes are obtained from the model or if not found possibly created with a default constructor if it is available.
如果没有默认构造函数可用 Spring MVC
抛出一个 BeanInstantiationException
异常
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [entity.Product]: No default constructor found
您可以安全地删除所有空指针检查。
要了解 Spring MVC
默认情况下可以在 Controller 方法中处理什么,您应该查看 spring-web
工件包中的代码和 javadoc org.springframework.web.method.annotation
和 spring-webmvc
包中的工件 org.springframework.web.servlet.mvc.method.annotation
.
关于java - Spring MVC : Is it necessary to test if a @ModelAttribute is null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24569287/