通过session进行验证码验证

我们先完成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);	//转发,可以查看我们是否验证成功了
    }
}

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值