zoukankan      html  css  js  c++  java
  • SpringBoot+EasyCaptcha实现验证码功能

    一、EasyCaptcha简介
    Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。
    开源地址 https://github.com/whvcse/EasyCaptcha

    二、SpringBoot项目如何使用
    1、初始化一个基本的SpringBoot项目
    2、引入EasyCaptcha 依赖

            <dependency> <groupId>com.github.whvcse</groupId>
                <artifactId>easy-captcha</artifactId>
                <version>1.6.2</version>
            </dependency>

    3、生成验证码

    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception{
        GifCaptcha gifCaptcha = new GifCaptcha(130,48,4);
        CaptchaUtil.out(gifCaptcha, request, response);
        String verCode = gifCaptcha.text().toLowerCase();
        request.getSession().setAttribute("CAPTCHA",verCode);  //存入session 
    }

    4、校验验证码

    public class LoginController {
    
        private static final Logger log = LoggerFactory.getLogger(LoginController.class);
        @GetMapping("/")
        public String login() {
            return "/test";
        }
    
        @PostMapping("/test")
        public String test(HttpServletRequest request, HttpServletResponse response) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String captcha = request.getParameter("code");
            String sessionCode = request.getSession().getAttribute("CAPTCHA").toString();
            if(sessionCode == null ||StringUtils.isEmpty(sessionCode)){
                return "验证码为空";
            }
            if(captcha.equals(sessionCode)){
                return "验证通过";
            }
            return "验证失败";
        }
    }

    5、前端html中页面代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script type="text/javascript" src="./lib/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
    
    <div>
        <form action="http://localhost:8088/test" method="post">
            <div>
                <label>用户名</label>
                <input type="text" name="username" id="username">
                <label>密码</label>
                <input type="password" name="password" id="password">
                <label>验证码</label>
                <img src="/captcha" height="48px" width="130px">
                <input type="text" name="code" id="code">
                <input type="submit" value="登录">
            </div>
        </form>
    </div>
    </body>
    </html>

    ref:EasyCaptcha: Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。 (gitee.com)

  • 相关阅读:
    105.UDP通信实现广播
    104.tcp多线程读写实现群聊
    103.tcp通信实现远程控制
    102.tcp实现多线程连接与群聊
    101.自动注入
    100.dll调用
    99.遍历进程并直接写入内存
    98.TCP通信传输文件
    97.TCP通信
    96.udp通信
  • 原文地址:https://www.cnblogs.com/cy0628/p/15166486.html
Copyright © 2011-2022 走看看