Captcha 验证码Example

maven依赖

防止和spring中的servlet冲突

<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>

 

后端代码

/**
     * 获取验证码图片
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/captcha-image")  
    public ModelAndView handleRequest
        (HttpServletRequest request, HttpServletResponse response) {  

        ServletOutputStream out = null;
        try {
            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 “Constants.KAPTCHA_SESSION_KEY“是Key
            request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
            // create the image with the text  
            //System.out.println(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
            BufferedImage bi = captchaProducer.createImage(capText);  
            out = response.getOutputStream();  
            // write the data out  
            ImageIO.write(bi, "jpg", out);
            out.flush();  
            logger.info("*****服务端验证码:*******" + capText);
        } catch (IOException e) {
            logger.info("*****服务端验证码异常*******" + e.getMessage());
            e.printStackTrace();
        }  
        finally {  
               try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.info("*****关流失败*****"+e.getMessage());
            }
        }  
        return null;  
    } 

 

前端

直接访问映射验证码路径即可

后台校验

获取session中的验证码校验即可 Constants.KAPTCHA_SESSION_KEY为验证码的key

欢迎指正,交流沟通,共同进步!

posted @ 2017-04-17 16:25  丨Mars  阅读(1611)  评论(0编辑  收藏  举报