java - Spring MVC : Is it necessary to test if a @ModelAttribute is null?

标签 java spring session spring-mvc modelattribute

我正在开发一个 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.annotationspring-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/

相关文章:

c# - 更新包装对象的最佳方法

java - Spring配置中的条件语句

java - 哪个 Datanucleus 日志记录级别最全面?

session - ELB 是基于 draining tcp 的吗?

php - php 中的安全 session /cookie

java - 使用 JDBC 进行日期过滤

javascript - 如何使用 testcafe 获取表中一列的文本,然后将其 eql 断言为 "something"

java - 我的程序中出现 IllegalStateException?

java - 如何从 JerseyTest 子类访问 Spring Bean

session - MVC SessionStateAttribute 不能用作全局属性