Spring 4 MVC Form Handling Annotation

spring+4+mvc+form+handling+annotation

Click here to download eclipse supported ZIP file




This is home.html JSP file and it is used display the output for the application.



<html>
<body>
<h1>Spring MVC Form handling Annotation Example</h1>
<h3><a href="./customer.htm">Click here to get form page!!!</a></h3>
</body>
</html>

This is CustomerForm.jsp JSP file and it is used display the output for the application.



<%@ 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: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
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 number :</td>
<td><form:radiobuttons path="favNumber" items="${numberList}" />
</td>
<td><form:errors path="favNumber" 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>

This is CustomerSuccess.jsp JSP file and it is used display the output for the application.



<%@ 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 Number :</td><td>${customer.favNumber}</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>


This is CustomerController.java file having the controller logic and it will have the services defined in it.


 

    
package com.cv.spring.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.cv.spring.customer.model.Customer;
import com.cv.spring.customer.validator.CustomerValidator;
/**
@author Chandra Vardhan
*/
@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("numberList")
  public List<String> populateNumberList() {
    
    //Data referencing for number radiobuttons
    List<String> numberList = new ArrayList<String>();
    numberList.add("Number 1");
    numberList.add("Number 2");
    numberList.add("Number 3");
    numberList.add("Number 4");
    numberList.add("Number 5");
    
    return numberList;
  }
  
  @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("Apache Wicket""Apache Wicket");
    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("US""United Stated");
    country.put("CHINA""China");
    country.put("SG""Singapore");
    country.put("MY""Malaysia");
    
    return country;
  }
  
}

This is Customer.java file having the source code to execute business logic.


 

    
package com.cv.spring.customer.model;

/**
@author Chandra Vardhan
*/
public class Customer{
  
  //textbox
  String userName;
  
  //textarea
  String address;
  
  //password
  String password;
  String confirmPassword;
  
  //checkbox
  boolean receiveNewsletter;
  String [] favFramework;
  
  //radio button
  String favNumber;
  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 getFavNumber() {
    return favNumber;
  }
  public void setFavNumber(String favNumber) {
    this.favNumber = favNumber;
  }
  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;
  }
}

This is CustomerValidator.java file having the source code to execute business logic.


 

    
package com.cv.spring.customer.validator;

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

import com.cv.spring.customer.model.Customer;

/**
@author Chandra Vardhan
*/
public class CustomerValidator implements Validator{

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

  }

  @Override
  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, "favNumber"
        "required.favNumber""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");
    }
    
  }
  
}



This is pom.xml file having the entries of dependency jars and information to build the application .


	
<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/xsd/maven-4.0.0.xsd">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.cv.spring.common</groupId> <packaging>war</packaging> <version>1.0</version> <name>SpringMVC Maven Webapp</name> http://maven.apache.org <properties> <spring.version>4.2.0.RELEASE</spring.version> <hibernate.version>4.3.5.Final</hibernate.version> <log4j-version>1.2.17</log4j-version> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> provided </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>Spring4MVCFormHandlingAnnotation</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <artifactId>Spring4MVCFormHandlingAnnotation</artifactId> </project>


This is customer.properties properties file and these properties are used in the application.



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.favNumber = Please select a number!
notmatch.password = Password and Conform password is not match!
required.country = Please select a country!
required.javaSkills = Please select a java Skill!


This is mvc-dispatcher-servlet.xml spring configuration file and these entries are used in the application.


 

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.cv.spring.customer.controller" />
<bean class="com.cv.spring.customer.validator.CustomerValidator" />
<!-- Register the Customer.properties -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="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>


This is web.xml deployment descriptor file and it describes how the web application should be deployed.


	
<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>

<error-page>
<error-code>404</error-code>
<location>/WEB-INF/pages/404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/pages/404.jsp</location>
</error-page>

<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>


This is log4j.properties file having the entries for logging the information into the console/file.



#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

1 comment: