| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package com.kxs.admin.api.handler;
- import cn.hutool.captcha.CaptchaUtil;
- import cn.hutool.captcha.LineCaptcha;
- import cn.hutool.captcha.generator.RandomGenerator;
- import com.kxs.common.core.constant.CacheConstants;
- import com.kxs.common.core.constant.SecurityConstants;
- import lombok.RequiredArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.core.io.ByteArrayResource;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.MediaType;
- import org.springframework.util.FastByteArrayOutputStream;
- import org.springframework.web.servlet.function.HandlerFunction;
- import org.springframework.web.servlet.function.ServerRequest;
- import org.springframework.web.servlet.function.ServerResponse;
- import java.util.Optional;
- import java.util.concurrent.TimeUnit;
- /**
- * 验证码生成逻辑处理类
- *
- * @author 没秃顶的码农
- * @date 2023/11/03
- */
- @Slf4j
- @RequiredArgsConstructor
- public class ImageCodeHandler implements HandlerFunction<ServerResponse> {
- private static final Integer DEFAULT_IMAGE_WIDTH = 100;
- private static final Integer DEFAULT_IMAGE_HEIGHT = 40;
- private final RedisTemplate<String, Object> redisTemplate;
- @Override
- public ServerResponse handle(ServerRequest serverRequest) {
- // 保存验证码信息
- Optional<String> randomStr = serverRequest.param("randomStr");
- //生成验证码
- RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
- LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
- lineCaptcha.setGenerator(randomGenerator);
- redisTemplate.setKeySerializer(new StringRedisSerializer());
- randomStr.ifPresent(s -> redisTemplate.opsForValue()
- .set(CacheConstants.DEFAULT_CODE_KEY + s, lineCaptcha.getCode(), SecurityConstants.CODE_TIME, TimeUnit.SECONDS));
- // 转换流信息写出
- FastByteArrayOutputStream os = new FastByteArrayOutputStream();
- lineCaptcha.write(os);
- return ServerResponse.status(HttpStatus.OK)
- .contentType(MediaType.IMAGE_JPEG)
- .body(new ByteArrayResource(os.toByteArray()));
- }
- }
|