15_Spring Boot集成AJ-Captcha实现滑动验证码功能
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
@RestController
public class CaptchaController {
@Autowired
private Producer kaptchaProducer;
@GetMapping("/captcha")
public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// 获取验证码文本内容
String captchaText = kaptchaProducer.createText();
// 生成验证码图片
BufferedImage challenge = kaptchaProducer.createImage(captchaText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
// 将验证码文本内容保存到session中
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, captchaText);
// 设置响应头
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
// 将图片输出到客户端
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(jpegOutputStream.toByteArray());
responseOutputStream.flush();
responseOutputStream.close();
} finally {
if (jpegOutputStream != null) {
jpegOutputStream.close();
}
}
}
}
这段代码实现了一个简单的滑动验证码接口,当访问 /captcha
路径时,会生成一个新的验证码图片并返回给客户端。验证码文本内容保存在了session中,以供后续的登录或者其他需要验证的操作使用。
评论已关闭