JSP刷新页面表单重复提交问题解决办法分享

使用sessionID和时间戳作为标识,关键代码如下:

 代码如下:

public class SswpdjAction extends BaseAction{

      public String execute(){
        /**业务代码**/
        ................
        //设置标识
        this.setSessionToken();
        //转到添加页面
        return "toAdd";
      }
  
      public String reSave(){
        if(this.token != null && this.token.equals(this.getSessionToken())){
          /**设置新标识**/
          this.setSessionToken();
      
          /**业务代码**/
          ..............
          return "toAdd";
        }else{
          printWriter out = null;
          try{
            httpServletResponse.setContentType("text/html;charset=UTF-8");
            out = httpServletResponse.getWriter();
            out.println("<script>alert('刷新提交表单!');</script>");
            out.flush();
        
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(out != null){
                    out.close();
                }
            }
        }
        return null;
  }
}

public class BaseAction extends ActionSupport{

    /**jsp页面标识**/
    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;
        }
    }

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

    /**MD5加密**/
    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页面设置标识隐藏域:

 代码如下:

<form>
  <input type="hidden" name="token" value="${SessionToken}" />
</form>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值