springboot添加加法验证码

添加验证码

效果如下:

 

 

步骤:

引入pom

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

编写配置类:

package cn.taotao.config;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

@Configuration
public class KaptachaConfig {

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        //如果需要生成算法验证码加上一下配置
        properties.put("kaptcha.textproducer.char.string", "1234567890");
        //如果需要去掉干扰线
        //properties.put("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
 
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }


}

编写图像输出类

@Resource
    private StringRedisTemplate stringRedisTemplate;
 
    @Resource
    private Producer producer;
 
 
    @RequestMapping("/number.jpg")
    public void number(HttpServletResponse response ,HttpServletRequest request) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
 
        //生成文字验证码
        String text = producer.createText();
 
        //个位数字相加
        String s1 = text.substring(0, 1);
        String s2 = text.substring(1, 2);
        int count = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
 
        //生成图片验证码
        BufferedImage image = producer.createImage(s1 + "+" + s2 + "=?");
 
        //保存 redis key 自己设置
        //stringRedisTemplate.opsForValue().set("veriflycode",String.valueOf(count));
        HttpSession session = request.getSession();
        session.setAttribute("kaptcha",String.valueOf(count));  
        
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

编写controller

@RequestMapping("/login")
    public String login(@RequestParam("username") String username, 
        @RequestParam("password") String password,@RequestParam("kaptcha") String kaptcha,Map<String ,Object> map,HttpServletRequest request) {    
        // 内联页面统计次数
        this.domainService.updateLoginHit();
        if(!request.getSession().getAttribute("kaptcha").equals(kaptcha)) {
            System.err.println(request.getSession().getAttribute("kaptcha"));
            map.put("errors","验证码错误");
            return "admin116/login";
        }

。。。。。。。。。。。。。。。。

 

posted @ 2021-08-06 08:11  琴声清幽  阅读(206)  评论(0编辑  收藏  举报