Spring MVC Fast Tutorial: displaying and processing a form

What are we going to build?

A form to create a new car.

When the form is submitted, we will create a new Car object and redirect the user to the car list page.

Add a new method to the service class

Add a method to add a car in the CarService class:

public void add(Car car) {
	carList.add(car);
}

Add a controller method to display the form

In CarController, add a method to display the form:

@RequestMapping("/car/add")
public void carAdd() {
}

The implicit view name for this controller method is car/add (based on the route). Because of the JSP view resolver declared in the AppConfig class, the /WEB-INF/jsp/car/add.jsp file will be used as view.

Add a JSP with the form

Create /WEB-INF/jsp/car/add.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 
<h1>Add a car</h1>
 
<form:form method="POST">
	<p>
		Name:
		<input type="text" name="name" />
	</p>
	<p>
		Price:
		<input type="text" name="price" />
	</p>
 
	<input type="submit" />
</form:form>

It's a standard HTML form which will be submitted to the URL of the current page /car/add. Spring <form:form> tag is not necessary here (we could have used a standard <form>, but it will be for the next part of the tutorial (validating the form).

Add a controller method to process the form

In CarController, add a method to process the form when it's submitted:

@RequestMapping(value="/car/add", method=RequestMethod.POST)
public String carAddSubmit(@ModelAttribute Car car) {
	carService.add(car);
	return "redirect:/car/list";
}

This method will be called when the form is submitted because of method=RequestMethod.POST (when the form is displayed, GET is implicitly used).

The form fields will be automatically mapped to the corresponding attributes of the @ModelAttribute object. For example, the form field price will be mapped to the price attribute of the Car object.

We then add the new car to the car list and redirect to the car list page.

Test wether it's working

Summary

We've built:

  • a controller method to display a form
  • a form (in a JSP file)
  • a controller method to process the form when it's submitted.

The source code is available on GitHub.

Next: Validate a form
Previous: Build a Spring MVC web application
Up: Spring MVC Fast Tutorial

Feedback