/**验证码生成后台方法*/
@RequestMapping(value = "/losepassword/getvalidatecode",method = RequestMethod.GET)
public void getVerificationCode(HttpServletRequest request,HttpServletResponse response){
int width = 64;
int height = 24;
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = environment.getAvailableFontFamilyNames();
int fontIndex = (int)(Math.random()*(fontNames.length-1));
Font mFont = new Font(fontNames[fontIndex],Font.PLAIN,height - 2);
String randomString = "ABCDEFGHJKLMNPQRSTUVWXYZ123456789";
String codeString = "";
Random random = new Random();
for (int i = 0; i < 4; i++) {
codeString+=randomString.charAt(random.nextInt(randomString.length()-1));
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(2, 2, width-3, height-3);
graphics.setFont(mFont);
graphics.setColor(Color.black);
graphics.drawRect(1, 1, width-1, height - 1);
graphics.setColor(Color.cyan);
for (int i = 0; i < 10; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
graphics.drawLine(x, y, x + xl, y + yl);
}
int red = 0, green = 0, blue = 0;
char c;
for (int i = 0; i < 4; i++) {
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
c = codeString.charAt(i);
graphics.setColor(new Color(red,green,blue));
graphics.drawString(c + " ", i * 14 + 3, height-3);
}
HttpSession session = request.getSession();
session.setAttribute("validateCode", codeString);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream out;
try {
out = response.getOutputStream();
ImageIO.write(image, "jpeg", out);
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException("生成验证码出错!",e);
}
return ;
}
/**前台调用*/
<input class="account_check" name="validate_code" type="text" value="" />
<img id="imgObj" />
<a href="#" id="freshen"> 看不清 </a>
/**js代码*/
$("#imgObj").attr("src","./losepassword/getvalidatecode");
$("#freshen").click(function(){
$("#imgObj").attr("src","./losepassword/getvalidatecode?"+Math.random());
});
$("#imgObj").click(function(){
$("#imgObj").attr("src","./losepassword/getvalidatecode?"+Math.random());
});