Kaptcha配置CaptchaConfig和控制CaptchaController

博客介绍了在Java和Spring Boot环境下实现验证码功能的方法。前端调用后端接口可使用验证码,还提及了Kaptcha所需依赖(版本号不一),以及配置类CaptchaConfig.class和控制类CaptchaController.class 。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端调用对应的后端接口即可使用验证码

Kaptcha所需依赖(版本号不一)
<!-- Kaptcha -->
<dependency>
     <groupId>com.github.penggle</groupId>
     <artifactId>kaptcha</artifactId>
     <version>2.3.2</version>
</dependency>
配置类CaptchaConfig.class (包自导)
@Configuration
public class CaptchaConfig {

   @Bean
   public DefaultKaptcha defaultKaptcha() {
       //验证码生成器
       DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
       //配置
       Properties properties = new Properties();
       //是否有边框
       properties.setProperty("kaptcha.border", "yes");
       //设置边框颜色
       properties.setProperty("kaptcha.border.color", "105,179,90");
       //边框粗细度,默认为1
       // properties.setProperty("kaptcha.border.thickness","1");
       //验证码
       properties.setProperty("kaptcha.session.key", "code");
       //验证码文本字符颜色 默认为黑色
       properties.setProperty("kaptcha.textproducer.font.color", "blue");
       //设置字体样式
       properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
       //字体大小,默认40
       properties.setProperty("kaptcha.textproducer.font.size", "30");
       //验证码文本字符内容范围 默认为abced2345678gfynmnpwx
       // properties.setProperty("kaptcha.textproducer.char.string", "");
       //字符长度,默认为5
       properties.setProperty("kaptcha.textproducer.char.length", "4");
       //字符间距 默认为2
       properties.setProperty("kaptcha.textproducer.char.space", "4");
       //验证码图片宽度 默认为200
       properties.setProperty("kaptcha.image.width", "100");
       //验证码图片高度 默认为40
       properties.setProperty("kaptcha.image.height", "40");
       Config config = new Config(properties);
       defaultKaptcha.setConfig(config);
       return defaultKaptcha;
   }

}
控制类CaptchaController.class (包自导)
@RestController
public class CaptchaController {

   @Autowired
   private DefaultKaptcha defaultKaptcha;

   @ApiOperation(value = "验证码")
   @GetMapping(value = "/captcha", produces = "image/jpeg")
   public void captcha(HttpServletRequest request, HttpServletResponse response) {
       // 定义response输出类型为image/jpeg类型
       response.setDateHeader("Expires", 0);
       // Set standard HTTP/1.1 no-cache headers.
       response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
       // 设置IE扩展的HTTP / 1.1无缓存标头(使用addHeader)。
       response.addHeader("Cache-Control", "post-check=0, pre-check=0");
       // 设置标准的HTTP / 1.0无缓存标头。
       response.setHeader("Pragma", "no-cache");
       // 返回一张图片
       response.setContentType("image/jpeg");
       //-------------------生成验证码 begin --------------------------
       //获取验证码文本内容
       String text = defaultKaptcha.createText();
       System.out.println("验证码内容:" + text);
       //将验证码文本内容放入session
       request.getSession().setAttribute("captcha", text);
       //根据文本验证码内容创建图形验证码
       BufferedImage image = defaultKaptcha.createImage(text);
       ServletOutputStream outputStream = null;
       try {
           outputStream = response.getOutputStream();
           //输出流输出图片,格式为jpg
           ImageIO.write(image, "jpg", outputStream);
           outputStream.flush();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           if (null != outputStream) {
               try {
                   outputStream.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       //-------------------生成验证码 end --------------------------
   }
}
Ruoyi-Cloud集成行为验证码可以通过引入第三方库Kaptcha来实现。下面是实现步骤: 1. 在pom.xml文件中添加依赖: ```xml <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> ``` 2. 创建一个验证码生成器类,实现行为验证码的生成逻辑,代码如下: ```java import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; @Component public class CaptchaGenerator { @Autowired private DefaultKaptcha defaultKaptcha; /** * 生成行为验证码图片 * @param request * @param response * @throws IOException */ public void generate(HttpServletRequest request, HttpServletResponse response) throws IOException { // 设置响应头信息,禁止图像缓存 response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); // 生成验证码文本 String text = defaultKaptcha.createText(); // 将验证码文本保存到session中 request.getSession().setAttribute("captcha", text); // 创建验证码图片 BufferedImage image = defaultKaptcha.createImage(text); // 将验证码图片输出到客户端 try (OutputStream out = response.getOutputStream()) { ImageIO.write(image, "jpg", out); out.flush(); } } /** * 验证行为验证码 * @param request * @param inputText * @return */ public boolean validate(HttpServletRequest request, String inputText) { String captcha = (String) request.getSession().getAttribute("captcha"); if (captcha == null) { return false; } if (!captcha.equals(inputText)) { return false; } return true; } /** * 配置Kaptcha * @return */ public DefaultKaptcha getDefaultKaptcha() { Properties properties = new Properties(); // 图片宽度 properties.setProperty("kaptcha.image.width", "150"); // 图片高度 properties.setProperty("kaptcha.image.height", "50"); // 字符集 properties.setProperty("kaptcha.textproducer.char.string", "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"); // 字符长度 properties.setProperty("kaptcha.textproducer.char.length", "4"); // 字符间距 properties.setProperty("kaptcha.textproducer.char.space", "5"); // 字体大小 properties.setProperty("kaptcha.textproducer.font.size", "30"); // 干扰线颜色 properties.setProperty("kaptcha.noise.color", "black"); // 干扰线数量 properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } } ``` 3. 在Spring Boot配置类中注入验证码生成器类,并将Kaptcha配置为Bean: ```java import com.google.code.kaptcha.impl.DefaultKaptcha; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CaptchaConfig { /** * 注入验证码生成器 * @return */ @Bean public CaptchaGenerator captchaGenerator() { CaptchaGenerator captchaGenerator = new CaptchaGenerator(); captchaGenerator.setDefaultKaptcha(defaultKaptcha()); return captchaGenerator; } /** * 配置Kaptcha * @return */ @Bean public DefaultKaptcha defaultKaptcha() { return captchaGenerator().getDefaultKaptcha(); } } ``` 4. 在需要使用验证码的Controller中调用验证码生成器的generate方法生成验证码图片,代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class CaptchaController { @Autowired private CaptchaGenerator captchaGenerator; @GetMapping("/captcha") public void generate(HttpServletRequest request, HttpServletResponse response) throws IOException { captchaGenerator.generate(request, response); } } ``` 5. 在登录接口中调用验证码生成器的validate方法验证用户输入的验证码是否正确,代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; @Controller public class LoginController { @Autowired private CaptchaGenerator captchaGenerator; @PostMapping("/login") public String login(HttpServletRequest request, @RequestParam String captcha) { boolean valid = captchaGenerator.validate(request, captcha); if (!valid) { // 验证码错误 return "redirect:/login?error"; } // 验证码正确,进行登录操作 // ... return "redirect:/index"; } } ``` 以上就是在Ruoyi-Cloud中集成行为验证码的步骤。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值