kaptcha生成验证码

Meven的pom.xml中加入



     com.github.axet
     kaptcha
     0.0.9

Spring中声明


    
        
            
                
                    yes
                    105,179,90
                    blue
                    125
                    60
                    45
                    code
                    4
                    宋体,楷体,微软雅黑
                
            
        
    

编写Controller

@Controller
@RequestMapping("/account")
public class AccountController extends AdminBaseController {

    Producer captchaProducer = null;

    @Autowired
    public void setCaptchaProducer(Producer captchaProducer) {
        this.captchaProducer = captchaProducer;
    }

    @RequestMapping("/kaptchaGet")
    public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        // store the text in the session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        System.out.println("Captchca:"+request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResult login(LoginModel model,HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

        /*if (!model.getCaptcha().equals(captcha))
            return ajaxResult(false, "验证码不正确");*/

        ......

        return ajaxResult(true,"");
    }

}

login界面

如果看不清楚,请单击图片刷新!     点击刷新

Js

function refreshCaptcha(){
    var ran = Math.floor(Math.random() * 100)
    $('#captcha1').attr('src','/account/kaptchaGet?' + ran);
}

完成效果

kaptcha生成验证码_第1张图片

你可能感兴趣的:(Java)