Springboot 集成 Kaptcha 验证码

  • 2018-09-25 10:27:28
  • 1481
  • 0



pom.xml 依赖:


<!-- 验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>



KaptchaConfig 配置类:



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() {
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.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", "135");
        // 图片高
        properties.setProperty("kaptcha.image.height", "30");
        // 字体大小
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        // session key
        properties.setProperty("kaptcha.session.key", "kaptchaCode");
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", "5");
        // 使用那些字符生成验证码
        properties.setProperty("kaptcha.textproducer.char.string", "ACDEFHKPRSTWX345679");
        // 使用哪些字体
        properties.setProperty("kaptcha.textproducer.font.names", "Arial");
        // 干扰线颜色
        properties.setProperty("kaptcha.noise.color", "black");
        // 图片样式阴影
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
         return defaultKaptcha;
    }
 }





KaptchaController 类:




import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ganjiangps.wangdaibus.common.controller.BaseController;
import com.google.code.kaptcha.impl.DefaultKaptcha;
/**
 * kaptcha 验证码
 * 
 * @author cjm
 *
 */
@RequestMapping("/kaptcha")
@Controller
public class KaptchaController extends BaseController{
 
    @Resource
    DefaultKaptcha defaultKaptcha;
    /**
     * 生成验证码
     * @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 = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.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();
    }
    
    @RequestMapping("/VerifyKaptcha")
    public void VerifyKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        String  code = request.getParameter("code");//用户输入的验证码
        System.out.println(code);
        //缓存的验证码
        String scode = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        System.out.println(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY "==" scode);
        boolean flag = false;
        if(code != null && scode != null && code.equalsIgnoreCase(scode)){
        flag = true;
        }
        
        if(flag){
        System.out.println("验证成功");
        }else{
        System.out.println("验证失败");
        }
    }
  
}




测试jsp:


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>验证码测试jsp</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
 </head>
<body>
 <div>
        <!-- 后面添加参数起到清除缓存作用 -->
        <img alt="验证码" onclick="this.src='/kaptcha/defaultKaptcha?d=' new Date()*1" src="/kaptcha/defaultKaptcha" />
    <form action="/kaptcha/VerifyKaptcha" > 
        <input type="text" name="code" />
        <input type="submit" value="提交" class="btn btn-success"></input>
    </form>
 
     </div>
   </body>
</html>



启动访问jsp显示  如图:




回复
举报
全部回复(0)

参与讨论