Wednesday 29 January 2014

Spring MVC form handling example

In this tutorial, we show you how to develop a Spring MVC form handling example.




Create New Dynamic Web Project in Eclipse with folder Structure as shown below.





Below is the Content for pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  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.mahesh.common</groupId>
  <artifactId>SpringMVC</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringMVC Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
    </repositories>
 
  <dependencies>
   
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
   
    <!-- Spring framework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>

    <!-- Spring MVC framework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.0.5.RELEASE</version>
    </dependency>
   
    <!-- Apache Commons Upload -->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.2</version>
    </dependency>

    <!-- Apache Commons Upload -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>

    <!-- JSTL -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.1.2</version>
    </dependency>
   
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>SpringMVC</finalName>
  </build>
</project>


Below is the Content for web.xml



<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>Spring Web MVC 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>*.htm</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>


Below is the Content for mvc-dispatcher-servlet.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.mahesh.customer.controller" />
   
    <bean class="com.mahesh.customer.validator.CustomerValidator" />
   
     <!-- Register the Customer.properties -->
    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="com/mahesh/customer/properties/Customer" />
    </bean>
    
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
          <property name="prefix">
              <value>/WEB-INF/pages/</value>
           </property>
          <property name="suffix">
             <value>.jsp</value>
          </property>
    </bean>

</beans>


Below is the Content for CustomerController.java



 package com.mahesh.customer.controller;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import com.mahesh.customer.model.Customer;
import com.mahesh.customer.validator.CustomerValidator;

@Controller
@RequestMapping("/customer.htm")
public class CustomerController{
  
    CustomerValidator customerValidator;
  
    @Autowired
    public CustomerController(CustomerValidator customerValidator){
        this.customerValidator = customerValidator;
    }
  
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(
            @ModelAttribute("customer") Customer customer,
            BindingResult result, SessionStatus status) {
      
        customerValidator.validate(customer, result);
      
        if (result.hasErrors()) {
            //if validator failed
            return "CustomerForm";
        } else {
            status.setComplete();
            //form success
            return "CustomerSuccess";
        }
    }
  
    @RequestMapping(method = RequestMethod.GET)
    public String initForm(ModelMap model){
      
        Customer cust = new Customer();
        //Make "Spring MVC" as default checked value
        cust.setFavFramework(new String []{"Spring MVC"});
      
        //Make "Make" as default radio button selected value
        cust.setSex("M");
      
        //make "Hibernate" as the default java skills selection
        cust.setJavaSkills("Hibernate");
      
        //initilize a hidden value
        cust.setSecretValue("I'm hidden value");
      
        //command object
        model.addAttribute("customer", cust);
      
        //return form view
        return "CustomerForm";
    }
  
  
    @ModelAttribute("webFrameworkList")
    public List<String> populateWebFrameworkList() {
      
        //Data referencing for web framework checkboxes
        List<String> webFrameworkList = new ArrayList<String>();
        webFrameworkList.add("Spring MVC");
        webFrameworkList.add("Struts 1");
        webFrameworkList.add("Struts 2");
        webFrameworkList.add("JSF");
        webFrameworkList.add("Apache Wicket");
      
        return webFrameworkList;
    }
  
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
      
    }
  
    @ModelAttribute("colorList")
    public List<String> populateColorList() {
      
        //Data referencing for number radiobuttons
        List<String> colorList = new ArrayList<String>();
        colorList.add("Color 1");
        colorList.add("Color 2");
        colorList.add("Color 3");
        colorList.add("Color 4");
        colorList.add("Color 5");
      
        return colorList;
    }
  
    @ModelAttribute("javaSkillsList")
    public Map<String,String> populateJavaSkillList() {
      
        //Data referencing for java skills list box
        Map<String,String> javaSkill = new LinkedHashMap<String,String>();
        javaSkill.put("Hibernate", "Hibernate");
        javaSkill.put("Spring", "Spring");
        javaSkill.put("WebService", "WebService");
        javaSkill.put("Struts", "Struts");
      
        return javaSkill;
    }

    @ModelAttribute("countryList")
    public Map<String,String> populateCountryList() {
      
        //Data referencing for java skills list box
        Map<String,String> country = new LinkedHashMap<String,String>();
        country.put("IN", "India");
        country.put("US", "United Stated");
        country.put("SG", "Singapore");
        country.put("MY", "Malaysia");
      
        return country;
    }
  
}


Below is the Content for Customer.java



package com.mahesh.customer.model;


public class Customer{
   
    //textbox
    String userName;
   
    //textarea
    String address;
   
    //password
    String password;
    String confirmPassword;
   
    //checkbox
    boolean receiveNewsletter;
    String [] favFramework;
   
    //radio button
    String favColor;
    String sex;
   
    //dropdown box
    String country;
    String javaSkills;
   
    //hidden value
    String secretValue;
   
    public String getSecretValue() {
        return secretValue;
    }
    public void setSecretValue(String secretValue) {
        this.secretValue = secretValue;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getConfirmPassword() {
        return confirmPassword;
    }
    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }
    public boolean isReceiveNewsletter() {
        return receiveNewsletter;
    }
    public void setReceiveNewsletter(boolean receiveNewsletter) {
        this.receiveNewsletter = receiveNewsletter;
    }
    public String[] getFavFramework() {
        return favFramework;
    }
    public void setFavFramework(String[] favFramework) {
        this.favFramework = favFramework;
    }
    public String getFavColor() {
        return favColor;
    }
    public void setFavColor(String favColor) {
        this.favColor = favColor;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getJavaSkills() {
        return javaSkills;
    }
    public void setJavaSkills(String javaSkills) {
        this.javaSkills = javaSkills;
    }
   
}

Below is the Content for CustomerValidator.java



package com.mahesh.customer.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.mahesh.customer.model.Customer;

public class CustomerValidator implements Validator{

    public boolean supports(Class clazz) {
        //just validate the Customer instances
        return Customer.class.isAssignableFrom(clazz);

    }

    public void validate(Object target, Errors errors) {
       
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
                "required.userName", "Field name is required.");
       
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address",
                "required.address", "Field name is required.");
       
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
                "required.password", "Field name is required.");
           
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
                "required.confirmPassword", "Field name is required.");
       
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "sex",
                "required.sex", "Field name is required.");
       
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "favColor",
                "required.favColor", "Field name is required.");
       
        ValidationUtils.rejectIfEmptyOrWhitespace(
                errors, "javaSkills", "required.javaSkills","Field name is required.");
       
        Customer cust = (Customer)target;
       
        if(!(cust.getPassword().equals(cust.getConfirmPassword()))){
            errors.rejectValue("password", "notmatch.password");
        }
       
        if(cust.getFavFramework().length==0){
            errors.rejectValue("favFramework", "required.favFrameworks");
        }

        if("NONE".equals(cust.getCountry())){
            errors.rejectValue("country", "required.country");
        }
       
    }
   
}


Below is the Content for Customer.properties


required.userName = Username is required!
required.address = Address is required!
required.password = Password is required!
required.confirmPassword = Confirm password is required!
required.favFrameworks = Please select at least a web frameworks!
required.sex = Please select a sex!
required.favColor = Please select a Color!
notmatch.password = Password and Conform password is not match!
required.country = Please select a country!
required.javaSkills = Please select a java Skill!


Below is the Content for CustomerForm.jsp


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<style>
.error {
    color: #ff0000;
}
.errorblock{
    color: #FF0000;
    background-color: #ffEEEE;
    border: 3px solid #7CB1DD;
    padding:8px;
    margin:16px;
}

</style>
</head>

<body>
<h2>Spring's form tags example</h2>

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

<form:errors path="*" cssClass="errorblock" element="div"/>

<table>
<tr>
<td>UserName : </td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td>Address : </td>
<td><form:textarea path="address" /></td>
<td><form:errors path="address" cssClass="error" /></td>
</tr>
<tr>
<td>Password : </td>
<td><form:password path="password" /></td>
<td><form:errors path="password" cssClass="error" /></td>
</tr>
<tr>
<td>Confirm Password : </td>
<td><form:password path="confirmPassword" /></td>
<td><form:errors path="confirmPassword" cssClass="error" /></td>
</tr>
<tr>
<td>Subscribe to newsletter? : </td>
<td><form:checkbox path="receiveNewsletter" /></td>
<td><form:errors path="receiveNewsletter" cssClass="error" /></td>
</tr>
<tr>
<td>Favourite Web Frameworks : </td>
<td>
    <form:checkboxes items="${webFrameworkList}" path="favFramework" />
</td>
<td><form:errors path="favFramework" cssClass="error" /></td>
</tr>
<tr>
<td>Sex : </td>
<td>
<form:radiobutton path="sex" value="M"/>Male
<form:radiobutton path="sex" value="F"/>Female
</td>
<td><form:errors path="sex" cssClass="error" /></td>
</tr>
<tr>
<td>Choose a color : </td>
<td>
    <form:radiobuttons path="favColor" items="${colorList}"  />
</td>
<td><form:errors path="favColor" cssClass="error" /></td>
</tr>

<tr>
<td>Country : </td>
<td>
<form:select path="country">
    <form:option value="NONE" label="--- Select ---"/>
    <form:options items="${countryList}" />
</form:select>
</td>
<td><form:errors path="country" cssClass="error" /></td>
</tr>

<tr>
<td>Java Skills : </td>
<td>
<form:select path="javaSkills" items="${javaSkillsList}" multiple="true" />
</td>
<td><form:errors path="javaSkills" cssClass="error" /></td>
</tr>


<form:hidden path="secretValue" />

<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>

</body>
</html>


Below is the Content for CustomerSuccess.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<body>
<h2>Spring's form tags example</h2>

<table>
<tr>
<td>UserName :</td><td>${customer.userName}</td>
</tr>
<tr>
<td>Address :</td><td>${customer.address}</td>
</tr>
<tr>
<td>Password :</td><td>${customer.password}</td>
</tr>
<tr>
<td>Confirm Password :</td><td>${customer.confirmPassword}</td>
</tr>
<tr>
<td>Receive Newsletter :</td><td>${customer.receiveNewsletter}</td>
</tr>
<tr>
<td>Favourite Web Frameworks :</td>
<td>
<c:forEach items="${customer.favFramework}" var="current">
   [<c:out value="${current}" />]
</c:forEach>
</td>
</tr>
<tr>
<td>Sex :</td><td>${customer.sex}</td>
</tr>
<tr>
<td>Favourite Color :</td><td>${customer.favColor}</td>
</tr>
<tr>
<td>Country :</td><td>${customer.country}</td>
</tr>
<tr>
<td>Java Skills :</td><td>${customer.javaSkills}</td>
</tr>
<tr>
<td>Hidden Value :</td><td>${customer.secretValue}</td>
</tr>

</table>

</body>
</html>


Run the Application by Deploying the SpringMVC.war in Web/Application Server.

Url: http://localhost:8080/SpringMVC/customer.htm











No comments:

Post a Comment