Wednesday, May 28, 2014

Duplicate form submission Prevention using Spring MVC

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.


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



  PostRedirectGetUsingSpringMVC
 
        add_student.jsp
      
   

  
        org.springframework.web.context.ContextLoaderListener
   

  
   
        contextConfigLocation
        WEB-INF/context-conf.xml
   

     
 
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        1
   

   
        dispatcher
        *.html
   


dispatcher-servlet.xml:->  place it in WebContent/WEB-INF/



    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">
 
 
  
   
   
  
                  class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
             
                  /
              

             
                 .jsp
             

       

      
   



context-conf.xml: place it in WebContent/WEB-INF/


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


            class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
       

       
          
                    org.demo.model.Student  
          
       


       
           
                org.hibernate.dialect.MySQLDialect
                true
                none
           

       

   

   
       
   

  
   
       
   
 
   
   
    




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




Post->Redirect->get example

  
   

  
       
           
               
           
          
           
               
           
          
           
               
           
          
       
id:
Name:

   






show_student.jsp



  
  

${student1.name}added successfully..



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

No comments: