图形验证码

maven dependency:

<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>

Controller:

@Controller
public class CaptchaController {
    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
        Kaptcha kaptcha = new Kaptcha();
        kaptcha.captcha(request,response);
    }
}

Kaptcha

public class Kaptcha {
    private Properties props = new Properties();
    private Producer kaptchaProducer = null;
    private String sessionKeyValue = null;
    private String sessionKeyDateValue = null;
    //如果使用需要自定义更多配置,可以加构造函数,把配置传进来
    public Kaptcha() {
        ImageIO.setUseCache(false);
        this.props.put("kaptcha.border", "no");
        this.props.put("kaptcha.textproducer.font.color", "black");
        this.props.put("kaptcha.textproducer.char.space", "5");
        this.props.put("kaptcha.image.width", "150");
        this.props.put("kaptcha.image.height", "50");
        Config config = new Config(this.props);
        this.kaptchaProducer = config.getProducerImpl();
        this.sessionKeyValue = config.getSessionKey();
        this.sessionKeyDateValue = config.getSessionDate();
    }
    //生成图形验证码,将图片写入response,将验证码写入session
    public void captcha(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {
        resp.setHeader("Cache-Control", "no-store, no-cache");
        resp.setContentType("image/jpeg");
        String capText = this.kaptchaProducer.createText();
        WebUtils.putSession(req, resp, this.sessionKeyValue, capText);
        WebUtils.putSession(req, resp, this.sessionKeyDateValue, new Date());
        BufferedImage bi = this.kaptchaProducer.createImage(capText);
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(bi, "jpg", out);
    }
    //从session中取出放入的验证码
    public static String getGeneratedKey(HttpServletRequest request, 
    HttpServletResponse response) {
        return (String) WebUtils.getSession(request, response, "KAPTCHA_SESSION_KEY");
    }

} 

页面如何使用:

<image onclick="createCode()" src="${rc.contextPath}/captcha.jpg"/>
<script> function createCode(){ $("#codeImage").attr("src","${rc.contextPath}/numOnlyCaptcha.jpg? t="+new Date().getTime()); } </script>

你可能感兴趣的:(图形验证码)