目录
一、spring使用kaptcha
1导入依赖
2. 配置文件设置
3.编写请求验证码
4.使用
二、springboot的使用
一、spring使用kaptcha
1导入依赖
<!--验证码--><dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version><exclusions><exclusion><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId></exclusion></exclusions></dependency>
2. 配置文件设置
<bean id="config" class="com.google.code.kaptcha.util.Config"><constructor-arg index="0" ><props><!--验证码是否有边框--><prop key="kaptcha.border">yes</prop><prop key="kaptcha.border.color">105,179,90</prop><prop key="kaptcha.textproducer.font.color">blue</prop><!--图片的宽高--><prop key="kaptcha.image.width">110</prop><prop key="kaptcha.image.height">32</prop><prop key="kaptcha.textproducer.font.size">30</prop><prop key="kaptcha.session.key">code</prop><!--验证码有几个字--><prop key="kaptcha.textproducer.char.length">4</prop><prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop></props></constructor-arg></bean>
3.编写请求验证码
package com.sofwin.controller;import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;@Controller
public class CodeController {@Autowiredprivate Producer captchaProducer ;@RequestMapping("/kaptcha")public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {HttpSession session = request.getSession();response.setDateHeader("Expires", 0);response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");response.addHeader("Cache-Control", "post-check=0, pre-check=0");response.setHeader("Pragma", "no-cache");response.setContentType("image/jpeg");//生成验证码String capText = captchaProducer.createText();//将验证码传入到session域中session.setAttribute("code", capText);//向客户端写出BufferedImage bi = captchaProducer.createImage(capText);ServletOutputStream out = response.getOutputStream();ImageIO.write(bi, "jpg", out);try {out.flush();} finally {out.close();}}
}
4.使用
二、springboot的使用
参考这里:https://www.jianshu.com/p/484eb3cc54d1