Beny Xu Beny Xu - 6 months ago 49
Java Question

spring mvc prevent direct access a method

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

Answer

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

}
Comments