Question

I am trying to prevent multiple form submits caused by browser refresh by setting a use once only token in session and comparing it with request. However when I am trying to reset the session token, it is not getting updated. Below is my code.

Set Token which renders the jsp page

getSession().setAttribute(Globals.TRANSACTION_TOKEN_KEY, "123");

This is in my jsp

  <s:hidden name="token" value="123"/>

Action class

String requestToken = getToken();
String sessionToken = (String)      
getRequest().getSession().getAttribute(Globals.TRANSACTION_TOKEN_KEY);

 if(requestToken.equalsIgnoreCase(sessionToken)){
   //reset the token  
  getRequest().getSession().setAttribute(Globals.TRANSACTION_TOKEN_KEY, "124");

   //perform update

 }

The session token is not getting updated to 124. Please assist.

Thanks, Prasheel.

Was it helpful?

Solution

You can use below code in action.

In loading of previous page

 ActionContext.getContext().getSession().put(Globals.TRANSACTION_TOKEN_KEY, "123");

In jsp page

<s:hidden name="token" value="123"/>

And in action class of form submission

 Map<String,Object> session = ActionContext.getContext().getSession();
     if(getToken().toString().equalsIgnoreCase(session.get(Globals.TRANSACTION_TOKEN_KEY).toString())){
   System.out.println("request is handled");
       //reset the token
       //perform update
         session.put(Globals.TRANSACTION_TOKEN_KEY, "124");
     }

In both jsp pages use this

< %
  response.setHeader("Cache-Control", "no-cache, no-store");
  response.setDateHeader("Expires", 0);
  response.setHeader("Vary", "*");
% >

The simple way is

if (session.getAttribute("recordInsertedSuccessfully") == null )
{
   //update records
   //after inserting into the database we should do :
   session.putAttribute("recordInsertedSuccessfully","true");
} else {
   //case of form re-submission
}

Your problem is you are again calling the method which is setting session variable to 123.

make another method runinspect2(), copy paste code from runinspect() but remove line from runinspect2() which is setting session variable to 123 which is following line

 ActionContext.getContext().getSession().put(Globals.TRANSACTION_TOKEN_KEY, "123");

and call runinspect2() in update() method it is simple

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top