验证码的简单实现----java

简单实现验证码的登录认证。

一、工具:

idea、 springboot、 thymeleaf

二、验证码的Controller类 :

@Controller
public class CaptchaController {
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置响应头信息,告诉浏览器返回的内容类型为图片
        response.setContentType("image/png");
        response.setCharacterEncoding("UTF-8");
        // 在内存中创建图象
        int width = 60, height = 20;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics g = image.getGraphics();
        //设定背景色
        g.setColor(new Color(200, 200, 200));
        g.fillRect(0, 0, width, height);
        String s="0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        char [] c=s.toCharArray(); //将字符串通过toCharArray()方法,转化为字符数组
        StringBuffer str=new StringBuffer();
        ThreadLocalRandom crandom=ThreadLocalRandom.current();//生成随机数的current()方法
        for(int i=0;i<4;i++){
            char code=c[crandom.nextInt(0,s.length())];//随机获取字符数组中的一个字符
            str.append(code); //将字符通过append()方法增加到字符串中
        }
        //取随机产生的验证码(4位数字)
        Random rnd = new Random();
        // nextInt 得到一个0~8999的值, 写成下面的写法是为了保证最少有4位数
        g.setColor(Color.black);
        g.setFont(new Font("", Font.PLAIN, 20));
        g.drawString(str.toString(), 10, 17);
        //将验证码存入session
        // 把验证码存到session里面,等一下验证的时候需要核对验证码是否正确
        // 每次刷新验证码,其实session里面的验证码也会更新
        // 因为后面的值把前面的值替换掉了
        request.getSession().setAttribute("randStr", str.toString());
        //将验证码显示到图象中
        // 随机产生100个干扰点,使图象中的验证码不易被其他程序探测到
        for (int i = 0; i < 100; i++) {
            int x = rnd.nextInt(width);
            int y = rnd.nextInt(height);
            g.drawOval(x, y, 1, 1);
        }
        ImageIO.write(image, "png", response.getOutputStream());
        // 输出图象到页面
        ServletOutputStream out = response.getOutputStream();
        out.flush();
        out.close();
    }
}

三、验证码的验证:

@Controller
public class ValidateServlet extends HttpServlet {
    @Autowired
    private Jwt jwt;
    @Autowired
    private YongHuMapper yongHuMapper;
    @RequestMapping("/servlet")
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        //得到提交的验证码
        String code = request.getParameter("code");
        //获取session中的验证码
        System.out.println(code);
        HttpSession session = request.getSession();
        String randStr = (String) session.getAttribute("randStr");
        System.out.println(randStr);
        PrintWriter out = response.getWriter();
        // request请求发过来的验证码和session里面的验证码进行核验
        if (code.equals(randStr)) {
                request.getSession().setAttribute("login", token);
                request.getRequestDispatcher("/login").forward(request, response);
            }else{
                out.print("登录失败!");
            }
        } else {
            out.println("验证码错误!");
        }
    }
}

四、显示验证码:

<!doctype html>
<html lang="ch" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <title>用户登录界面</title>
    <script>
        function refresh() {
            // 创建一个新的XHR对象
            var xhr = new XMLHttpRequest();
            var newurl = "/captcha";
            // 初始化一个GET请求
            xhr.open('GET', newurl, true);

            // 设置响应类型为blob
            xhr.responseType = 'blob';
            // 当请求加载完成时
            xhr.onload = function () {
                if (this.status === 200) {
                    // 创建一个新的URL表示指定的File对象或Blob对象
                    // 将img的src设置为新的URL
                   imgValidate.src = URL.createObjectURL(this.response);
                }
            };
            xhr.send();
        }
    </script>
</head>
<body>
<img name="imgValidate" border=0 th:src="@{/captcha}" onclick="refresh()">
</body>
</html>

 

文章到此结束!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值