验证码生成

 

/**验证码生成后台方法*/

@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());

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值