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:
How doe it work?
Assuming that the same action handles both form display and form submission, here's the sample code:
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.
- In the action class leading to the display of the form, call
saveToken(request) - 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 callingresetToken(request), then continue processing the form submission. Otherwise, skip form processing since it's double submission.
How doe it work?
-
saveTokengenerates a unique token and saves it in the session under the keyorg.apache.struts.action.TOKEN. - When the form is rendered, the struts
html:formtag generates a hidden field namedorg.apache.struts.action.TOKEN. - Upon form submission,
isTokenValidcompares the token stored in the session with that submitted from the form. If they are equal, return true. Otherwise, return false. -
resetTokenremoves 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 saveToken(request); // prepare form rendering... } else { // form submission if (isTokenValid(request)) { resetToken(request); processForm(form); 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.