SpringBoot集成Kaptcha验证码生成器快速入门Demo
    		       		warning:
    		            这篇文章距离上次修改已过428天,其中的内容可能已经有所变动。
    		        
        		                
                
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
 
@RestController
public class KaptchaController {
 
    @GetMapping("/captcha")
    public void getKaptchaImage(HttpServletResponse response) throws Exception {
        // 设置响应头
        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");
 
        // 创建Kaptcha生成验证码的工厂
        Producer kaptchaProducer = getKaptchaProducer();
 
        // 通过工厂生成验证码
        BufferedImage bufferedImage = kaptchaProducer.createImage(getKaptchaProperties());
 
        // 将验证码图片写入响应流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
 
        // 设置Session验证码属性
        // request.getSession().setAttribute("captcha", TextCaptcha);
 
        // 将输出流的内容写入响应
        response.getOutputStream().write(outputStream.toByteArray());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
 
    private Producer getKaptchaProducer() {
        return new com.google.code.kaptcha.impl.DefaultKaptcha();
    }
 
    private Config getKaptchaProperties() {
        Properties properties = new Properties();
        // 设置文本的字体
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
        // 设置文本的颜色
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
        // 设置文本的大小
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "30");
        // 设置边框
        properties.setProperty(Constants.KAPTCHA_BORDER, "no");
        // 设置背景颜色
        properties.setProperty(Constants.KAPTCHA_BACKGROUND_COLOR, "white");
        // 设置文本的长度
        properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGT           
评论已关闭