Reputation: 39
I just started learning spring mvc 3. I found a small problem where my controller would handle a post request (registration form). but if type the mapping value (bla3/save.html) in address bar, it will execute the method which it shouldn't. That's why I need a solution for this, if someone type the address directly, it should redirect to other pages instead trying to add new user.
@RequestMapping(value = "/save", method = RequestMethod.POST) //save new user
public ModelAndView saveUser(@ModelAttribute("user") User user, BindingResult result){
userService.addUser(user);
return new ModelAndView("redirect:/users.html");
}
Upvotes: 0
Views: 2768
Reputation: 1838
You can let the method only be executed only when there are specific headers like below code.
@RequestMapping(value = "/save", method = RequestMethod.POST, headers="X-Requested-With=XMLHttpRequest")
In this case the method is only be executed when it is an jquery ajax request (jQuery automatically adds the header)
Of course it is just kind of Poka-yoke
Upvotes: 0
Reputation: 23352
Add this method in your controller class.
@RequestMapping(value = "bla3/save", method = RequestMethod.GET)
public ModelAndView saveUser(@ModelAttribute("user") User user, BindingResult result){
userService.addUser(user);
...
return new ModelAndView("redirect:/users.html");
}
If type the mapping value (bla3/save.html) in address bar. This method will execute.
Upvotes: 1
Reputation: 52809
If you have the URL directly in the address bar it would be a GET request for which you can handle a different behaviour e.g. GET is prohibited for this URL or render the blank form for the User on the submission of which the POST method will be called upon.
@RequestMapping(value = "/save", method = RequestMethod.GET)
public ModelAndView saveUser(@ModelAttribute("user") User user, BindingResult result){
userService.addUser(user);
}
Upvotes: 3