springboot集成kaptcha生成图片验证码
硅谷探秘者
2020-03-02发表
0
0
1361
pom依赖
<properties>
<kaptcha.version>0.0.9</kaptcha.version>
</properties>
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
生成验证码的配置类
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;
/**
* 生成验证码配置类
*/
@Configuration
public class KaptchaConfig {
@Bean
public DefaultKaptcha producer() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.textproducer.char.space", "5");
properties.put("kaptcha.textproducer.font.color", "blue");
properties.put("kaptcha.textproducer.char.length", "4");
properties.put("kaptcha.image.height", "40");
properties.put("kaptcha.image.width", "160");
properties.put("kaptcha.textproducer.font.size", "30");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
获取图片验证码接口
@Autowired
private Producer producer;
/**
* 获取验证码图片
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/photo",method=RequestMethod.GET)
public void captcha(HttpServletResponse response,HttpServletRequest request)throws ServletException, IOException {
response.setHeader("Cache-Control", "no-store, no-cache");
response.setContentType("image/jpeg");
//生成文字验证码
String text = producer.createText();
//生成图片验证码
BufferedImage image = producer.createImage(text);
//保存到shiro session(注意:如果没有securityManager配置,则暂时无法工作,测试时先注释掉)
request.getSession().setAttribute("code",text);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(image, "jpg", out);
out.flush();
return ;
}
效果
