牛客网开发项目——2.5如何生成验证码

牛客网后端项目实战(十):生成验证码

https://code.google.com/archive/p/kaptcha

导入jar包

首先,还是老方法,在mvnrepository网站搜索kaptcha,添加到pom等待idea自动下载。

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

编写kaptcha配置类

新建一个config包,在包下新建KaptchaConfig类。

  • 首先使用@Configuration注解定义配置类
    • 从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
  • 然后使用@Bean注解定义kaptchaProducer方法。
    • 返回类型producer实际是一个接口,可以按住ctrl+鼠标左键点击Producer查看
    • 使用的DefaultKaptcha类实现了Producer接口
  • 使用properties配置kaptcha相关内容
    • 验证码图片长宽
    • 字体大小颜色
    • 验证码字符范围,我使用0-9和大写的A-Z,长度为4
    • 噪声配置,kaptcha生成的验证码图片本身已经是处理过,这里选择无噪声,也就是不加干扰
package com.neu.langsam.community.config;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {



    @Bean
    public Producer kaptchaProducer(){
        Properties properties=new Properties();
        properties.setProperty("kaptcha.image.width","100");
        properties.setProperty("kaptcha.image.height","40");
        properties.setProperty("kaptcha.textproducer.font.size","32");
        properties.setProperty("kaptcha.textproducer.font.color","0,0,0");
        properties.setProperty("kaptcha.textproducer.char.String","0123456789ABCDEFGHIJKMLNOPQRSTUVWXYZ");
        properties.setProperty("kaptcha.textproducer.char.length","4");
        properties.setProperty("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");

        DefaultKaptcha kaptcha=new DefaultKaptcha();
        Config config =new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }
}


生成随机字符,图片

1、我们在LoginController写生成验证码的请求。

  • 因为这里返回的不是网页也不是字符串,所以我们传入HttpServletResponse自己返回
  • 同时,生成验证码和图片后需要保存来核对,又是敏感数据,采用session
private static final Logger logger= LoggerFactory.getLogger(LoginController.class);

@Autowired
    private Producer kaptchaProducer;

@RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
    public void getKaptcha(HttpServletResponse response, HttpSession session){
        //生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);

        //将验证码存入session
        session.setAttribute("kaptcha",text);

        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            logger.error("响应验证码失败"+e.getMessage());
        }
    }

运行项目,进入登录页面,前端js逻辑已经处理好了,所以可以直接正常显示。

2、将动态生成验证码的图片配置到,login.html中
3、用js实现,点击超链接就实现动态刷新功能

// global.js 文件里定义全局常量
var CONTEXT_PATH ="/community";
<div class="col-sm-4">
	<img th:src="@{/kaptcha}" id="kaptcha" style="width:100px;height:40px;" class="mr-2"/>
	<a href="javascript:refresh_kaptcha();" class="font-size-12 align-bottom">刷新验证码</a> //调用refresh_kaptcha()函数
</div>
......
<script>
		function refresh_kaptcha(){
			var path = CONTEXT_PATH + "/kaptcha?p="+Math.random();  
			$("#kaptcha").attr("src", path);
		}
</script>

var path = CONTEXT_PATH + “/kaptcha?p=”+Math.random(); 是为了随机修改路径,避免路径一致而导致浏览器不访问的情况。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值