In Spring MVC (I'm working with 3.0.2), two HTTP methods are always (or mostly as it seems to me) reserved (i.e. mapped with appropriate handlers) which are GET and POST such as
@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 invoked when a GET request is made.
@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 invoked when a POST request is made. Assuming that the Spring controller is designated with the @RequestMapping(value="admin_side/Temp") annotation.
Now, what happens, if I need to use Ajax and I need to perform different functionality than the preceding methods do? I can neither handle another method with the GET method nor with the POST method because there are already handlers mapped (both the HTTP methods, GET and POST are reserved to handle the showForm() and onSubmit() methods respectively).
For the sake of demonstration, I used the method=RequestMethod.PUT approach with Ajax such as
@RequestMapping(method=RequestMethod.PUT)
public @ResponseBody String getStateList(@ModelAttribute("tempBean") @Valid TempBean tempBean, BindingResult error, HttpServletRequest request, HttpServletResponse response)
{
return "Message";
}
and it worked as intended but I felt it should not be the best solution. How do you handle Ajax requests in Spring MVC, if you have such a scenario (actually, it seems to be quite usual to me)? Should I (always) use RequestMethod.PUT? (or what is the best HTTP method for Ajax in Spring?)
Is there a way to map more than one method with same HTTP method in the same controller (an obvious answer should be no)? Again, which approach do you use when you need to work with Ajax in Spring MVC? Hope you follow what I mean! It's quite difficult for me to express as my English is at the very initial stage.