【发布时间】:2011-06-18 12:25:08
【问题描述】:
Spring 3 MVC 使用控制器处理多个表单提交。
我正在开发具有多种形式的 JSP 页面。 1) 搜索客户,2) 搜索产品,3) 打印某些东西等。我有一个不同的表单绑定对象绑定到每个表单,我的控制器代码如下所示
@Controller
@RequestMapping(value="/search.do")
public class SearchController {
@RequestMapping(method = RequestMethod.GET)
public String pageLoad(ModelMap modelMap) {
modelMap.addAttribute("productSearch", new ProductSearchCriteria());
modelMap.addAttribute("customerSearch", new CustomerSearchCriteria());
modelMap.addAttribute("print", new PrintForm());
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView searchProducts(@ModelAttribute("productSearch") ProductSearchCriteria productSearchCriteria,
BindingResult result, SessionStatus status) {
//Do Product search
return modelAndView;
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView searchCustomers(@ModelAttribute("customerSearch") CustomerSearchCriteria customerSearchCriteria,
BindingResult result, SessionStatus status) {
//Do Customer search
return modelAndView;
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView printSomething(@ModelAttribute("print") PrintForm printForm,
BindingResult result, SessionStatus status) {
//Print something
return modelAndView;
}
}
上述方法肯定不像我想象的那样有效。我收到异常说'不支持请求方法'POST''。如果我在上面的控制器中只有一个 POST 方法说 searchProducts 它运行良好。但它不会使用超过一种 POST 方法。我还尝试在 JSP 中添加隐藏参数并更改类似于下面的方法签名,只是为了再次获得相同的异常。
@RequestMapping(method = RequestMethod.POST, params="pageAction=searchProduct")
public ModelAndView searchProducts(@ModelAttribute("productSearch") ProductSearchCriteria productSearchCriteria,
BindingResult result, SessionStatus status) {
//Do Product search
return modelAndView;
}
任何人都可以提出正确的方法来实现上述目标吗?此外,对源材料或进一步阅读的任何参考将不胜感激。谢谢。
编辑 #1: 只要您在 JSP 中正确获取隐藏参数,上述带有 params="pageAction=searchProduct" 的方法就可以完美地工作(请参阅下面的评论)。除此之外,@Bozho 和@Biju Kunjummen 的回答也非常有帮助,并且是处理多个表单提交的好(可能更好?)替代方案。
【问题讨论】:
-
您确定使用隐藏字段的方法不起作用吗?
-
确实如此。我很困惑为什么它不起作用。我在这里找到了类似的问题,并使用相同的 params="name=value" 技术进行了回答。许多人投了赞成票,这一定是解决这个问题的一种方法。
-
很奇怪,它应该可以工作。
-
@axtavt 搞定了。这是一个非常明显的错误,我想把自己埋在耻辱中。我的隐藏参数被定义为 它应该是 。你表达的怀疑让我一次又一次地重复它,直到它最终击中我。我没有足够的特权来投票给您,但非常感谢您的帮助。谢谢。
标签: spring-mvc jakarta-ee controller