如果你在网上搜的话,会出来很多种方法,我接下来要写的是纯java生成验证码图片,以及校验的。
老规矩,直接复制粘贴过去用好吗
第一步:
导入依赖
<!--验证码-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
第二步:
写一个配置类,配置你生成验证码的那张图
@Configuration
public class KaptchaConfig {
/**
* 验证码生成相关
*/
@Bean
public DefaultKaptcha kaptcha() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.border.color", "105,179,90");
properties.put("kaptcha.textproducer.font.color", "blue");
properties.put("kaptcha.image.width", "125");
properties.put("kaptcha.image.height", "45");
properties.put("kaptcha.textproducer.font.size", "45");
properties.put("kaptcha.session.key", "code");
properties.put("kaptcha.textproducer.char.length", "4");
properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
第三步:
写一个Controller,让前端来调你这个接口,生成或者刷新验证码,返回一个图,如下:
@Controller
@RequestMapping("/kaptcha")
public class KaptchaController {
@Autowired
private Producer producer;
/**
* 生成验证码
*/
@RequestMapping("/code")
public void kaptcha(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = producer.createText();
// store the text in the session
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text
BufferedImage bi = producer.createImage(capText);
ServletOutputStream out = null;
try {
out = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
// write the data out
try {
ImageIO.write(bi, "jpg", out);
} catch (IOException e) {
e.printStackTrace();
}
try {
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上是生成验证码的代码,写到这里就明白了各位,校验我还没写,明天再写吧,划一会儿水~~~~~~
校验你们可以自己写,就是把前端输入的验证码和session里的验证码比较一下。如果想偷懒的话,等着看我下一篇吧。。。。。