Java中防止表单重复提交(2)

@WebServlet("/transfer")
public class CopyOfTransferServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;
   
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //创建令牌,并跳转到submit.jsp
        String token = UUID.randomUUID().toString();
        System.out.println(token);
        req.getSession().setAttribute("TOKEN_IN_SESSION", token);
        req.setAttribute("token", token);
        req.getRequestDispatcher("/views/repeatsubmit/submit.jsp").forward(req, resp);
       
    }
}

此时jsp文件中就是这个样子

<h3>转账界面</h3>
        <form action="/trans" method="post">
            <input type="hidden" value="${token }"/>
            转账金额:<input type="text" min="1" required /><br/>
            <input type="submit" value="转账" />
        </form>

TokenUtil.java
//令牌的工具类
//创建令牌
//校验令牌
//销毁令牌
public class TokenUtil {
    private final static String TOKEN_IN_SESSION = "TOKEN_IN_SESSION";
    public static void savaToken(HttpServletRequest req) {
        String token = UUID.randomUUID().toString();
        System.out.println(token);
        req.getSession().setAttribute(TOKEN_IN_SESSION, token);
        req.setAttribute("token", token);
    }

public static boolean validateToken(HttpServletRequest req,
            String tokenInrequest) {
        //获取session中的token值
        String sessionToken = (String) req.getSession().getAttribute(
                TOKEN_IN_SESSION);
        if (tokenInrequest.equals(sessionToken)) {
            req.getSession().removeAttribute(TOKEN_IN_SESSION);
            return true;
        }
        return false;
    }
}

这样就好了,使用者只需要调用这个工具类就好了,不需要再去写创建令牌等一系列操作

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/757d0afb2ea65c7a9739919eff17644d.html