You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.7 KiB
49 lines
1.7 KiB
// com.example.demo.controller.CaptchaController.java
|
|
package com.example.demo.controller.coin;
|
|
|
|
import com.google.code.kaptcha.Producer;
|
|
import jakarta.servlet.http.HttpServletResponse;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.data.redis.core.StringRedisTemplate;
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
import org.springframework.web.bind.annotation.RequestParam;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
import javax.imageio.ImageIO;
|
|
import java.awt.image.BufferedImage;
|
|
import java.io.IOException;
|
|
import java.util.concurrent.TimeUnit;
|
|
|
|
@RestController
|
|
public class CaptchaController {
|
|
|
|
@Autowired
|
|
private Producer kaptchaProducer;
|
|
|
|
@Autowired
|
|
private StringRedisTemplate redisTemplate;
|
|
|
|
/**
|
|
* 获取图形验证码
|
|
* @param uuid 前端生成的唯一标识,用于关联验证码
|
|
*/
|
|
@GetMapping("/captcha")
|
|
public void captcha(@RequestParam String uuid, HttpServletResponse response) throws IOException {
|
|
if (uuid == null || uuid.trim().isEmpty()) {
|
|
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "uuid is required");
|
|
return;
|
|
}
|
|
|
|
// 生成验证码文本和图片
|
|
String code = kaptchaProducer.createText();
|
|
BufferedImage image = kaptchaProducer.createImage(code);
|
|
|
|
// 存入 Redis,5分钟过期
|
|
redisTemplate.opsForValue().set("CAPTCHA:" + uuid, code, 5, TimeUnit.MINUTES);
|
|
|
|
// 输出图片
|
|
response.setHeader("Cache-Control", "no-store");
|
|
response.setContentType("image/jpeg");
|
|
ImageIO.write(image, "jpg", response.getOutputStream());
|
|
}
|
|
}
|