SSM中的登陆验证码

时间:2023-12-20 14:04:38

@Autowired
private Producer captchaProducer = null;
/**
* 后台登录验证码
* @param request
* @param response
* @param name
* @throws IOException
*/
@RequestMapping({"/verify.htm"})
public void verify(HttpServletRequest request, HttpServletResponse response, String name) throws IOException
{


HttpSession session = request.getSession();
String sRand = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);


//logger.info(sRand+"scyzm---");
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.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
/*if (CommUtil.null2String(name).equals(""))

else {
session.setAttribute(name, capText);
}*/
session.setAttribute("verify_code", capText);
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}

}


private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}