使用hutool工具包生成验证码

重点可以查看Hutool — 🍬A set of tools that keep Java sweet.

的参考文档。

1.导入依赖

<dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>5.7.5</version>
    </dependency>

2.登录页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="bp" value="${pageContext.request.contextPath}" scope="session"/>
<html>
<head>
    <title>登录页</title>
    <link rel="stylesheet" type="text/css" href="${bp}/static/css/base.css">
    <script src="${bp}/static/js/jquery-1.11.1.js"></script>
</head>
<body>
<div id="login">
    <h3>欢迎登录</h3>
    <form action="${bp}/user?method=login" method="post">
        <p><input type="text" name="username" class="input"  placeholder="请输入用户名"></p>
        <p><input type="password" name="password" class="input" placeholder="请输入密码"></p>
        <p><input type="text" name="token" style="width: 200px;height: 50px; margin-right: 10px" placeholder="请输入验证码"><img src="${bp}/user?method=getCode" width="90px" height="50px"style="vertical-align: middle" onclick="changeImg()"></p>
        <p><input type="submit" value="立即登录" class="input"><a href="register.jsp">注册账号</a></p>
    </form>
<%--    显示登录错误的信息--%>
    <span style="color: red">${requestScope.msg}</span>
</div>

<script>
    //单击改变验证码
    function changeImg() {
        let sr = $("img").attr("src")+"&date= "+new Date().getTime()
        $("img").attr("src",sr)
    }
</script>


</body>
</html>

重点部分:

<p><input type="text" name="token" style="width: 200px;height: 50px; margin-right: 10px" placeholder="请输入验证码"><img src="${bp}/user?method=getCode" width="90px" height="50px"style="vertical-align: middle" onclick="changeImg()"></p>
       
<script>
    //单击改变验证码
    function changeImg() {
        let sr = $("img").attr("src")+"&date= "+new Date().getTime()
        $("img").attr("src",sr)
    }
</script>
</body>
</html>

3.servlet部分

//  生成验证码
    protected void  getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        //  包含干扰线的验证码图片  width  图片宽度  height:图片高度  codeCount 验证码的位数  lineCount  干扰线的条数
        LineCaptcha lineCaptcha = new LineCaptcha(100, 60, 4, 5);
        // 获取图片中的验证码 保存在session会话对象中 用于后续登录验证
        String code = lineCaptcha.getCode();
        System.out.println("code = " + code);
        req.getSession().setAttribute("code", code);

        //将图片以流的形式响应给前端浏览器
        ServletOutputStream outputStream = resp.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();

    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值