Spring MVC Form Example

Reading Time: 3 minutes

In this tutorial I will show you how to create a simple form using Spring 3 MVC Web framework. I have checked other examples regarding creation of forms in Spring MVC Framework, there are many ways of achieving it. With the simplicity  of Spring MVC version 3, we are easing our forms to be implemented on forms. Especially we enjoy coding forms in spring avoiding definition of each command name or anything on xml configuration file. So let’s get started to Spring forms! We are creating a simple project adds and lists as many users as you enter. Also the project is on my Github as well, you may download the entire project

First of all we need essentially our POJO class, the below we are creating one

User.java

package com.tugrulaslan.domain;

/**
 * Created by Tugrul on 19.02.2014.
 */
public class User {

    private String firstName;
    private String lastName;
    private String email;
    private Integer age;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

MainController.java

package com.tugrulaslan.controller;

import com.tugrulaslan.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tugrul on 19.02.2014.
 */
@Controller
public class MainController {

    private List<User> allUserList = new ArrayList<User>();

    @RequestMapping(value = "/user-form")
    public ModelAndView personPage(){
        return new ModelAndView("user-page", "userCommand", new User());
    }

    @RequestMapping(value = "/addUser")
    public ModelAndView processPerson(@ModelAttribute User user){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user-result-page");
        modelAndView.addObject("user", user);
        allUserList.add(user);
        return modelAndView;
    }

    @RequestMapping(value = "/listUsers")
    public ModelAndView listAllPerson(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user-list");
        modelAndView.addObject("users",allUserList);

        return modelAndView;
    }
}

Here is the important point what we need to focus on “userCommand” in “personPage”, we need to combine and link our controller to the desired form area, also the form variables need to be hooked up with the domain object, on the 3rd parameter we are sending a new class of User POJO the below evaluate the

user-page.jsp

<%--
  Created by IntelliJ IDEA.
  User: Tugrul
  Date: 19.02.2014
  Time: 11:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
    <title>Person Form</title>
</head>
<body>
<form:form method="post" commandName="userCommand" action="addUser.html">
    <table>
        <tbody>
        <tr>
            <td><form:label path="firstName">Firstname: </form:label></td>
            <td><form:input path="firstName" /></td>
        </tr>
        <tr>
            <td><form:label path="lastName">Lastname: </form:label></td>
            <td><form:input path="lastName" /></td>
        </tr>
        <tr>
            <td><form:label path="email">Email: </form:label></td>
            <td><form:input path="email" /></td>
        </tr>
        <tr>
            <td><form:label path="age">Age: </form:label></td>
            <td><form:input path="age" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Add User" />
            </td>
        </tr>
        </tbody>
    </table>
</form:form>

</body>
</html>

As we see the simple form here, we have combined our controller and User POJO class with each other to provide the communication.

user-list.jsp

<%--
  Created by IntelliJ IDEA.
  User: Tugrul
  Date: 19.02.2014
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Person List</title>
</head>
<body>
<h1>User List</h1>
<c:if test="${not empty users}">
    <table border="1">
        <tr>
            <td>Firstname</td>
            <td>Lastname</td>
            <td>Email</td>
            <td>Age</td>
        </tr>
        <c:forEach var="element" items="${users}">
            <tr>
                <td>${element.firstName}</td>
                <td>${element.lastName}</td>
                <td>${element.email}</td>
                <td>${element.age}</td>
            </tr>
        </c:forEach>
    </table>
</c:if>
<a href="/">Index</a><br />
</body>
</html>

Here we are listing all registered and stored users in our list defined in our controller class

user-result-page.jsp

<%--
  Created by IntelliJ IDEA.
  User: Tugrul
  Date: 19.02.2014
  Time: 11:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Person Result Page</title>
</head>
<body>
<h1>Created User Details</h1>
<p><b>First Name:</b> ${user.firstName}</p>
<p><b>Last Name:</b> ${user.lastName}</p>
<p><b>Email:</b> ${user.email}</p>
<p><b>Age:</b> ${user.age}</p>
<a href="/">Index</a>
</body>
</html>

where we show the outcome what the user has entered

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Tugrul
  Date: 19.02.2014
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<html>
<body>
<h2>===Main Menu===</h2>
</body>
<a href="/user-form">Add a New User</a><br />
<a href="/listUsers">List All Users</a>
</html>

Web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
               xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
               xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"
               xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
               xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        				http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        				http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:component-scan
        base-package="com.tugrulaslan.controller" />

<bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:annotation-driven />

</beans>

pom.xml

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.tugrulaslan</groupId>
    <artifactId>SpringFormExample</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringFormExample Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <org.springframework.version>3.2.6.RELEASE</org.springframework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${org.springframework.version}</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>SpringFormExample</finalName>
    </build>
</project>