Wednesday 10 December 2014

Spring MVC : Preventing Duplicate Form Submission without Spring Security



Spring MVC so far has no out of box solution to prevent duplicate form submission yet , while below are the possible solutions :

Option 1 , javascript : disable submit button 


Option 2 , Post-Redirect-Get pattern : send a redirect after submit 


Option 3 , tokening : unique token between client and server 


Both option 1 and option 2 have drawbacks , let's see how to implement option 3.


 


Step 1 : token handler

This class is used to generate a unique token and save in the cache :









Step 2 : token tag lib

To use "TokenHandler" with jstl below is the tag lib class :create spring-token.tld as below and put under src/main/resources/META-INF/spring-token.tld







Step 3 : check token annotation and interceptor

This annotation can be put on any method in "Controller" for the request that needs token validation.
Define a Spring interceptor for token validation purpose :






 


Step 4 : generate token on JSP

Just put <junjun:token/> under a <form> tag as below:







 


Step 5 : Spring configuration for interceptor and cache manager









Step 6 : use @CheckToken annotation

 Whenever token is needed for request validation , token could be include in the page by , and @CheckToken can used to check if the token is valid :


 


Step 7 : Verify


Run org.junjun.util.spring.AppLauncher , and open browser http://localhost:6060 , one of the requests should failed.


 


NOTE : 

1. source code of the project could be found here : 

Web App : https://github.com/junjun-dachi/spring-util/tree/master/prevent-duplicate-form-submission-web

Token : https://github.com/junjun-dachi/spring-util/tree/master/prevent-duplicate-form-submission-token-taglib

2. this solution does not support application that runs in distributed environment , please use and refer to ehcache document for cluster cache manager configuration 


3. Spring Security has one solution for CSRF we will see later





4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. sorry only see your message today , please refer to the github source , thank you.

      Delete
  2. is it for double click or refresh issue(this code)

    ReplyDelete
  3. you defined org.junjun.util.spring.token.tags.TokenTag in tld file but where is TokenTag class file?

    ReplyDelete

Flag Counter