Struts: prevent form double submission with saveToken 


October 15, 2008 21:49:22    Last update: October 15, 2008 21:49:22
Follow these steps to prevent form double submission in struts:
  1. In the action class leading to the display of the form, call saveToken(request)
  2. In the action class handling the form submission, check the validity of the token by calling isTokenValid(request). If token is valid, reset the token by calling resetToken(request), then continue processing the form submission. Otherwise, skip form processing since it's double submission.

How doe it work?
  1. saveToken generates a unique token and saves it in the session under the key org.apache.struts.action.TOKEN.
  2. When the form is rendered, the struts html:form tag generates a hidden field named org.apache.struts.action.TOKEN.
  3. Upon form submission, isTokenValid compares the token stored in the session with that submitted from the form. If they are equal, return true. Otherwise, return false.
  4. resetToken removes the token stored in the session.

Assuming that the same action handles both form display and form submission, here's the sample code:
public ActionForward execute(ActionMapping map,
                             ActionForm form,
                             HttpServletRequest request,
                             HttpServletResponse response) 
                     throws Exception {
    String action = request.getParameter("action");

    ActionForward fwd = map.findForward("display");
    if (!"submit".equals(action)) {  // display the form
        // prepare form rendering...
    else { // form submission
        if (isTokenValid(request)) {
            fwd = map.findForward("success");
        else { // double submission
            fwd = map.findForward("invalid");

    return fwd;

Since the token is saved in the user session, this mechanism assumes that the user is "single threaded", which is true most of the time. If you bring up the form in one window, then open a new browser window and navigate to another form (or, the same form), and then submit the form in the original window, it will fail.
Share |
| Comment  | Tags