我的大多数控制器都有重复的代码,如下所示。
@RequestMapping(value = "process1/add.do", method = RequestMethod.POST)
public String add(@ModelAttribute("obj1") @Valid Object1 obj1,
ModelMap modelMap, HttpServletRequest request) {
String tp = request.getParameter("tp");
String co = request.getParameter("co");
String a = request.getParameter("a");
String successUrl = "process2/add.do?tp" + tp + "&co=" + co;
String failureUrl = "process1/list.do?tp" + tp + "&co=" + co;
try {
obj1.setType(tp);
obj1.setCode(co);
obj1.setValue(a);
process1Service.add(obj1, a);
return "redirect:successUrl";
} catch (Exception e) {
return "redirect:failureUrl";
}
}
@RequestMapping(value = "process2/add.do", method = RequestMethod.POST)
public String add(@ModelAttribute("obj2") @Valid Object2 obj2,
ModelMap modelMap, HttpServletRequest request) {
String tp = request.getParameter("tp");
String co = request.getParameter("co");
String successUrl = "process3/add.do?tp" + tp + "&co=" + co;
String failureUrl = "process2/list.do?tp" + tp + "&co=" + co;
try {
obj2.setType(tp);
obj2.setCode(co);
process2Service.add(obj2);
return "redirect:successUrl";
} catch (Exception e) {
return "redirect:failureUrl";
}
}
我在这里省略了get-methods,因为很容易猜到它们是怎样的。 关键是几乎我的post-methods甚至get-methods都获得了名为“tp”和“co”的url参数。 有没有什么好主意可以避免写重复代码?