如何在Spring Controller方法中从许多@RequestParam参数切换到@ModelAttribute

我刚开始使用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)?

谢谢.

最佳答案
这里不需要@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
}

转载注明原文:如何在Spring Controller方法中从许多@RequestParam参数切换到@ModelAttribute - 代码日志