[英]Spring MVC Web Application - proper use of Model
我正在使用Spring Framework用Java開發Web應用程序。 在一頁上,我讓用戶選擇年份。 這是代碼:
@Controller
public class MyController {
@RequestMapping(value = "/pick_year", method = RequestMethod.GET)
public String pickYear(Model model) {
model.addAttribute("yearModel", new YearModel);
return "pick_year";
}
@RequestMapping(value = "/open_close_month_list", method = RequestMethod.POST)
public String processYear(Model model, @ModelAttribute("yearModel") YearModel yearModel) {
int year = yearModel.getYear();
// Processing
}
}
public class YearModel {
private int year;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
此實現有效,但我想使用更簡單的方法從用戶那里獲得幫助。 我認為僅僅為了得到一個整數而制作特殊模型並不是很好的方法。
因此,我的問題是:是否可以以某種方式簡化此代碼?
感謝您的任何幫助。 米蘭
通常,您使用模型將數據從控制器傳遞到視圖,並使用@RequestParam
從控制器中的提交表單獲取數據。 意思是,您的POST方法如下所示:
public String processYear(@RequestParam("year") int year) {
// Processing
}
實際上,您只需要存儲整數,就不需要創建一個全新的特殊類來保存它
@Controller
public class MyController {
@RequestMapping(value = "/pick_year", method = RequestMethod.GET)
public String pickYear(ModelMap model) {
model.addAttribute("year", 2012);
return "pick_year";
}
@RequestMapping(value = "/open_close_month_list", method = RequestMethod.POST)
public String processYear(@ModelAttribute("year") int year) {
// Processing
}
}
相反,您可以(如果可能)對視圖進行重做,以便可以使用@RequestParam
將整數直接傳遞給方法pickYear
將其呈現到視圖中,以便可以以相同的方式將此參數傳遞給第二個方法processYear
。
@Controller
public class MyController {
// In the pick_year view hold the model.year in any hidden form so that
// it can get passed to the process year method
@RequestMapping(value = "/pick_year", method = RequestMethod.GET)
public ModelAndView pickYear(@RequestParam("year") int year) {
ModelAndView model = new ModelAndView("pick_year");
model.addAttribute("year", 2012);
return model;
}
@RequestMapping(value = "/open_close_month_list", method = RequestMethod.POST)
public String processYear(@RequestParam("year") int year) {
// Processing
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.