Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

java - Spring MVC - Multiple submit button to a Form

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" />

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 ?

Thanks!

question from:https://stackoverflow.com/questions/8954426/spring-mvc-multiple-submit-button-to-a-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

you may direct to different url request according to button pressed with one controller.

for cancel button,

@RequestMapping(params = "cancel", method = RequestMethod.POST)
public String cancelUpdateUser(HttpServletRequest request) {
    return "redirect:/users.html";
}

what request mapping does is to scan post request if it contains params name = cancel.

for save button,

@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.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...