I have a method in my AccountController like
@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
public String update(@ModelAttribute Account account) {
this.getAccountDao().save(account);
return "redirect:/users/account/";
}
I am using org.springframework.web.filter.HiddenHttpMethodFilter and so my view has a hidden form field as –
<form:form method="POST" modelAttribute="account">
<input type="hidden" name="_method" value="PUT" />
....
Now my question is how does the controller know when to Create a new Account or to Update it or how does it know if the request is a POST or a PUT? To me it always looks like it is going to be PUT.
I just don’t like using anything apart from GET and POST. The controller does not need to care whether it needs to create a new one or update it. If the form has a hidden account id field, the service can figure out what DAO method to call.
EDIT
If this is only going to be a PUT request then I would need to create a new jsp for POST. Unfortunately both requests are very similar in that they need almost exact data to be submitted, except for account id. I want to be able to use this same method from the controller and the same jsp for both POST and PUT and depending on either the model – account is saved or updated.
The controller doesn’t know if you create or update an entity, it only knows the
RequestMethods which the method reacts to.The hidden field you specified and the
HiddenHttpMethodFilteryou are using, result inPUTbeing the HTTP method, visible to your controller, as the filter changes the method in the request. (according to the javadocs).In result, the browser uses
POSTto transmit its data to the server, then theFilterruns and changes the method in the request toPUT, so for the application behind thatFilterit looks like the request had been sent withPUT.I don’t see a problem in being very similar code, just factor the similar behavoir out to another method.. eg: