In Spring MVC (I work with 3.0.2), two HTTP methods: always (or, for the most part, it seems to me) are reserved (i.e. mapped to the corresponding handlers) that are GET and POST , for example
@RequestMapping(method=RequestMethod.GET) public String showForm(Map model) { //Usually retrieve data from the database when the page is loaded. return "admin_side/Temp"; }
The above method is called when a GET request is executed.
@RequestMapping(method=RequestMethod.POST) public String onSubmit(@ModelAttribute("tempBean") @Valid TempBean tempBean, BindingResult error, Map model, HttpServletRequest request, HttpServletResponse response) { //Perform some basic operations with the database like insert, update or delete when the form is submitted (by clicking a submit button or so). return "admin_side/Temp"; }
The above method is called when the POST request is executed. Assuming the Spring controller is indicated by the @RequestMapping(value="admin_side/Temp") annotation.
Now, what happens if I need to use Ajax and I need to perform various functions, than the previous methods do? I can not handle another method of using the GET method and the POST method, because it is already processed handlers (both HTTP method, GET and POST methods of treatment reserved for showForm() and onSubmit() , respectively).
For demonstration, I used the method=RequestMethod.PUT approach with Ajax , for example
@RequestMapping(method=RequestMethod.PUT) public @ResponseBody String getStateList(@ModelAttribute("tempBean") @Valid TempBean tempBean, BindingResult error, HttpServletRequest request, HttpServletResponse response) { return "Message"; }
and he worked as intended, but I felt that this was the best not . How do you handle Ajax requests in Spring MVC if you have such a scenario (in fact, it seems to me that this is a fairly common occurrence)? Should I (always) use RequestMethod.PUT ? (or is the best HTTP method for Ajax in Spring?)
Is there a way to map multiple methods to the same HTTP method in the same controller (the obvious answer should be no )? Again, what approach do you use when you need to work with Ajax in Spring MVC? I hope you understand what I mean! It is very difficult for me to express that my English is in its infancy.