ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

【Spring Boot】验证码:整合 kaptcha 生成、校对验证码

2021-07-09 18:06:03  阅读:247  来源: 互联网

标签:defaultKaptcha Spring Boot httpServletResponse 验证码 kaptcha setProperty propertie


文章目录


效果展示

失败

在这里插入图片描述
在这里插入图片描述


成功

在这里插入图片描述

在这里插入图片描述



1.导入依赖

<!--验证码组件-->
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

返回顶部


2.验证码配置类 KaptchaConfig

验证码kaptcha 属性配置大全

本类是用来进行验证码的基础样式配置,具体内容参考注释。

package com.zyx.bootweb.config;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Properties;

@Component
public class KaptchaConfig {
	@Bean
	public DefaultKaptcha getDefaultKaptcha() {
		DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
		Properties properties = new Properties();
		// 图片边框
		properties.setProperty("kaptcha.border", "yes");
		// 边框颜色
		properties.setProperty("kaptcha.border.color", "105,179,90");
		// 字体颜色
		properties.setProperty("kaptcha.textproducer.font.color", "orange");
		// 图片宽
		properties.setProperty("kaptcha.image.width", "100");
		// 图片高
		properties.setProperty("kaptcha.image.height", "40");
		// 字体大小
		properties.setProperty("kaptcha.textproducer.font.size", "35");
		// session key
		properties.setProperty("kaptcha.session.key", "code");
		// 验证码长度
		properties.setProperty("kaptcha.textproducer.char.length", "4");
		// 字体
		properties.setProperty("kaptcha.textproducer.font.names", "微软雅黑");
		// 验证码字符集
		properties.setProperty("kaptcha.textproducer.char.string","1234567890abcdefghijklmnpqrstuvwxyz");

		Config config = new Config(properties);
		// 使配置生效
		defaultKaptcha.setConfig(config);

		return defaultKaptcha;
	}
}

返回顶部


3.Controller层:验证码生成

/**
* 1、验证码工具
*/
@Autowired
DefaultKaptcha defaultKaptcha;

/**
* 2、生成验证码
 *
 * @param httpServletRequest
 * @param httpServletResponse
 * @throws Exception
 */
@RequestMapping("/defaultKaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws Exception {
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {
        // 生产验证码字符串并保存到session中
        String createText = defaultKaptcha.createText();
        httpServletRequest.getSession().setAttribute("rightCode", createText);
        // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        ImageIO.write(challenge, "jpg", jpegOutputStream);
    } catch (IllegalArgumentException e) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}

返回顶部


4.Controller层:验证码校验

/**
* 3、校对验证码
* @param httpServletRequest
* @param httpServletResponse
* @return
*/
@RequestMapping("/checkCode")
public ModelAndView checkCode(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, HttpSession session) {
   ModelAndView andView = new ModelAndView();
   String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
   String tryCode = (String) session.getAttribute("tryCode");
   System.out.println("rightCode:" + rightCode + " ———— tryCode:" + tryCode);
   if (!rightCode.equals(tryCode)) {
       andView.addObject("msg", "验证码错误");
       andView.setViewName("login");
   } else {
       andView.addObject("msg", "登录成功");
       andView.setViewName("admin/main");
   }
   return andView;
}

返回顶部


5.Html页面调用

<!--   验证码   -->
<div class="inputText">
    <span class="iconfont icon-prompt"></span>
    <input type="text" id="code" name="tryCode" placeholder="VerifyCode" style="background-color: #FFFFFF00; "/>
    <img style="vertical-align:middle;" alt="验证码" onclick="this.src='/defaultKaptcha?d='+new Date()*1" src="/defaultKaptcha"/>
</div>

onclick:实现点击验证码图片进行刷新效果!

这里本人在使用网上的案例时,出现一个问题,就是检验的时候获取不到提交的验证码信息,会显示为null值。但是F12查看确认是提交了的。

所以本人换了种方式,直接获取到表单中的tryCode验证码,然后存贮在session中;其他登陆信息完成后,最后检查验证码,此时从session中取出页面中输入的验证码,与正确的验证码进行对比。
在这里插入图片描述
在这里插入图片描述

返回顶部


参考:使用 SpringBoot + kaptcha 生成、校对 验证码

标签:defaultKaptcha,Spring,Boot,httpServletResponse,验证码,kaptcha,setProperty,propertie
来源: https://blog.csdn.net/qq_45797116/article/details/118611198

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有