我刚开始使用Spring,我已经设法从JSP视图中的表单中收集数据并将表单提交给控制器。从视图中获取的数据中,我实例化了一个模型对象,该对象还包含其他模型对象:
@RequestMapping(value = "/updateEntry", method = RequestMethod.GET)
public RedirectView updateAction(ModelAndView model,
@RequestParam(value = "name", defaultValue = "none") String selectedWaveName,
@RequestParam(value = "id", defaultValue = "-1") int id,
@RequestParam(value = "function", defaultValue = "none") String function,
@RequestParam(value = "evidence", defaultValue = "none") String evidence,
@RequestParam(value = "action", defaultValue = "none") String action,
@RequestParam(value = "topicId", defaultValue = "-1") int topicId,
@RequestParam(value = "topic", defaultValue = "none") String topic,
@RequestParam(value = "topicDesc", defaultValue = "none") String topicDesc,
@RequestParam(value = "waveId", defaultValue = "-1") int waveId,
@RequestParam(value = "waveStart", defaultValue = "none") String waveStart,
@RequestParam(value = "waveEnd", defaultValue = "none") String waveEnd)
throws ParseException {
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date dateStart = formatter.parse(waveStart);;
Date dateEnd = formatter.parse(waveEnd);
waveDAO.updateFormResults(new FormResults(id,
new Topic(topicId, topic, topicDesc),
new Wave(waveId, selectedWaveName, dateStart, dateEnd),
evidence, action, function));
return new RedirectView("/hr/?name=" + selectedWaveName);
}
如何使用@ModelAttribute用更少的行替换整个@RequestParam行? 我是否还需要将@ModelAttribute注释添加到模型类(FormResults,Topic,Wave)?
感谢。
答案 0 :(得分:3)
@ModelAttribute
。我通常做的事情(但可能对你的情况不利)是一个包含所有这些数据的对象:
@RequestMapping(value = "/updateEntry", method = RequestMethod.GET)
public RedirectView updateAction(ModelAndView model, Options options) throws ParseException {
...
}
public static class Options {
private String selectedWaveName,
private int id,
...
// Getters and setters
}
答案 1 :(得分:1)
ModelAttribute注释最终确实起作用,我发现在使用这个注释时,你从前端传递的变量(在我的例子中来自JSP页面)应该与声明的属性具有完全相同的名称。你是模特班!
例如,如果你有一个类似的模型类:
public class FormResults {
private int id;
private Topic topic;
private Wave wave;
private String evidence;
private String action;
private String manager;
... }
此外,您需要所有类属性的getter和setter方法,以及默认构造函数!
您从JSP页面发送到使用@ModelAttribute注释的控制器方法的变量将命名为:
<input type="text" name="id" ...
<input type="text" name="evidence" ...
<input type="text" name="action" ....
<input type="text" name="manager" ...
这也适用于你有一个复杂的对象,它有另一个对象作为属性(就像我的情况:Topic,Wave)。 您所要做的就是使用类名前缀命名这些输入:ex:topic,wave,后跟那些类属性,例如:topic.id,wave.id ......
这是我的控制器方法的签名:
@RequestMapping(value = "/updateEntry", method = RequestMethod.GET)
public ModelAndView updateAction(ModelAndView model,
@ModelAttribute("fr") FormResults fr) throws ParseException {
...}
Spring会自动创建一个FormResults对象。就是这样! :)