Spring Boot集成kaptcha实现表单图片验证

 

  Kaptcha是一个基于SimpleCaptcha的验证码开源项目,Kaptcha的使用比较方便,只需添加jar包依赖之后简单地配置就可以使用了。

添加依赖

如果你使用maven来统一管理jar包,则在工程的pom.xml中添加dependency

1 <dependency>  
2     <groupId>com.google.code.kaptcha</groupId>  
3     <artifactId>kaptcha</artifactId>  
4     <version>2.3.2</version>  
5 </dependency>

如果是非maven管理的项目,则直接在官网下载kaptcha的jar包,然后添加到项目lib库中,下载地址:

Kaptcha

原理

  • 后台生成验证码图片,将图片传到前台。

  • 后台在session中保存验证码内容。

  • 前台输入验证码后传到后台在后台取出session中保存的验证码进行校验。

注意,验证码的明文是不能传送到前端的。前端内容都是透明的,不安全。验证码是用来防机器人并不是单单防人。如果把验证码明文传到前端很容易就会被破解。

图片验证码的配置类KaptchaConfig

定义图片的信息,包括边框,颜色等等

 1 import org.springframework.stereotype.Component;
 2  3 import java.util.Properties;
 4  5 import org.springframework.context.annotation.Bean;
 6 import com.google.code.kaptcha.impl.DefaultKaptcha;
 7 import com.google.code.kaptcha.util.Config;
 8  9 /**
10  * @program: component
11  * @author: ***
12  * @description: 这是图片验证的配置类
13  * @create: 2019/4/5 10:51
14  **/
15 @Component
16 public class KaptchaConfig {
17 18     @Bean
19     public DefaultKaptcha getDefaultKaptcha() {
20         com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
21         Properties properties = new Properties();
22         // 图片边框
23         properties.setProperty("kaptcha.border", "yes");
24         // 边框颜色
25         properties.setProperty("kaptcha.border.color", "105,179,90");
26         // 字体颜色
27         properties.setProperty("kaptcha.textproducer.font.color", "red");
28         // 图片宽
29         properties.setProperty("kaptcha.image.width", "110");
30         // 图片高
31         properties.setProperty("kaptcha.image.height", "40");
32         // 字体大小
33         properties.setProperty("kaptcha.textproducer.font.size", "30");
34         // session key
35         properties.setProperty("kaptcha.session.key", "code");
36         // 验证码长度
37         properties.setProperty("kaptcha.textproducer.char.length", "4");
38         // 字体
39         properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
40         Config config = new Config(properties);
41         defaultKaptcha.setConfig(config);
42 43         return defaultKaptcha;
44     }
45 }

KaptchaController类实现图片的生成与校验

首先一定要注入验证码工具 DefaultKaptcha

 1 @Autowired
 2     DefaultKaptcha defaultKaptcha;
 3  4 import java.awt.image.BufferedImage;
 5 import java.io.ByteArrayOutputStream;
 6  7 import javax.imageio.ImageIO;
 8 import javax.servlet.ServletOutputStream;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.stereotype.Controller;
14 import org.springframework.web.bind.annotation.RequestMapping;
15 import org.springframework.web.servlet.ModelAndView;
16 import com.google.code.kaptcha.impl.DefaultKaptcha;
17 18 /**
19  * @program: component
20  * @author: ***
21  * @description: Kaptcha控制
22  * @create: 2019/4/5 10:54
23  **/
24 @Controller
25 public class KaptchaController {
26     /**
27      * 1、验证码工具
28      */
29     @Autowired
30     DefaultKaptcha defaultKaptcha;
31 32     /**
33      * 2、生成验证码
34      *
35      * @param httpServletRequest
36      * @param httpServletResponse
37      * @throws Exception
38      */
39     @RequestMapping("/defaultKaptcha")
40     public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
41             throws Exception {
42         byte[] captchaChallengeAsJpeg = null;
43         ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
44         try {
45             // 生产验证码字符串并保存到session中
46             String createText = defaultKaptcha.createText();
47             httpServletRequest.getSession().setAttribute("rightCode", createText);
48             // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
49             BufferedImage challenge = defaultKaptcha.createImage(createText);
50             ImageIO.write(challenge, "jpg", jpegOutputStream);
51         } catch (IllegalArgumentException e) {
52             httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
53             return;
54         }
55 56         // 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
57         captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
58         httpServletResponse.setHeader("Cache-Control", "no-store");
59         httpServletResponse.setHeader("Pragma", "no-cache");
60         httpServletResponse.setDateHeader("Expires", 0);
61         httpServletResponse.setContentType("image/jpeg");
62         ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
63         responseOutputStream.write(captchaChallengeAsJpeg);
64         responseOutputStream.flush();
65         responseOutputStream.close();
66     }
67 68     /**
69      * 3、校对验证码
70      *
71      * @param httpServletRequest
72      * @param httpServletResponse
73      * @return
74      */
75     @RequestMapping("/imgvrifyControllerDefaultKaptcha")
76     public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,
77                                                          HttpServletResponse httpServletResponse) {
78         ModelAndView andView = new ModelAndView();
79         String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
80         String ClientCode = httpServletRequest.getParameter("ClientCode");
81 //        rightCode是生成码,ClientCode是表单提交码
82         System.out.println("rightCode:" + rightCode + " ———— ClientCode:" + ClientCode);
83         if (!rightCode.equals(ClientCode)) {
84             andView.addObject("info", "验证码错误");
85             andView.setViewName("index");
86         } else {
87             andView.addObject("info", "登录成功");
88             andView.setViewName("success");
89         }
90         return andView;
91     }
92 93     @RequestMapping("/toIndex")
94     public String toIndex() {
95         return "index";
96     }
97 }

前端页面Login.html

简单的一个表单就可以,此处需要注意几点:

  1. onclick="this.src='defaultKaptcha?d='+new Date()*1" //每次点击图片是刷新图片,重新生成图片

  2. src="defaultKaptcha" // 访问controller中的验证方法

1 <h1 th:text="${info}" />
2 <form action="imgvrifyControllerDefaultKaptcha" method="post">      
3     <input type="text" name="vrifyCode"/>
4     <img alt="验证码" onclick="this.src='defaultKaptcha?d='+new Date()*1"
5            src="defaultKaptcha"> </br>
6     <input type="submit" value="提交"/> 
7 </form>

实现的效果

猜你喜欢

转载自www.cnblogs.com/jeemia/p/10680581.html