java + html 图片验证码

  1. springboot 项目引入依赖
    1. <dependency>
          <groupId>cn.hutool</groupId>
          <artifactId>hutool-all</artifactId>
          <version>4.3.2</version>
      </dependency>

      工具包↑

    2. 编写controller测试类(使用hutool工具生产验证码图片)根据自己的情况使用,网上很多生成验证码工具

    3. 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);//输出
      	}
      
      }
      

       

    4. 在项目的resources目录下的static下创建xxxx.html

    5. <!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>

       

    6. 浏览器访问xxx.html页面

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值