kaptcha Java验证码

在项目中经常会使用验证码,kaptcha 就一个非常不错的开源框架,分享下自己在项目中的使用:

1、首先下载kaptcha 把kaptcha-2.3.2.jar包放在lib下

2、登陆页面初始化 document.getElementById("mycode").src="${pageContext.request.contextPath}/kaptcha/code?"+Math.random();

3、@RequestMapping("/kaptcha")
public class CaptchaController {

    @Autowired private Producer captchProducer;
    
    
    /**
     * 生产验证码方法
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/code")
    public ModelAndView getKaptchaImage(HttpServletRequest request,HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        //String code = session.getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();//得到验证码
        //System.out.println("******************************验证码是:"+code+"***************************");
        //设置浏览器的请求头
        response.setDateHeader("Expires", 0);
        response.addHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        
        String capText = captchProducer.createText();//创建验证码内容
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);//将验证码存入到session中
        
        BufferedImage bi = captchProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);//输出验证码图片
        out.flush();
        out.close();
        return null;
    }

原文地址:https://www.cnblogs.com/chizizhixin/p/5311619.html