1.demo-admin模块导入依赖
<!--kaptcha依赖-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2.创建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.创建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 = "验证码相关")
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.验证测试
image.png