spring+4+mvc+duplicated+form+submission
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>Spring4 MVC Duplicated Form Submission Example</h1>
<h3><a href="./customerController.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="customerForm">
<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>
<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>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.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
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.cv.spring.customer.model.Customer;
/**
* @author Chandra Vardhan
*/
public class CustomerController extends SimpleFormController{
public CustomerController(){
setCommandClass(Customer.class);
setCommandName("customerForm");
}
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
Customer customer = (Customer)command;
System.out.println(customer);
//put the model in session, so that it's able pass to another controller
request.getSession().setAttribute("customer",customer);
return new ModelAndView("customerSuccessRedirect");
}
@Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
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");
return cust;
}
@Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Map referenceData = new HashMap();
//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");
referenceData.put("webFrameworkList", webFrameworkList);
//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");
referenceData.put("numberList", numberList);
//Data referencing for country dropdown 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");
referenceData.put("countryList", country);
//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");
referenceData.put("javaSkillsList", javaSkill);
return referenceData;
}
} |
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>
<artifactId>Spring4MVCDuplicatedFormSubmission</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>SpringMVC Maven Webapp</name>
http://maven.apache.org
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
test
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</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>
<finalName>Spring4MVCDuplicatedFormSubmission</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</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>Spring4MVCDuplicatedFormSubmission</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</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.passwordConfirm = 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!
|
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">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="com.cv.spring.customer.controller.CustomerController"> <property name="formView" value="CustomerForm" /> <property name="successView" value="customerSuccessRedirect" /> <!-- <property name="successView" value="customerSuccessRedirect" /> --> <!-- Map a validator --> <property name="validator"> <bean class="com.cv.spring.customer.validator.CustomerValidator" /> </property> </bean> <!-- Redirect Controller --> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/CustomerSuccess.htm">customerSuccessController</prop> </props> </property> </bean> <bean id="customerSuccessController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"> <property name="viewName" value="CustomerSuccess" /> </bean> <!-- 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> <property name="order" value="1" /> </bean> <bean class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="location"> <value>/WEB-INF/spring-views.xml</value> </property> <property name="order" value="0" /> </bean> </beans>
|
This is spring-views.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">
<!-- Redirect view --> <bean id="customerSuccessRedirect" class="org.springframework.web.servlet.view.RedirectView"> <property name="url" value="CustomerSuccess.htm" /> </bean> </beans>
|
This is web.xml deployment descriptor file and it describes how the web application should be deployed.
| <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <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
|
No comments:
Post a Comment