我是春天的新人。我有以下控制器:
1) 将参与方添加到数据库的简单控制器。
@Controller
@RequestMapping("/party")
@SessionAttributes()
public class PartyController {
@RequestMapping(value = "/new", method=RequestMethod.GET)
public ModelAndView newPartyGet(@ModelAttribute("party")
Party party, BindingResult result) throws IOException{
ModelAndView mav = new ModelAndView("/views/party/party_add.jsp", "party", party);
return mav;
}
@RequestMapping(value = "/new", method=RequestMethod.POST)
public String newPartyPost(@ModelAttribute("party") Party party,
HttpServletRequest req) throws IOException{
if (party.validate()) {
//here is called servlet, which add party to google app engine database
return "forward:/partyadd";
} else {
party.fromRequest(req);
return "/views/party/party_add.jsp";
}
}
2) 相同,但有比赛。
@Controller
@RequestMapping("/party/{id}/contest")
@SessionAttributes()
public class ContestController {
@RequestMapping(value = "/new", method=RequestMethod.GET)
public ModelAndView newContestGet(@ModelAttribute("contest")
Contest contest, BindingResult result) throws IOException{
ModelAndView mav = new ModelAndView("/views/contest/contest_add.jsp", "contest", contest);
return mav;
}
@RequestMapping(value = "/new", method=RequestMethod.POST)
public String newContestPost(@ModelAttribute("contest") Contest contest,
HttpServletRequest req) throws IOException{
if (contest.validate()) {
//here is called servlet, which add contest to google app engine database
return "forward:/contestadd";
} else {
party.fromRequest(req);
return "/views/contest/contest_add.jsp";
}
}
还有更多,添加探针或参与者。
这些控制器之间的差异并不明显,所以我想用两种方法编写一个控制器,让我可以提供这种形式。
可能吗?
好的,我看到我没有很好地解释我想说的话。
我有很多控制器,都看起来像这样:
@Controller
@SessionAttributes()
public class MyObjectController {
@RequestMapping(value = "/new", method=RequestMethod.GET)
public ModelAndView MyObjectGet(@ModelAttribute("myObject")
MyObject myObject, BindingResult result) throws IOException{
ModelAndView mav = new ModelAndView("/views/myObject_add.jsp", "myObject", myObject);
return mav;
}
@RequestMapping(value = "/new", method=RequestMethod.POST)
public String MyObjectPost(@ModelAttribute("myObject") MyObject myObject,
HttpServletRequest req) throws IOException{
if (myObject.validate()) {
//here is called servlet, which add myObject to google app engine database
return "forward:/myObjectadd";
} else {
myObject.fromRequest(req);
return "/views/myObject_add.jsp";
}
}
其中“myObject”可以是竞赛、参与者等。通常我可以对所有事情重复这个代码很多次,但我认为有更好的解决方案。