获取图形验证码-java完整

2021/11/19 17:09:53

本文主要是介绍获取图形验证码-java完整,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在做验证码的时候在网上翻阅了很久资料,找到一个算是比较好的版本的图形验证码:

  • 导入jar包
      <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>  
  • 配置 kaptcha.properties文件
# 验证码配置
kaptcha.border=no
kaptcha.border.color=105,179,90
kaptcha.image.width=100
kaptcha.image.height=45
kaptcha.session.key=code
kaptcha.textproducer.font.color=blue
kaptcha.textproducer.font.size=35
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=\u5B8B\u4F53,\u6977\u4F53,\u5FAE\u8F6F\u96C5\u9ED1
  • 写配置文件 config
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.Properties;


@Configuration
@PropertySource(value = {"classpath:kaptcha.properties"})
public class CaptchaConfig {
    @Value("${kaptcha.border}")
    private String border;
    @Value("${kaptcha.border.color}")
    private String borderColor;
    @Value("${kaptcha.textproducer.font.color}")
    private String fontColor;
    @Value("${kaptcha.image.width}")
    private String imageWidth;
    @Value("${kaptcha.image.height}")
    private String imageHeight;
    @Value("${kaptcha.session.key}")
    private String sessionKey;
    @Value("${kaptcha.textproducer.char.length}")
    private String charLength;
    @Value("${kaptcha.textproducer.font.names}")
    private String fontNames;
    @Value("${kaptcha.textproducer.font.size}")
    private String fontSize;

    /**
     * 自定义 验证码生成器
     * @return
     */
    @Bean(name = "captchaProducer")
    public DefaultKaptcha getKaptchaBean(){

        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();

        //加载验证码配置
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", border);
        properties.setProperty("kaptcha.border.color", borderColor);
        properties.setProperty("kaptcha.textproducer.font.color", fontColor);
        properties.setProperty("kaptcha.image.width", imageWidth);
        properties.setProperty("kaptcha.image.height", imageHeight);
        properties.setProperty("kaptcha.session.key", sessionKey);
        properties.setProperty("kaptcha.textproducer.char.length", charLength);
        properties.setProperty("kaptcha.textproducer.font.names", fontNames);
        properties.setProperty("kaptcha.textproducer.font.size",fontSize);
        defaultKaptcha.setConfig(new Config(properties));
        return defaultKaptcha;
    }
}
  • 写接口
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.rubik.common.model.CaptchaImageModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <p>
 * 获取图形验证码 前端控制器
 * </p>
 *
 * @author MR.RP
 * @since 2021-09-24
 */
@RestController
@Api(tags = "获取验证码")
@RequestMapping("/api")
public class CaptchaController {

    @Resource
    public DefaultKaptcha defaultKaptcha;


    @GetMapping(value="/image")
    @ApiOperation(value = "获取图形验证码",notes = "获取图形验证码")
    public void kaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        // 验证码文字
        String capText = defaultKaptcha.createText();
        // 将验证码存入session 并设置2分钟后过期
        session.setAttribute("captcha_key",new CaptchaImageModel(capText,2*60));
        ServletOutputStream out = response.getOutputStream();
        BufferedImage bufferedImage =defaultKaptcha.createImage(capText);
        ImageIO.write(bufferedImage,"jpg",out);
        out.flush();
    }
}

这里笔者没有redis,所以直接写的session里面了,使用时可以用缓存;

-测试接口
启动项目后,用postman直接请求如图所示:
在这里插入图片描述



这篇关于获取图形验证码-java完整的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程