今天發現了一個有意思的生成驗證碼的工具,研究了一下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
yml配置:
kaptcha:
height: 50
width: 200
content:
length: 4 # 字符個數
source: abcdefghjklmnopqrstuvwxyz23456789 #生成的驗證碼字符,不支持中文,自動會轉大小寫
space: 6
font:
color: 56,99,216
name: Arial #字體名稱
size: 40 #字體大小
background-color:
to: white
from: 25,60,91 #這裏可以配RGB,也可以配顏色的單詞,white,blue,red
border:
enabled: true
color: black #同理也可以RGB
thickness: 1
controller:
@Controller
@Log4j2
public class DemoController {
/**
* 1、驗證碼工具
*/
@Autowired
DefaultKaptcha defaultKaptcha;
@GetMapping("/code")
public ResponseEntity<byte[]> downloadFile(HttpServletRequest httpServletRequest) throws IOException {
// 生產驗證碼字符串並保存到session中
String createText = defaultKaptcha.createText();
httpServletRequest.getSession().setAttribute("code", createText);
// 使用生產的驗證碼字符串返回一個BufferedImage對象並轉爲byte寫入到byte數組中
BufferedImage challenge = defaultKaptcha.createImage(createText);
// 轉換流信息寫出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
ImageIO.write(challenge, "jpeg", os);
HttpHeaders headers = new HttpHeaders();
MediaType mediaType = MediaType.valueOf("image/jpeg");
headers.add("Cache-Control", "no-store");
headers.add("Pragma", "no-cache");
headers.setContentType(mediaType);
return new ResponseEntity<>(os.toByteArray(), headers, HttpStatus.OK);
}
@GetMapping("/check")
public ResponseEntity verify(HttpServletRequest request) {
String rightCode = (String) request.getSession().getAttribute("code");
String tryCode = request.getParameter("code");
HttpHeaders headers = new HttpHeaders();
if (!rightCode.equals(tryCode)) {
log.info( "錯誤的驗證碼");
return new ResponseEntity("錯誤的驗證碼", headers, HttpStatus.BAD_REQUEST);
} else {
return new ResponseEntity("成功", headers, HttpStatus.BAD_REQUEST);
}
}
}
好了,上面就是簡單的demo,剩下的就自己玩吧