快速学会SpringBoot图形验证码生成:一步步教你打造安全验证

1.效果图

2.pom.xml

 <!-- 验证码配置-->
        <dependency>
            <groupId>com.github.axet</groupId>
            <artifactId>kaptcha</artifactId>
            <version>0.0.9</version>
        </dependency>

3.config配置类

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 org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Properties;

/**
 * 图形验证码配置类
 */
@Configuration
public class KaptchaConfig implements WebMvcConfigurer {
    @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");
        Config config=new Config(properties);
        DefaultKaptcha defaultKaptcha =new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

4.SmsService接口类

public interface SmsService {
    Result sendAliSms(String number) throws ClientException, com.aliyuncs.exceptions.ClientException;

    ServletOutputStream patternCode(HttpServletResponse response) throws IOException;

}

5.SmsServiceImpl业务类


import com.google.code.kaptcha.Producer;
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private Producer producer;


  /**
     * 获取图型验证码
     */
    @Override
    public ServletOutputStream patternCode(HttpServletResponse response) throws IOException {
        String text= producer.createText();//验证码内容
        BufferedImage image=producer.createImage(text);//验证码图片流
        ServletOutputStream out =response.getOutputStream();
        ImageIO.write(image,"jpg",out);
        IOUtils.closeQuietly(out);
        存缓存
        //redisDao.vSet(text,text,300);
        return out;
    }

}

6.SmsController控制方法

/**
 * 短信
 * 验证码
 * 工具类
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

     @Resource
    private SmsService smsService;


 /**
     * 发送图像验证码
     */
    @GetMapping("/patternCode")
    public ServletOutputStream patternCode(HttpServletResponse response) throws IOException {
       return smsService.patternCode(response);
    }

}

7.推荐程序员必备网站

天梦星服务平台 (tmxkj.top)icon-default.png?t=N7T8https://tmxkj.top/#/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值