JSP refresh page form repeat submission problem solution share

  • 2020-06-15 10:05:11
  • OfStack

sessionID and timestamp are used for identification, and the key code is as follows:


public class SswpdjAction extends BaseAction{
      public String execute(){
        /** Business code **/
        ................
        // Set the identity 
        this.setSessionToken();
        // Go to the add page 
        return "toAdd";
      }
  
      public String reSave(){
        if(this.token != null && this.token.equals(this.getSessionToken())){
          /** Setting a new identity **/
          this.setSessionToken();
      
          /** Business code **/
          ..............
          return "toAdd";
        }else{
          printWriter out = null;
          try{
            httpServletResponse.setContentType("text/html;charset=UTF-8");
            out = httpServletResponse.getWriter();
            out.println("<script>alert(' Refresh the submission form! ');</script>");
            out.flush();
        
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(out != null){
                    out.close();
                }
            }
        }
        return null;
  }
}
public class BaseAction extends ActionSupport{

    /**jsp Page identifier **/
    protected String token;

    public String getToken(){
        return token;
    }

    public void setToken(String token){
        this.token = token;
    }

    public String getSessionToken(){
        if(null != httpSession.getAttribute("Token")){
            return httpSession.getAttribute("Token");
        }else{
            return null;
        }
    }

    /** Identify generated **/
    public void setSessionToken(){
        String flag = useMd5(httpSession.getId() + System.currentTimeMillis());
        httpSession.setAttribute("Token", flag);
        httpServletRequest.setAttribute("SessionToken", flag);
    }

    /**MD5 encryption **/
    private String useMd5(String str){
        byte[] bs = str.getBytes();
        String result = null;
        try{
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(bs);
            result = md5.digest().toString();
        }catch(NoSuchAlgorithmException e){
            e.printStackTrace();
        }finally{

        }
        return result;
    }
}

JSP page sets the identity hidden domain:


<form>
  <input type="hidden" name="token" value="${SessionToken}" />
</form>


Related articles: