我们先完成html页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>验证码验证</title>
<script>
window.onload = function () {
document.getElementById("change_img").onclick = function () {
document.getElementById("check_Code").src = "/text/captche?time="+new Date().getTime();
}
}
</script>
</head>
<body>
<form method="post" action="/text/login">
<table border="1">
<tr>
<td colspan="2"><img id="check_Code" src="/text/captche" width="100%"></td>
</tr>
<tr>
<td colspan="2"><input type='text' name='validCode' value=''></td>
</tr>
<tr>
<td ><input type='submit' value='验证' width="100%"></td>
<td ><a id="change_img" href="#">换一张?</a></td>
</tr>
</table>
</form>
<div>结果:<%=request.getAttribute("check_result") == null ? "" : request.getAttribute("check_result")%></div>
//这里的输出用来查看我们是否验证成功
</body>
</html>
页面样式如下
其次我们要生成验证码并且获取验证码生成的随机字符进行比对(这里的生成验证码的代码我就省略不写了,可以看一下我的生成验证码那篇文章,把下面三句加进去就可以了)
......
static String checkCode_session; //创建一个成员变量
......
checkCode_session = caption.toString(); //在方法中获得验证码随机字符
......
req.getSession().setAttribute("checkCode_session",checkCode_session); //将验证码随机字符保存到Request对象中
......
接下来我们编写一个login
@WebServlet("/login")
public class LoginController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
this.doPost(req,response);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8"); //这里要和你的html页面的编码方式一模一样
String checkCode=req.getParameter("validCode"); //这里我们将用户输入的验证码提取出来
HttpSession session = req.getSession();
String checkCode_session = (String) session.getAttribute("checkCode_session"); //提取出服务器生成的验证码字符串
if(checkCode_session != null && checkCode_session.equalsIgnoreCase(checkCode)){ //进行比对
req.setAttribute("check_result","验证码匹配");
}
else{
req.setAttribute("check_result","验证码不匹配");
}
req.getRequestDispatcher("/login.jsp").forward(req,resp); //转发,可以查看我们是否验证成功了
}
}