// 解决表单重复提交方案1:PRG模式(POST-REDIRECT-GET) (重定向到结果页面)
// https://en.wikipedia.org/wiki/Post/Redirect/Get- 请求支付PayServlet
@WebServlet("/pay")
public class PayServlet extends HttpServlet {
private Logger logger = LoggerFactory.getLogger(PayServlet.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 产生Token
String token = UUID.randomUUID().toString();
//2. 放入session
HttpSession session = req.getSession();
session.setAttribute("token",token);
//3. 放入表单
req.setAttribute("token",token);
req.getRequestDispatcher("/WEB-INF/views/pay.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 从表单中获取Token
String token = req.getParameter("token");
//2. 从session中获取token
HttpSession session = req.getSession();
String sessionToken = (String) session.getAttribute("token");
//3. 判断表单中的token和session中的token是否一致
if(token != null && token.equals(sessionToken)) {
//4. 将session中的token删除
session.removeAttribute("token");
String money = req.getParameter("money");
logger.info("成功扣款{}元",money);
//请求转发的形式去了结果页面
req.getRequestDispatcher("/WEB-INF/views/paysuc.jsp").forward(req,resp);
} else {
logger.warn("表单重复提交");
req.getRequestDispatcher("/WEB-INF/views/payerror.jsp").forward(req,resp);
}
//resp.sendRedirect("/pay/suc");
}
2.支付成功PaySuccessServlet
@WebServlet("/pay/suc")
public class PaySuccessServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/WEB-INF/views/paysuc.jsp").forward(req,resp);
}
}
3.支付pay
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="/pay" method="post">
<input type="hidden" name="token" value="${requestScope.token}">
<input type="text" name="money">
<button>支付</button>
</form>
</body>
</html>
4提示重复提交payerror
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>提交异常!</h3>
<ul>
<li>可能进行了重复提交</li>
<li>服务器端正在升级...</li>
</ul>
</body>
</html>
5.支付成功页面paysuc
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>支付成功,感谢惠顾!</h3>
</body>
</html>