验证码
表单重复提交
表单重复提交有三种常见的情况:
情况一:提交完表单。如果采用请求转发,当用户提交完请求,浏览器会记录下最后一次请求的全部信息。此时若用户按下F5功能键,就会发起浏览器记录的最后一次请求,导致表单重复提交!
解决方案:请求重定向
情况二:用户正常提交服务器,但是由于网络延迟等原因,长时间未收到服务器响应,此时,用户重复点击提交,也会造成表单重复提交
解决方案:验证码
情况三:用户正常提交服务器,且成功提交。但成功后用户回退浏览器,重新提交,也会造成表单重复提交
解决方案:验证码

谷歌kaptcha图片验证码的使用
1、引入依赖

2、在web.xml中配置用于生成验证码的Servlet程序
<servlet>
<servlet-name>KaptchaServlet</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>KaptchaServlet</servlet-name>
<url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>
3、在表单中使用img标签显示验证码图片并使用它
<form action="http://localhost:8080/myjavaweb/response1" method="get">
用户名:<input type="text" name="username"><br>
验证码:<input type="text" name="code" style="width: 80px;">
<img src="http://localhost:8080/myjavaweb/kaptcha.jpg" style="width: 120px"; height="30px"><br>
<input type="submit" value="登录">
</form>
4、在服务器获取谷歌生成的验证码和客户端发送过来的验证码比较使用
package com.tang.web.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 Response1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(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 username = req.getParameter("username");
String code = req.getParameter("code");
if(token !=null && token.equalsIgnoreCase(code)) {
System.out.println("保存到数据库");
} else {
System.out.println("请不要重复提交表单");
}
}
}
实现点击验证码图片切换验证码
给验证码图片添加上点击事件
<form action="http://localhost:8080/myjavaweb/response1" method="get">
用户名:<input type="text" name="username"><br>
验证码:<input type="text" name="code" style="width: 80px;">
<img src="http://localhost:8080/myjavaweb/kaptcha.jpg" id="code_img" style="width: 120px"; height="30px"><br>
<input type="submit" value="登录">
</form>
<script type="text/javascript">
$(function () {
//给验证码的图片绑上单击事件
$("#code_img").click(function () {
this.src = "http://localhost:8080/myjavaweb/kaptcha.jpg?d="+new Date(); //加上时间戳跳过浏览器缓存,发起请求
});
})
</script>

浙公网安备 33010602011771号