Controller get method to handle form submit

When the user submits the form, the browser sends an HTTP POST request. Now let's create a method to handle this. To keep things simple, we will log the content of the form object. The complete listing of the method is as follows:

    @RequestMapping(value = "/create-user", method = 
RequestMethod.POST)
public String addTodo(User user) {
logger.info("user details " + user);
return "redirect:list-users";
}

A few important details are as follows:

  • @RequestMapping(value = "/create-user", method = RequestMethod.POST): Since we want to handle the form submit, we use the RequestMethod.POST method.
  • public String addTodo(User user): We are using the form backing object as the parameter. Spring MVC will automatically bind the values from the form to the form backing object.
  • logger.info("user details " + user): Log the details of the user.
  • return redirect:list-users: Typically, on submitting a form, we save the details of a database and redirect the user to a different page. Here, we are redirecting the user to /list-users. When we use redirect, Spring MVC sends an HTTP Response with status 302; that is, REDIRECT to the new URL. The browser, on processing the 302 response, will redirect the user to the new URL. While the POST/REDIRECT/GET pattern is not a perfect fix for the duplicate form submission problem, it does reduce the occurrences, especially those that occur after the view is rendered.

The code for list users is pretty straightforward and is listed as follows:

    @RequestMapping(value = "/list-users",  
method = RequestMethod.GET)
public String showAllUsers() {
return "list-users";
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset