在JSP验证 验证码,不用Session

来源:互联网 发布:guava 并发编程 编辑:程序博客网 时间:2024/06/07 16:30

在JS生成验证码数字,传入后台,再生成验证码。

1、JSP:

<img  id="checkCode" align="middle" title="点击刷新验证码" onclick="getNewCode()"  style="cursor: pointer;">
2、JS:

var CODE;//全局变量function createCode(){  CODE = "";      var codeLength = 4;//验证码的长度      //所有候选组成验证码的字符,可以用中文      var selectChar = new Array(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');      for(var i=0;i<codeLength;i++)      {          var charIndex = Math.floor(Math.random()*60);          CODE +=selectChar[charIndex];      }      return CODE;  }  function getNewCode(){      //显示验证码      $("#checkCode").attr("src","/utils/getValidateCodeNewMethod.do?code="+createCode());  }  

3、Java:

@RequestMapping("getValidateCodeNewMethod")public void getValidateCodeNewMethod(HttpServletRequest request,HttpServletResponse response,String code)throws Exception{     response.setContentType("image/jpeg");      response.setHeader("Cache-Control", "no-cache");      response.setHeader("Pragma", "No-cache");      response.setDateHeader("Expires", 0L);         int width = 80;      int height = 30;      BufferedImage image = new BufferedImage(width, height, 1);      Graphics g = image.getGraphics();      Random random = new Random();      g.setColor(getRandColor(200, 250));      g.fillRect(0, 0, width, height);          g.setFont(new Font("Fixedsys", Font.BOLD,28));    g.setColor(getRandColor(160, 200));      for (int i = 0; i < 155; i++) {          int x = random.nextInt(width + 100);          int y = random.nextInt(height + 100);          int xl = random.nextInt(10);          int yl = random.nextInt(12);          g.drawOval(x, y, x + xl, y + yl);      }         String sRand=code;      for (int i = 0; i < sRand.length(); i++) {                 String rand = sRand.substring(i, i+1);                 g.setColor(new Color(20 + random.nextInt(110), 20 + random                  .nextInt(110), 20 + random.nextInt(110)));          g.drawString(rand, 14 * i + 5, 25);      }       g.dispose();      ServletOutputStream imageOut = response.getOutputStream();      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(imageOut);      encoder.encode(image);     }  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);         }  



原创粉丝点击