Spring Boot集成AJ-Captcha实现滑动验证码功能
import com.ajcaptcha.Captcha;
import com.ajcaptcha.CaptchaFactory;
import com.ajcaptcha.CaptchaServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
import java.io.IOException;
@RestController
public class CaptchaController {
private final CaptchaFactory captchaFactory = new CaptchaFactory();
@GetMapping("/captcha")
public ResponseEntity<byte[]> getCaptcha(HttpServletResponse response) throws IOException, CaptchaServiceException {
// 设置响应头,浏览器不要缓存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 创建一个Captcha对象
Captcha captcha = captchaFactory.createCaptcha();
// 将图片输出为ByteArrayOutputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(captcha.getImage(), "png", outputStream);
// 设置session,存储验证码文本
request.getSession().setAttribute("captcha", captcha.getChallenge());
// 返回图片的响应实体
return new ResponseEntity<>(outputStream.toByteArray(), HttpStatus.OK);
}
}
这段代码演示了如何在Spring Boot应用中创建一个简单的控制器,用于处理获取滑动验证码的请求,并返回验证码图片。它使用了CaptchaFactory
来创建Captcha
对象,并将验证码文本存储在HTTP会话中。最后,它将验证码图片以二进制数据的形式返回给客户端。
评论已关闭