0

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");
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Beny Xu
  • 39
  • 1
  • 6

3 Answers3

3

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);  

}
Jayendra
  • 52,349
  • 4
  • 80
  • 90
  • ok so basically all I have to do is create another method to handle GET request. I'll try it tomorrow since the project is in my office pc. – Beny Xu Nov 14 '12 at 13:35
  • yes .. just have a controller method to act on the HTTP GET request – Jayendra Nov 14 '12 at 14:41
1

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.

Muhammad Imran Tariq
  • 22,654
  • 47
  • 125
  • 190
0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Willy
  • 1,828
  • 16
  • 41