问题描述
我正在尝试将 2 个提交按钮发布到表单,每个按钮操作映射到不同的控制器.这是我的映射
I am trying to have 2 submit buttons post to a form, with each button action mapped to different controllers. Here are my mappings
@RequestMapping(value="/save", method=RequestMethod.POST, params="save")
@RequestMapping(value="/save", method=RequestMethod.POST, params="renew")
我的提交按钮看起来像这样 -
And my submit buttons look like these -
<input type="submit" name="save" class="button" value="Save" />
<input type="submit" name="renew" class="button" value="Renew" />
正如您从我的映射中看到的,我依赖于使用参数来区分点击了哪个按钮.问题是它在 90% 的时间内都可以工作,但有时我会遇到以下异常 -
As you can see from my mapping, I am relying on the use of params to differentiate what button was clicked on. The problem is that it works 90% of the time but sometimes I get the exception below -
java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8090/myapp/save': {public java.lang.String com.myapp.SaveController.save(MyEntity,javax.servlet.http.HttpSession), public java.lang.String com.myapp.SaveController.saveAndRenew(MyEntity,javax.servlet.http.HttpSession)}
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:248)
org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:194)
奇怪的是,当发生这种情况并且我重新提交页面时,之后一切正常.有没有更好的方法来实现我想要做的事情?
Strangely, when this happens and I re-submit the page, everything works fine afterwards. Is there a better way to achieve what I'm trying to do ?
谢谢!
推荐答案
如果表单指定了这些按钮:
if the form has these buttons specified:
input type="submit" class="button" name="save" value="Save"
input type="submit" class="button" name="delete" value="Delete"
input type="submit" class="button" name="cancel" value="Cancel"
您可以根据一个控制器按下的按钮指向不同的 url 请求.
you may direct to different url request according to button pressed with one controller.
对于取消按钮,
@RequestMapping(params = "cancel", method = RequestMethod.POST)
public String cancelUpdateUser(HttpServletRequest request) {
return "redirect:/users.html";
}
请求映射的作用是扫描 post 请求,如果它包含参数 name = 取消.
what request mapping does is to scan post request if it contains params name = cancel.
保存按钮,
@RequestMapping(params = "save", method = RequestMethod.POST)
public String saveUser(HttpServletRequest request, @ModelAttribute User user, BindingResult result, SessionStatus status) {
// validate your result
// if no errors, save it and redirect to successView.
}
这篇关于Spring MVC - 一个表单的多个提交按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!