1.引入maven依赖
<!--验证码-->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<artifactId>javax.servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
2.编写kaptcha配置类
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
@Component
public class KaptchaConfig {
@Bean
public DefaultKaptcha getDefaultKaptcha() {
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 图片边框
properties.setProperty("kaptcha.border", "no");
// 边框颜色
properties.setProperty("kaptcha.border.color", "105,179,90");
// 字体颜色
properties.setProperty("kaptcha.textproducer.font.color", "blue");
// 图片宽
properties.setProperty("kaptcha.image.width", "116");
// 图片高
properties.setProperty("kaptcha.image.height", "37");
// 字体大小
properties.setProperty("kaptcha.textproducer.font.size", "35");
// session key
properties.setProperty("kaptcha.session.key", "code");
// 验证码长度
properties.setProperty("kaptcha.textproducer.char.length", "4");
// 字体
properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
3.编写controller
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.google.code.kaptcha.impl.DefaultKaptcha;
/**
* Created by 12168 on 2018/10/26.
*/
@Controller
public class KaptchaCotroller {
@Autowired
private DefaultKaptcha captchaProducer;
/**
* 获取验证码 的 请求路径
* @param httpServletRequest
* @param httpServletResponse
* @throws Exception
*/
@RequestMapping("/defaultKaptcha")
public void defaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String createText = captchaProducer.createText();
httpServletRequest.getSession().setAttribute("vrifyCode", createText);
//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = captchaProducer.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
//定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream =
httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
/**
* 验证的方法
* @param httpServletRequest
* @param httpServletResponse
* @return
*/
@RequestMapping("/imgvrifyControllerDefaultKaptcha")
public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
ModelAndView andView = new ModelAndView();
String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
String parameter = httpServletRequest.getParameter("vrifyCode");
System.out.println("Session vrifyCode "+captchaId+" form vrifyCode "+parameter);
if (!captchaId.equals(parameter)) {
andView.addObject("info", "错误的验证码");
andView.setViewName("kaptcha");
} else {
andView.addObject("info", "登录成功");
andView.setViewName("kaptcha");
}
return andView;
}
}
4.编写html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head lang="en">
<meta charset="UTF-8" />
<title>hello</title>
</head>
<body>
<h1 th:text="${info}" />
<div>
<img alt="验证码" onclick = "this.src=WEB_ROOT+'defaultKaptcha?d='+new Date()*1" th:src="@{/defaultKaptcha}" />
</div>
<form th:action="@{/imgvrifyControllerDefaultKaptcha}">
<input type="text" name="vrifyCode" />
<input type="submit" value="提交"></input>
</form>
</body>
</html>
启动项目
ok,测试成功
我这里使用了thymeleaf模板,不懂可以看我另一篇博客https://blog.csdn.net/linanqi_java/article/details/83507310