1.新建图形验证码实体类:
/**
* 图片验证码
*
* @author zhaohaibin
*/
@Data
public class ImageCode {
private BufferedImage image;
private String code;
private LocalDateTime expireTime;
/**
* @param image
* @param code
* @param expireIn - 超时时间(秒)
*/
public ImageCode(BufferedImage image, String code, int expireIn) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
}
public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
this.image = image;
this.code = code;
this.expireTime = expireTime;
}
/**
* 是否过期验证
*
* @return
*/
public boolean isExpried() {
return LocalDateTime.now().isAfter(expireTime);
}
}
2.新建图形验证码控制器及生成逻辑:
/**
* 验证码控制器
*
* @author zhaohaibin
*/
@RestController
public class ValidateCodeController {
public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
ImageCode imageCode = createImageCode(request);
sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
}
/**
* 生成图形验证码
*
* @param request
* @return
*/
private ImageCode createImageCode(HttpServletRequest request) {
int width = 67;
int height = 23;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g =<