Reputation: 181
I am developing Web Application in Java using Spring Framework. On one page, I am letting user pick year. Here is the code:
@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;
}
}
This implementation works, but I would like to use something simplier to get year from the user. I think making special model just to get one integer is not very good approach.
So, my question is: Is it possible to somehow simplify this code?
Thank you for any help. Milan
Upvotes: 0
Views: 885
Reputation: 25613
Indeed you just need to store the integer, you don't need to create a whole new special class to hold it
@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
}
}
What you could instead (if possible) is rework your view so that you can use @RequestParam
to pass directly an integer to your method pickYear
rendering it into the view so that this parameter could be passed onto the second method processYear
in the same way.
@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
}
}
Upvotes: 1
Reputation: 597432
Usually you use the model to pass data from controller to view, and you use @RequestParam
to get data from a submitted form in a controller. Meaning, your POST method would look like:
public String processYear(@RequestParam("year") int year) {
// Processing
}
Upvotes: 4