Hello Friends hope you all are doing well.today i am going to demonstrate how to prevent duplicate form submission using spring mvc.if url returns successview & if you refresh success page again and again than it might lead to multiple callback to database if method is interacting with url.
if you redirect to another page than request parameter will not be available to you.spring mvc will resolve both mentioned issues using Post Redirect Get pattern.
Spring mvc provides flash attributes in order to resolve issue of duplicate form submission. you can put attributes into flashmap that you want to get into success view page & get that values into success page.
Project structure is as follows:
limitation of flash attribute is it is pertaining to single request only.for each single request ,flash attributes are available.i am posting code as given below :
Model
package org.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student
{
@Id @Column(name="id")
private String studentid;
@Column
private String name;
public Student(){}
public String getStudentid() {
return studentid;
}
public void setStudentid(String studentid) {
this.studentid = studentid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DAO:
package org.dao;
import java.util.List;
import org.demo.model.Student;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class StudentDAO
{
private HibernateTemplate template;
public HibernateTemplate getTemplate() {
return template;
}
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public StudentDAO(HibernateTemplate template) {
this.template = template;
}
public void insert(Student student)
{
template.save(student);
}
public List<Student> getStudents()
{
return template.find("from student");
}
}
Controller
package org.demo.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dao.StudentDAO;
import org.demo.model.Student;
import org.springframework.stereotype.Controller;
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.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class StudentController
{
@RequestMapping(value="/showform", method=RequestMethod.GET)
public String showForm(@ModelAttribute("student") Student stud) {
return "add_student";
}
@RequestMapping(value="/add_student", method=RequestMethod.POST)
public String addStudent(@ModelAttribute("student1") Student student1,
final RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response)
{
WebApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
StudentDAO studentdao =(StudentDAO) context.getBean("studentDAO");
String id=request.getParameter("txtid");
String name=request.getParameter("txtname");
Student student= new Student();
student.setStudentid(id);
student.setName(name);
studentdao.insert(student);
redirectAttributes.addFlashAttribute("student1", student);
redirectAttributes.addFlashAttribute("message","Added successfully.");
return "redirect:show_student.html";
}
@RequestMapping(value="/show_student", method=RequestMethod.GET)
public String showStudent(@ModelAttribute("student1") Student student) {
return "show_student";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>PostRedirectGetUsingSpringMVC</display-name>
<welcome-file-list>
<welcome-file>add_student.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/context-conf.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml:-> place it in WebContent/WEB-INF/
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="org.demo.controller" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
context-conf.xml: place it in WebContent/WEB-INF/
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studentdb" />
<property name="username" value="root" />
<property name="password" value="admin!@#"/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<value>org.demo.model.Student</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg ref="mySessionFactory" />
</bean>
<bean id="studentDAO" class="org.dao.StudentDAO">
<constructor-arg ref="hibernateTemplate" />
</bean>
</beans>
showform.jsp: -> homepage
<%
response.sendRedirect("add_student.jsp");
%>
add_student.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>Post->Redirect->get example </title>
</head>
<body>
<form action="add_student.html" method="POST">
<table>
<tr>
<td>id:<input type="text" id="txtid" name="txtid"></td>
</tr>
<tr>
<td>Name:<input type="text" id="txtname" name="txtname"></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
show_student.jsp
<html>
<body>
<h2>${student1.name}added successfully..</h2>
</body>
</html>
the output will look like given below :
(1) simple form with id ,name
(2) after posting data to server ,data will be stored in flash map,success view is returned & data will be stored into database.
(3) if you resubmit the form again when success view appears,it will simply remove flash attribute from flash map & just display added successfully. this is how you can prevent duplicate form submission.
thanks for reading.
for any query ping me on pathak.nisarg@yahoo.com.
Enjoy Coding.
if you redirect to another page than request parameter will not be available to you.spring mvc will resolve both mentioned issues using Post Redirect Get pattern.
Spring mvc provides flash attributes in order to resolve issue of duplicate form submission. you can put attributes into flashmap that you want to get into success view page & get that values into success page.
Project structure is as follows:
limitation of flash attribute is it is pertaining to single request only.for each single request ,flash attributes are available.i am posting code as given below :
Model
package org.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student
{
@Id @Column(name="id")
private String studentid;
@Column
private String name;
public Student(){}
public String getStudentid() {
return studentid;
}
public void setStudentid(String studentid) {
this.studentid = studentid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DAO:
package org.dao;
import java.util.List;
import org.demo.model.Student;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class StudentDAO
{
private HibernateTemplate template;
public HibernateTemplate getTemplate() {
return template;
}
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public StudentDAO(HibernateTemplate template) {
this.template = template;
}
public void insert(Student student)
{
template.save(student);
}
public List<Student> getStudents()
{
return template.find("from student");
}
}
Controller
package org.demo.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dao.StudentDAO;
import org.demo.model.Student;
import org.springframework.stereotype.Controller;
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.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class StudentController
{
@RequestMapping(value="/showform", method=RequestMethod.GET)
public String showForm(@ModelAttribute("student") Student stud) {
return "add_student";
}
@RequestMapping(value="/add_student", method=RequestMethod.POST)
public String addStudent(@ModelAttribute("student1") Student student1,
final RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response)
{
WebApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
StudentDAO studentdao =(StudentDAO) context.getBean("studentDAO");
String id=request.getParameter("txtid");
String name=request.getParameter("txtname");
Student student= new Student();
student.setStudentid(id);
student.setName(name);
studentdao.insert(student);
redirectAttributes.addFlashAttribute("student1", student);
redirectAttributes.addFlashAttribute("message","Added successfully.");
return "redirect:show_student.html";
}
@RequestMapping(value="/show_student", method=RequestMethod.GET)
public String showStudent(@ModelAttribute("student1") Student student) {
return "show_student";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>PostRedirectGetUsingSpringMVC</display-name>
<welcome-file-list>
<welcome-file>add_student.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/context-conf.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml:-> place it in WebContent/WEB-INF/
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="org.demo.controller" />
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
context-conf.xml: place it in WebContent/WEB-INF/
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studentdb" />
<property name="username" value="root" />
<property name="password" value="admin!@#"/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<value>org.demo.model.Student</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg ref="mySessionFactory" />
</bean>
<bean id="studentDAO" class="org.dao.StudentDAO">
<constructor-arg ref="hibernateTemplate" />
</bean>
</beans>
showform.jsp: -> homepage
<%
response.sendRedirect("add_student.jsp");
%>
add_student.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>Post->Redirect->get example </title>
</head>
<body>
<form action="add_student.html" method="POST">
<table>
<tr>
<td>id:<input type="text" id="txtid" name="txtid"></td>
</tr>
<tr>
<td>Name:<input type="text" id="txtname" name="txtname"></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
show_student.jsp
<html>
<body>
<h2>${student1.name}added successfully..</h2>
</body>
</html>
the output will look like given below :
(1) simple form with id ,name
(2) after posting data to server ,data will be stored in flash map,success view is returned & data will be stored into database.
(3) if you resubmit the form again when success view appears,it will simply remove flash attribute from flash map & just display added successfully. this is how you can prevent duplicate form submission.
thanks for reading.
for any query ping me on pathak.nisarg@yahoo.com.
Enjoy Coding.