0

我正在使用一个项目,用户可以选择从新的表单提交开始,或者继续他们之前开始的表单提交。我正在使用 @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 方法中为空?提前致谢!

4

1 回答 1

3

您需要告诉它您要读取的参数的名称是什么:

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

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

编辑:

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

于 2011-06-01T00:43:14.920 回答