Spring Simple Form Controller

A Simple Form Controller is a controller class used for handling request submitted from a form in UI. It also contains methods to provide default data to the form, when it is displayed in UI.

The unique feature of SimpleFormController is it allows form views and success view to be handled decoratively compared to AbstractFormController.

Lets see a simple example of creating a User Details Form to use Simple Form Controller. It will contain fields such as User Name, Age and a Submit button. It will also contain current date on top of the page.

Create a custom controller as follows

UserFormController Class

public class UserFormController extends SimpleFormController
{
    private ModelMap modelMap = new ModelMap();

    public UserFormController()
    {
        setCommandClass(User.class);
        setCommandName("user");
    }

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception
    {
        User user = (User) command;
        ModelAndView mv = new ModelAndView(getSuccessView(), "user", user);
        return mv;
    }

    protected Map referenceData(HttpServletRequest request) throws Exception
    {
        modelMap.put("date", new Date());
        return modelMap;
    }
}

The user bean should be created prior to using it in our custom controller

User Bean Class

public class User implements Serializable
{
    private static final long serialVersionUID = -7320233902190166054L;

    public User()
    {
    }

    private String userName;

    private int    age;

    public String getUserName()
    {
        return userName;
    }

    public void setUserName(String userName)
    {
        this.userName = userName;
    }

    public int getAge()
    {
        return age;
    }

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

The referenceData(...) method returns a Map. It adds a key "data" to the map so
that current date can be displayed in UI.

protected Map referenceData(HttpServletRequest request) throws Exception
{
    modelMap.put("date",new Date());
    return modelMap;
}

When the form is submitted in UI, the onSubmit(..) method in UserFormController
will be executed. It returns a ModelAndView object, which should contains the view which is to be displayed and corresponding model details.

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception
    {
        User user = (User) command;
        ModelAndView mv = new ModelAndView(getSuccessView(), "user", user);
        return mv;
    }

The Spring configuration file for declaring the handler mappings and beans as follows

userForm-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd" >
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<description> This bean adds prefix and suffix to the view returned from any controller
</description>
<property name="prefix"><value>/WEB-INF/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<!-- URL and Corresponding Controller mapping to come here
For Example, when a request comes from the browser with url "index.htm"
it will be mapped to UserFormController.
-->
<property name="urlMap">
<map>
<entry key="/" value-ref = "userFormController "/>
<entry key="/index.htm" value-ref = "userFormController "/>
</map>
</property>
</bean>
<bean id="userFormController" class="in.techdive.UserFormController ">
<description> This controller bean contains formView and successView properties
FormView will be returned from referenceData(..) method, which will in turn
me returning to index.jsp view. successView is usually returned from onSubmit() method.
</description>
<property name="formView" value="index" />
<property name="successView" value="welcome" />
</bean>
</beans>

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>
Today is ${date}
<br>
<br>
Please provide user details
<br>
<pre>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="userName" ></form:input></td>
</tr>
<tr>
<td>Age :</td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="submit"></td>

</tr>
</table>
</form:form>
</pre>
</body>
</html>

Have a look at the welcome.jsp file. It will just display the user name and age which are submitted in the form in index.jsp

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<form:form method="POST" commandName="user">
User Name is ${user.userName} <br>
Age is ${user.age}
        </form:form>
</body>
</html>

The following is the entry to be made in web.xml file

web.xml changes

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringSimpleController</display-name>
<servlet>
<servlet-name>userForm</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/userForm-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>userForm</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- This is for Displaying the Index html page -->
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
</web-app>

The org.springframework.web.servlet.DispatcherServlet servlet will be loaded initially when the application is started. It loads beans from /WEB-INF/userForm-servlet.xml which is specified inside the tag. Usually the context configuration file should be of the form -servlet.xml.

In this way SimpleFormController can be used in a Spring application.

Technology: 

Search