Wednesday, July 6, 2011

SimpleFormController Example

SimpleFormController is used to handle form submissions using the Spring Framework. From Spring 3.0 onwards, SimpleFormController is deprecated. Add the @SupressWarnings annotation to the controller to remove any errors.

The following step by step approach helps you in creating a very simple SimpleFormController Example. This example takes four inputs from the user (firstName, lastName, age and hobbies). Prints them using the logger in the Controller class and returns the object for successful display.

1. The JSP file that takes the user input.

<%@ taglib uri="http://www.springframework.org/tags" prefix="tags"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Submit</title>
</head>
<body>

<form:form method="POST" commandName="user">

First Name : <form:input path="firstName" />
 <br>
Last Name : <form:input path="lastName" />
 <br>
Age : <form:input path="age" />
 <br>
Hobbies : <form:checkbox path="hobbies" value="Sports" label="Sports"/>
 <form:checkbox path="hobbies" value="Studies" label="Studies" />
 <br>
 <input type="submit" value="Submit" />
</form:form>
</body>
</html>

CommandName should be the same as the name provided in the Spring Configuration file that is described in the later sections.


2. The JSP file that displays the success message after the form gets submitted successfully.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Submit Success</title>
</head>
<body>
User Submitted Successfully.
<br>
First Name :
<c:out value="${user.firstName}"></c:out>
<br>
Last Name :
<c:out value="${user.lastName}"></c:out>
<br>
Age :
<c:out value="${user.age}"></c:out>
<br>
Hobbies:
<c:forEach items="${user.hobbies}" var="hobby">
 <c:out value="${hobby}"></c:out>, 
</c:forEach>
</body>
</html>

3. The bean object (User.class) in which the user details are stored while the form gets submitted.

package com.mybusiness.blueportal.beans;

public class User {

 private String firstName;
 private String lastName;
 private String age;
 private String[] hobbies;

 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 getAge() {
  return age;
 }

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

 public String[] getHobbies() {
  return hobbies;
 }

 public void setHobbies(String[] hobbies) {
  this.hobbies = hobbies;
 }
} 

4. The Controller class that receives the request when the form is submitted by the user.

package com.mybusiness.blueportal.controllers;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.mybusiness.blueportal.beans.User;

@SuppressWarnings("deprecation")
public class UserSubmitController extends SimpleFormController {
 
 private static final Logger LOG = Logger
   .getLogger(UserSubmitController.class.getName());

 @Override
 protected ModelAndView onSubmit(HttpServletRequest request,
   HttpServletResponse response, Object command, BindException errors)
   throws Exception {

  User user = (User) command;

  if (LOG.isLoggable(Level.INFO)) {
   LOG.info("UserName : " + user.getFirstName() + " "
     + user.getLastName() + ", Age: " + user.getAge()
     + ", Hobbies: " + user.getHobbies());
  }
  return new ModelAndView(getSuccessView(), "user", user);
 }
}

Spring takes care of mapping the request parameters to the command object (the bean object provided in the Spring configuration in the next step). So the bean object can be accessed directly with the values filled in already by the framework.

5. The Spring Configuration file that configures the SimpleFormController.
<bean name="/userSubmit.do" class="com.mybusiness.blueportal.controllers.UserSubmitController">
  <property name="sessionForm" value="true" />
  <property name="commandName" value="user" />
  <property name="commandClass" value="com.mybusiness.blueportal.beans.User" />
  <property name="formView" value="UserSubmit" />
  <property name="successView" value="UserSubmitSuccess" />
</bean>
formView:Tells the Spring Framework what web page has to get displayed when the user hits the URL for the first time
successView:Tells the Spring Framework what web page has to get displayed form submission is successful without any errors
commandClass:Tells the Spring Framework what bean object has to be used to map the variables on the web page
commandName:Tells the Spring Framework the name with which the request parameters are mapped in the web page

7 comments:

  1. Is it possible to implement Ajax validation using SimpleFormController. Or I should say can I call validator using Ajax.

    ReplyDelete
  2. Thanks a lot very much for the high your blog post quality and results-oriented help. I won’t think twice to endorse to anybody who wants and needs support about this area.
    rpa training in chennai

    ReplyDelete
  3. The young boys ended up stimulated to read through them and now have unquestionably been having fun with these things.
    JAVA Training in chennai

    ReplyDelete
  4. Thank you for sparing your time and knowledge with others.Good to see such an example.
    mobile service centre chennai

    ReplyDelete
  5. Hi, thank you very much for new information , i learned something new. Very well written. It was so good to read and usefull to improve knowledge. Keep posting. If you are looking for any python related information please visit our website
    python training in pune.

    ReplyDelete