【问题标题】:@RequestParam is null when accessed in @ModelAttribute method在@ModelAttribute 方法中访问时@RequestParam 为空
【发布时间】:2011-05-31 23:55:43
【问题描述】:

我正在使用一个项目,用户可以选择从新的表单提交开始,或者继续他们之前开始的表单提交。我正在使用 @ModelAttribute 表示法为新表单提交生成新对象。这很有效。现在我试图从数据库中获取信息,以根据给定的 id 在对象中预填充信息,但我遇到了障碍。我正在尝试使用 @RequestParam 获取使用表单提交传入的 id,但 id 正在返回 null。我可以看到 id 作为请求字符串的一部分发送,但它没有发送到 @ModelAttribute 方法。这是我目前所拥有的。

提交以发送 regId 以便可以预先填充表单的表单

<form id="preregistration" action="/Homepage/Pre-Registration" method="post">
<input type="text" name="view" id="view" value="preprocess"/>
<select name="regId" id="regId">
    <option value="0">Select</option>
    <option value="1234">1234</option>
    <option value="4567">4567</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit"/>
</form>    

模型属性方法

@ModelAttribute("event")
public Event createDefaultEvent(@RequestParam(required = false) Integer regId){
    log.debug("regId: {}", regId);
    if (regId == null){
        log.debug("make new event object");
        return new Event();
    } else {
        log.debug("retrieve event with id: {}", regId);
        return eventDao.get(regId);
    }
}    

请求映射方法

@RequestMapping(params = "view=preprocess")
public String getPreProcessInformation(@ModelAttribute("event") Event event)
    throws Exception{
        return "redirect:/preregistration.do?"+Page.EVENT.getView();
}

当我提交表单时,谁能帮我弄清楚为什么我的 regId 在@ModelAttruibute 方法中为空?提前致谢!

【问题讨论】:

    标签: java spring-mvc modelattribute


    【解决方案1】:

    你需要告诉它你想读入的参数的名字是什么:

    @RequestParam(value="regId", required = false)
    

    方法参数的名称不能在运行时通过反射获得。 Spring无法确定您在Java代码中将参数命名为“regId”,您需要告诉它。

    编辑:

    还有一些更学术的漫谈,ModelAttribute 方法最适合用于提供固定在您正在构建的视图范围内的参考数据。您计划将表单字段绑定到的事务项通常应该由实际的请求处理程序方法生成。如果您使用 OpenSession/EntityManagerInView 过滤器和/或 @SessionAttributes 注释,这将变得尤为重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2011-05-19
      • 2013-09-09
      • 1970-01-01
      • 2020-05-05
      相关资源
      最近更新 更多