我正在使用一个项目,在该项目中,用户可以选择从新的表单提交开始,也可以继续以前开始的表单提交。我正在使用@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方法中为null吗?提前感谢!
您需要告诉它您想要读取的参数的名称是什么:
@RequestParam(value="regId", required = false)
方法参数的名称在运行时不能通过反射获得。Spring不知道你在java代码中把参数命名为"regId",你需要告诉它
编辑:
此外,一些更具学术性的漫无边际的ModelAttribute方法最适合用于提供在您正在构建的视图范围内固定的参考数据。计划将表单字段绑定到的事务项通常应由实际的请求处理程序方法生成。如果使用OpenSession/EntityManagerInView筛选器和/或@SessionAttributes注释,这一点将变得格外重要。