js 關於驗證碼cookie

關於 驗證碼 cookie

網頁請求驗證碼 & 驗證碼審覈 & 看不清換一張

代碼:

  • 前臺js寫點擊事件/邏輯判斷
  • jsp生成驗證碼img

產生問題:

  • 1.某些瀏覽器能夠讀取,某些瀏覽器不能讀取驗證碼
  • 2.某些瀏覽器支持cookie,某些不支持
  • 3.localhost可以讀取,服務器不能讀取

解決思路:

  • 1.jsp中設置cookie的路徑
 cookie.setPath("/");//表示本project下文件都能訪問到該cookie
  • 2.瀏覽器設置隱私,允許讀取cookie
  • 3.查看服務器的系統時間,如果服務器時間與標準時間有差異,調整cookie的存活時間
  cookie.setMaxAge(600);//表示本cookie600秒之後失效

分享部分代碼

jsp:
<%@ page contentType="image/jpeg"
         import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*"
         pageEncoding="utf-8"%>
<%!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);
}%>
<%
  out.clear();//這句針對resin服務器,如果是tomacat可以不要這句
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);
  int width = 60, height = 20;
  BufferedImage image = new BufferedImage(width, height,
          BufferedImage.TYPE_INT_RGB);
  Graphics g = image.getGraphics();
  Random random = new Random();
  g.setColor(getRandColor(200, 250));
  g.fillRect(0, 0, width, height);
  g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
  g.setColor(getRandColor(160, 200));
  for (int i = 0; i < 155; i++) {
    int x = random.nextInt(width);
    int y = random.nextInt(height);
    int xl = random.nextInt(12);
    int yl = random.nextInt(12);
    g.drawLine(x, y, x + xl, y + yl);
  }
  String sRand = "";
  for (int i = 0; i < 4; i++) {
    String rand = String.valueOf(random.nextInt(10));
    sRand += rand;
    g.setColor(new Color(20 + random.nextInt(110), 20 + random
            .nextInt(110), 20 + random.nextInt(110)));
    //g.drawString(rand, 13 * i + 6, 16);
    g.drawString(rand, 13 * i + 6, 16);
  }
  // 將認證碼存入SESSION
  //session.setAttribute("sRand", sRand);
  g.dispose();
//  out.println("localStorage.setItem('sRand',"+ sRand +");");
  Cookie cookie=new Cookie("sRand", sRand);
  cookie.setMaxAge(600);
  cookie.setPath("/");
  response.addCookie(cookie);
  ImageIO.write(image, "JPEG", response.getOutputStream());
%>

html:
   <img src="image.jsp" id="imgDiv" style="...">

js 驗證驗證碼是否輸入正確:
   if(code != $.cookie('sRand')){
            $('input[name="code"]').val("");
            alertError("請填寫正確的驗證碼");
            return;
        }

js 更換驗證碼:
    function changeImg() {
        console.log("changeImg");
        $('input[name="code"]').val("");//清空輸入框
        $("#imgDiv").attr('src','image.jsp?'+Math.random());
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章