1.demo-admin模塊導(dǎo)入依賴
<!--kaptcha依賴-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2.創(chuàng)建kaptcha配置類
package com.lvxk.demo.admin.config;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* KaptchaConfig
* Description: <br/>
* date: 2020/5/5 15:17<br/>
*
* @author lvxk<br />
* @since JDK 1.8
*/
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.font.color", "black");
properties.put("kaptcha.textproducer.char.space", "5");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.創(chuàng)建controller,編寫獲取驗證碼接口
package com.lvxk.demo.admin.controller;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* SysLoginController 獲取驗證碼
* Description: <br/>
* date: 2020/5/5 15:19<br/>
*
* @author lvxk<br />
* @since JDK 1.8
*/
@RestController
@RequestMapping("kaptcha")
@Api(tags = "驗證碼相關(guān)")
public class SysLoginController {
@Autowired
private Producer producer;
@GetMapping("code")
@ApiOperation(value = "獲取驗證碼(5位)")
public void captha(HttpServletResponse response, HttpServletRequest request) throws IOException {
response.setHeader("Cache-Control","no-store,no-cache");
response.setContentType("image/jpeg");
//生成文字驗證碼
String text = producer.createText();
//生成圖片驗證碼
BufferedImage image = producer.createImage(text);
//保存驗證碼到session中
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image,"jpg",out);
IOUtils.closeQuietly(out);
}
}
4.驗證測試