- springboot 项目引入依赖
-
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.3.2</version> </dependency>
工具包↑
-
编写controller测试类(使用hutool工具生产验证码图片)根据自己的情况使用,网上很多生成验证码工具
-
package com.suziqing.bootdotest.controller; import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.LineCaptcha; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.OutputStream; @Controller @RequestMapping("/poc") public class ImgTest { /** * 验证码 */ @RequestMapping("/test11") public void test1(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { response.setContentType("image/png");//以图片形式打出 LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);//设置长和宽 lineCaptcha.createCode();//创建验证码,同事生产随机验证码字符串和验证码图片 String code = lineCaptcha.getCode();//获取到验证码 System.out.println("验证码为:"+code); OutputStream os = response.getOutputStream(); lineCaptcha.write(os);//输出 } }
-
在项目的resources目录下的static下创建xxxx.html
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript"> /** * 单击验证码图片的时候刷新当前验证码接口,从新获取新的验证码 */ function ss() { document.getElementById("img").src = "http://127.0.0.1/poc/test11?" + Math.random(); } </script> </head> <body> <form action="/poc/gettest" method="get"> <!-- <p>账号: <input type="text" name="user"/></p> <p>密码: <input type="text" name="password"/></p>--> <!-- src:请求的验证码接口地址 --> <p>验证码: <input type="text" name="yzm"/><img id="img" src="/poc/test11" alt="" onclick="ss()"/></p> <!-- <input type="submit" value="Submit"/>--> </form> </body> </html>
-
浏览器访问xxx.html页面
-
java + html 图片验证码
最新推荐文章于 2024-08-09 09:37:41 发布