一、驗證碼解決表單重複提交的原理
第一次訪問regist.jsp的時候,就會生成驗證碼,並且保存到Session中,第一次提交表單的時候,服務器獲取到客戶端提交的驗證碼和獲取到存取到Session中的驗證碼進行比較,如果相等的,允許接下來的操作,不等的話,就阻止接下來的操作。最後要刪除Session中驗證碼,當第二次重複提交的時候,Session中的驗證碼已經爲null,此時的話就阻止用戶的操作(解決了表單重複提交的問題)
二、谷歌Kaptcha圖片驗證碼的使用
1、導入谷歌驗證碼的jar包 kaptcha-2.3.2.jar
2、 在web.xml中去配置用於生成驗證碼的servlet程序
3、在表單中使用img標籤去顯示驗證碼圖片並使用它
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="http://localhost:8080/13_cookie_session/registServlet" method="get">
用戶名:<input type="text" name="username" > <br>
驗證碼:<input type="text" style="width: 60px;" name="code">
<img src="http://localhost:8080/13_cookie_session/kaptcha.jpg" alt="" style="width: 100px; height: 28px;"> <br>
<input type="submit" value="登錄">
</form>
</body>
</html>
4、在服務器獲取谷歌生成的驗證碼和客戶端發送過來的驗證碼比較使用。
package com.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;
public class RegistServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 獲取Session中的驗證碼
String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
// 刪除 Session中的驗證碼
req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
String code = req.getParameter("code");
// 獲取用戶名
String username = req.getParameter("username");
if (token != null && token.equalsIgnoreCase(code)) {
System.out.println("保存到數據庫:" + username);
resp.sendRedirect(req.getContextPath() + "/ok.jsp");
} else {
System.out.println("請不要重複提交表單");
}
}
}