Handling Form Data In Spring MVC Controller

Any typical web application would include filling out a form and sending the data back into the application. Spring MVC Controllers are very well suited for the form processing jobs. They can be helpful in displaying the form as well the processing the data submitted by the form.


Accepting form data in the Spring MVC Controller

Using Spring MVC we can directly bind the form data to our model object without having to write any mappers to maps the form fields to the model object. All we need to do is to take care that the form field names are identical to the model object fields.

Let’s consider a simple registration form where the user inputs some basic details to register himself to the application.

<form action="register" method="post">
    <div>
        <label>First Name</label>
        <input type="text" name="firstName">
    </div>
    <div>
        <label>Last Name</label>
        <input type="text" name="lastName">
    </div>
    <div>
        <label>Date of Birth</label>
        <input type="date" name="dob">
    </div>
    <div>
        <label>Email ID</label>
        <input type="text" name="email">
    </div>
    <div>
        <label>Password</label>
        <input type="password" name="password">
    </div>
    <div>
        <label>Mobile</label>
        <input type="text" name="mobile">
    </div>
    <div><input type="submit" value="Submit"></div>
</form>

Our model class would look like as shown below. Notice that the form field names are identical to the model class field names.

public class User {

    private String firstName;    
    private String lastName;
    
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date dob;
    
    private String email;
    private String password;
    private Long mobile;

    ... getters and setters ...
}

@DateTimeFormat is used to specify the format of the date that would be send from the form.

Controller

The code snippet to accepts the form in the controller is shown below.

@RequestMapping(value="/register", method=RequestMethod.POST)
public String registerUser(User user){
    .. handle user object...
}

When we have as the User object as the parameter of the method that controller would be handling the request, Spring would handle binding of the from data into the user object. We get the user object populated by Spring and would be available in the controller method for further processing.

Spring would also handle the type casting of the fields to their respective types before binding the data. Hence the date of birth and mobile fields would be automatically cased to Date and Long types as specified in the User class.

Sending data back to the View

Now that we are done with accepting the user data in our application, let's consider the case of sending the data back to the view for displaying. 

Lets say we want to display the user's profile to a user who are already registered. In order to be able to access the model data in the view we need a way to send the user data to the view. Spring provides the 'org.springframework.ui.Model' class which can be used for sending model data to the view. We need to add the model object as an attribute of the org.springframework.ui.Model object.

@RequestMapping("/profile")
public String showProfile(@RequestParam String email, Model model){
    model.addAttribute("USER", userMap.get(email));
    return "profile";
}

Once we have the model object injected into the org.springframework.ui.Model object we have then access it in the jsp (view) using simple JSTL tags.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<h2><c:out value="${USER.firstName}" />'s Profile</h2> <div> <label>Name: </label> <c:out value="${USER.firstName}"/> <c:out value="${USER.lastName}"/> </div> <div> <label>Date Of Birth: </label> <fmt:formatDate pattern="yyyy-MM-dd" value="${USER.dob}"/> </div> <div> <label>Email ID: </label> <c:out value="${USER.email}"/> </div> <div> <label>Mobile: </label> <c:out value="${USER.mobile}"/> </div>

Download Source Code

You can download the source code of the Sample Spring Application discussed in this article.

POPULAR ARTICLES

Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article