溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java后端產(chǎn)生驗(yàn)證碼后臺(tái)驗(yàn)證功能的實(shí)現(xiàn)代碼

發(fā)布時(shí)間:2020-09-11 10:55:15 來(lái)源:腳本之家 閱讀:239 作者:小秋蜀黍 欄目:編程語(yǔ)言

直接跳severlet在java后臺(tái)生成驗(yàn)證碼:

@RequestMapping(value="yzm.action")
 public void Yzm(HttpSession session,HttpServletResponse resp){
 // 驗(yàn)證碼圖片的寬度。   
   int width = 60;   
    // 驗(yàn)證碼圖片的高度。   
   int height = 20;   
   
   // 驗(yàn)證碼字符個(gè)數(shù)   
   int codeCount = 4;   
   
   int x = 0;   
   
   // 字體高度   
   int fontHeight;   
   
   int codeY;   
   
   char[] codeSequence = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };   
   x = width / (codeCount + 1);   
    fontHeight = height - 2;   
    codeY = height - 4; 
    BufferedImage buffImg = new BufferedImage(width, height,   
        BufferedImage.TYPE_INT_RGB);   
    Graphics2D g = buffImg.createGraphics();   
    // 創(chuàng)建一個(gè)隨機(jī)數(shù)生成器類   
    Random random = new Random();   
    // 將圖像填充為白色   
    g.setColor(Color.WHITE);   
    g.fillRect(0, 0, width, height);   
    // 創(chuàng)建字體,字體的大小應(yīng)該根據(jù)圖片的高度來(lái)定。   
    Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);   
    // 設(shè)置字體。   
    g.setFont(font);   
    // 畫邊框。   
//    g.setColor(Color.BLACK);   
//    g.drawRect(0, 0, width - 1, height - 1);   
    // 隨機(jī)產(chǎn)生160條干擾線,使圖象中的認(rèn)證碼不易被其它程序探測(cè)到。   
    g.setColor(Color.BLACK);   
    for (int i = 0; i < 1; i++) {   
      int x2 = random.nextInt(width);   
      int y2 = random.nextInt(height);   
      int xl = random.nextInt(12);   
      int yl = random.nextInt(12);   
      g.drawLine(x2, y2, x + xl, y2 + yl);   
    }   
    // randomCode用于保存隨機(jī)產(chǎn)生的驗(yàn)證碼,以便用戶登錄后進(jìn)行驗(yàn)證。   
    StringBuffer randomCode = new StringBuffer();
 
    int red = 0, green = 0, blue = 0;   
    // 隨機(jī)產(chǎn)生codeCount數(shù)字的驗(yàn)證碼。   
    for (int i = 0; i < codeCount; i++) {   
      // 得到隨機(jī)產(chǎn)生的驗(yàn)證碼數(shù)字。   
      String strRand = String.valueOf(codeSequence[random.nextInt(36)]);   
      // 產(chǎn)生隨機(jī)的顏色分量來(lái)構(gòu)造顏色值,這樣輸出的每位數(shù)字的顏色值都將不同。   
      red = random.nextInt(255);   
      green = random.nextInt(255);   
      blue = random.nextInt(255);   
      // 用隨機(jī)產(chǎn)生的顏色將驗(yàn)證碼繪制到圖像中。   
      g.setColor(new Color(red, green, blue));   
      g.drawString(strRand, (i + 1) * x, codeY);   
      // 將產(chǎn)生的四個(gè)隨機(jī)數(shù)組合在一起。   
      randomCode.append(strRand);   
    }   
    // 將四位數(shù)字的驗(yàn)證碼保存到Session中。   
    session.setAttribute("validateCode", randomCode.toString());   
    ServletOutputStream sos;
 try {
  sos = resp.getOutputStream();
  ImageIO.write(buffImg, "jpeg", sos);   
  sos.close();   
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }   
 }

jsp顯示頁(yè)面的代碼,點(diǎn)擊圖片刷新

<td><img id="img" src="yzm.action"/>${validateCode}</td>
      <td><input type="text" name="yzma"/><br/></td>
 $("#img").click(function(){
 $(this).attr("src","yzm.action?"+new Date().getTime());
  });

將文本框中的值傳入后臺(tái),與最開始生成驗(yàn)證碼的隨機(jī)數(shù)進(jìn)行比較即可完成驗(yàn)證。

Java后端產(chǎn)生驗(yàn)證碼后臺(tái)驗(yàn)證功能的實(shí)現(xiàn)代碼

頁(yè)面上拿到的session的值老是比驗(yàn)證碼晚一步,所以采取后臺(tái)進(jìn)行驗(yàn)證。這里我也不知道什么原因,望小伙伴們告知。。。

另一種思路,后臺(tái)生成隨機(jī)數(shù),前端生成畫布,用ajax拿隨機(jī)數(shù)

//后臺(tái)只生成隨機(jī)數(shù)
 @RequestMapping(value="random.action")
 public void findRandom (HttpServletResponse response) throws IOException{
  // 驗(yàn)證碼字符個(gè)數(shù)   
   int codeCount = 4;
   char[] codeSequence = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
   
   // 創(chuàng)建一個(gè)隨機(jī)數(shù)生成器類   
     Random random = new Random();
   // randomCode用于保存隨機(jī)產(chǎn)生的驗(yàn)證碼,以便用戶登錄后進(jìn)行驗(yàn)證。   
     StringBuffer randomCode = new StringBuffer();
     for (int i = 0; i < codeCount; i++) {   
       // 得到隨機(jī)產(chǎn)生的驗(yàn)證碼數(shù)字。   
       String strRand = String.valueOf(codeSequence[random.nextInt(36)]); 
       // 將產(chǎn)生的四個(gè)隨機(jī)數(shù)組合在一起。   
       randomCode.append(strRand);   
     }
     PrintWriter out = response.getWriter();
     out.print(randomCode);
 }

 jsp,jq,js代碼

<body>
    <canvas id="canvas" width="70" height="34"></canvas>
    <a href="javascript:;" rel="external nofollow" id="img" class="pull-right" >換一張</a>
    <input type="text" class="form-control" id="yzms" name="yzms" readonly = "readonly"  >
 </body>
 <script type="text/javascript">
    $.ajax({
 url:"random.action",
 success:function(k){
 console.log(k)
  $("#yzms").attr("value",k);
  drawPic();
 }
})
 $("#img").on("click",function(){
 var _this=$(this)
  $.ajax({
  url:"random.action",
  success:function(k){
  console.log(k)
   $("#yzms").attr("value",k);
   drawPic();
  }
 })
 }) 
 /**生成一個(gè)隨機(jī)數(shù)**/
 function randomNum(min,max){
  return Math.floor( Math.random()*(max-min)+min);
 }
 /**生成一個(gè)隨機(jī)色**/
 function randomColor(min,max){
  var r = randomNum(min,max);
  var g = randomNum(min,max);
  var b = randomNum(min,max);
  return "rgb("+r+","+g+","+b+")";
 }
  
 
 /**繪制驗(yàn)證碼圖片**/
 function drawPic(){
  var canvas=document.getElementById("canvas");
  var width=canvas.width;
  var height=canvas.height;
  var ctx = canvas.getContext('2d');
  ctx.textBaseline = 'bottom';
  /**繪制背景色**/
  ctx.fillStyle = randomColor(180,240); //顏色若太深可能導(dǎo)致看不清
  ctx.fillRect(0,0,width,height);
  /**繪制文字**/
 /*  for(var i=0; i<4; i++){ */
   var txt = $("#yzms").attr("value");
   ctx.fillStyle = randomColor(50,160); //隨機(jī)生成字體顏色
   ctx.font = randomNum(15,20)+'px SimHei'; //隨機(jī)生成字體大小
   var x = 20;
   var y = randomNum(20,30);
   var deg = randomNum(-45, 45);
   //修改坐標(biāo)原點(diǎn)和旋轉(zhuǎn)角度
   ctx.translate(x,y);
   ctx.rotate(deg*Math.PI/180);
   ctx.fillText(txt, 0,0);
   //恢復(fù)坐標(biāo)原點(diǎn)和旋轉(zhuǎn)角度
   ctx.rotate(-deg*Math.PI/180);
   ctx.translate(-x,-y);
 /*  } */
  /* /**繪制干擾線**/
   for(var i=0; i<8; i++){
   ctx.strokeStyle = randomColor(40,180);
   ctx.beginPath();
   ctx.moveTo( randomNum(0,width), randomNum(0,height) );
   ctx.lineTo( randomNum(0,width), randomNum(0,height) );
   ctx.stroke();
  } 
  /**繪制干擾點(diǎn)**/
  /* for(var i=0; i<100; i++){
   ctx.fillStyle = randomColor(0,255);
   ctx.beginPath();
   ctx.arc(randomNum(0,width),randomNum(0,height), 1, 0, 2*Math.PI);
   ctx.fill();
  } */
 }

效果展示:

Java后端產(chǎn)生驗(yàn)證碼后臺(tái)驗(yàn)證功能的實(shí)現(xiàn)代碼

總結(jié)

以上所述是小編給大家介紹的Java后端產(chǎn)生驗(yàn)證碼后臺(tái)驗(yàn)證功能的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI