Spring MVC Form handling Example

While developing a web application we usually come across some requirements that deal with capturing of data from the user in a form and then processing the same data on the server and returning any detailed result message to the user back.
In this article we will try out an example that uses html form along with spring mvc.

Spring MVC Form handling

In this example we will get employee details from the user and send it to the server.
1. Create a Spring Model

2. Contoller to handle the requests

In the getEmployee() method we set a empty Employee bean in the model with the name “command”.
Note that the command attribute needs to be set so that form tag in the jsp page uses the empty bean.

3. JSP page

For using the Form tag we need to add the tag libs as shown below
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

When user enters the data and submits the form, controller method addEmployee(@ModelAttribute("employee") Employee employee) is called.
The parameter passed is data filled in the form, mapped as Employee bean. You can process the data/ save data in database and then return the success/failure message to user.

Output
Open the empty form using http://localhost:8080/sampleproject/employee
Spring MVC Form handling

Submit the data once form is filled
Spring MVC Form handling

Download the Source Code : SpringMVC-Formhandling.zip

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn