我是Spring的新手,我設法從JSP視圖中的表單中收集數據並將我的表單提交給控制器。從視圖獲得性的數據,我實例化一個模型對象,其中還包含其他模型對象:如何在Spring Controller方法中從多個@RequestParam參數切換到@ModelAttribute
@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)?
謝謝。
只爲未來的讀者提供一個提示:你也可以創建一個與參數同名的setter(*例如*'public void setAction(private String action){}'),它將通過Spring自動調用。這樣您就不會受限於請求對象中的請求參數名稱(*即* FormResults)。例如,你可以有一個'private String lastAction'來代替 - 只需在setter中設置它。 –