2013年9月4日星期三

Enter the verification code correctly determine the problem

I made a login screen login.jsp, with session access Servlet generated verification code , print out a look, but it is the last generated verification code
When you first open login.jsp , session values ​​are removed null; refresh the page, then remove the last generated value is the verification code !
session last time out values ​​are the values ​​! validate the effect of this can not be achieved , willing to please help ! Thank you ! attached code !
This is the Servlet service method for generating a random verification code ! verification code will be placed in the Session

package com.fk.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* 获得图片验证码 
* @author Administrator
*
*/
public class GetImageCode extends HttpServlet {

private static final long serialVersionUID = 1L;

   private static int WIDTH = 60; 
    private static int HEIGHT = 20; 
 
    public char[] generateCheckCode() { 
        // 定义验证码的字符表 
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
        char[] rands = new char[4]; 
        for (int i = 0; i < 4; i++) { 
            int rand = (int) (Math.random() * 36); 
            rands[i] = chars.charAt(rand); 
        } 
        return rands; 
    } 
 
    public void drawRands(Graphics g, char[] rands) { 
        g.setColor(Color.BLACK); 
        g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18)); 
        // 在不同的高度上输出验证码的每个字符 
        g.drawString("" + rands[0], 1, 17); 
        g.drawString("" + rands[1], 16, 15); 
        g.drawString("" + rands[2], 31, 18); 
        g.drawString("" + rands[3], 46, 16); 
    } 
 
    public void drawBackground(Graphics g) { 
        // 画背景 
        g.setColor(new Color(0xDCDCDC)); 
        g.fillRect(0, 0, WIDTH, HEIGHT); 
        // 随机产生120个干扰点 
        for (int i = 0; i < 120; i++) { 
            int x = (int) (Math.random() * WIDTH); 
            int y = (int) (Math.random() * HEIGHT); 
            int red = (int) (Math.random() * 255); 
            int green = (int) (Math.random() * 255); 
            int blue = (int) (Math.random() * 255); 
            g.setColor(new Color(red, green, blue)); 
            g.drawOval(x, y, 1, 0); 
        } 
    } 
 
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        HttpSession session = request.getSession(); 
        response.setContentType("image/jpeg");  
        ServletOutputStream sos = response.getOutputStream(); 
 
        // 设置浏览器不缓存此图片 
        response.setHeader("Pragma", "No-cache"); 
        response.setHeader("Cache-Control", "no-cache"); 
        response.setDateHeader("Expires", 0); 
 
        // 创建内存图像并获得其图形上下文 
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, 
                BufferedImage.TYPE_INT_RGB); 
        Graphics g = image.getGraphics(); 
 
        // 产生随机的验证码 
        char[] rands = generateCheckCode(); 
 
        // 产生图像 
        drawBackground(g); 
        drawRands(g, rands); 
 
        // 结束图像的绘制过程,完成图像 
        g.dispose(); 
 
        // 将图像输出到客户端 
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        ImageIO.write(image, "JPEG", bos); 
        byte[] buf = bos.toByteArray(); 
        response.setContentLength(buf.length); 
        sos.write(buf); 
        bos.close(); 
        sos.close(); 
 
        // 将当前验证码存入到session中 
        session.setAttribute("checkCode", new String(rands)); 
        System.out.println(session.getAttribute("checkCode")); 
    } 
 
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        doGet(request, response); 
    }
   
}



  <servlet>
           <servlet-name>GetImageCode</servlet-name>
           <servlet-class>com.fk.util.GetImageCode</servlet-class>
    </servlet>
    <servlet-mapping>
           <servlet-name>GetImageCode</servlet-name>
           <url-pattern>/GetImageCode</url-pattern>
    </servlet-mapping>



<div class="control-group"> 
<label class="control-label">*验证码:</label>  
<div class="controls" style="width: 350px;">
<input type="text" name="verifyCode" id="verifyCode" maxlength="20" />  
<div id="code_div">
</div>  
<div id="verifyCode_error"></div>       
</div>
</div>


var bol5=false;
  /**
  * emailReg js验证  
  * V1.0
  */
  $(function (){
var i=0;
      //验证码 
      $("#verifyCode").blur(function(){      
    var verifyCode=$("#verifyCode").val();   
    if(i==0){
    $("#code_div").html("<img alt=\"验证码\" id=\"safecode\" src=\"${ctx}/GetImageCode\">"+"<a href=\"javascript:changeCode();\" id=\"changCode\">看不清楚</a>");
    i++;
    }
   
      if(verifyCode.replace(/(^\s*)|(\s*$)/g,"")==""){ 
      bol5=false;
      $("#verifyCode_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' width=\"15px\" height=\"15px\"/>请输入验证码");       
      }else{
  $.ajax({    
      type: "post",     
      url: "${ctx}/user.do?method=checkImgCode&imgCode="+verifyCode,      
      dataType: "json",   /*这句可用可不用,没有影响*/ 
      contentType: "application/json; charset=utf-8",    
      success: function (bol) {    
      if(!bol){ 
      bol5=true;
      $("#verifyCode_error").html("<img src='${ctx}/images/success_img.gif' width='16px' height='16px'/>");
      }else{
      bol5=false;
      $("#verifyCode_error").attr("class","error_div").html("<img src='${ctx}/images/error_img2.gif' width='15px' height='15px'/>"+"验证码不正确");  
      }
     
      },      
      error: function (XMLHttpRequest, textStatus, errorThrown) {    
      alert(errorThrown);    
      }    
    });
     
     
      }
  });


   });
 

------ Solution ------------------------------------- -------
you direct access to jsp pages do ?
------ Solution ---------------------------------------- ----
every request , plus timestamp
------ Solution ------------------------- -------------------
you should provide a servlet forwarded to the jsp page, a servlet plane is responsible for forwarding the verification code pages in memory to the session.
And you direct access to jsp, session was not yet saved the verification code , so the first time is null
------ Solution ---------------- ----------------------------
verification code is generated servlet it, it was displayed on the page ? In the page load time to put the servlet code generated characters can be saved to the session where the ah
------ Solution ------------------- -------------------------
your page should have a * Verification Code :





;


The

changed
then do the behind the js validation
regenerate a Servlet get page the $ {verifyCode} value getsession.getAttribute ("checkCode") value of the relatively long time it ! Jump directly ok on the same
------ Solution --------------------------------- -----------
you have made ​​a asynchronous validation , ah, so feel you asked the question and the answer you have to solve , not the same?
------ Solution ---------------------------------------- ----
avoid caching , url pass a random number of random
------ For reference only --------------------- ------------------
Yes, verification code is generally foreground or background verification ? If verification is the foreground , the background using ajax servlet determine whether the right to access it ?
------ For reference only -------------------------------------- -


js code above the first row so some jquery code
var i=0;
      //验证码 
      $("#verifyCode").blur(function(){      
            var verifyCode=$("#verifyCode").val();   
            if(i==0){
                 $("#code_div").html("<img alt=\"验证码\" id=\"safecode\" src=\"${ctx}/GetImageCode\">"+"<a href=\"javascript:changeCode();\" id=\"changCode\">看不清楚</a>");
                 i++;
            }......

------ For reference only ----------------------------------- ----


mouse enters the text box before generating code , the first afternoon timestamp
Click the picture to replace the verification code when it re- generate new code , plus a timestamp , the code is as follows:
 function changeCode(){      
  var timenow = new Date().getTime();  
  var safecode = document.getElementById("safecode");    
  safecode.src="<%=request.getContextPath()%>/GetImageCode?d="+timenow;   
  }

------ For reference only ----------------------------------- ----

not be so complicated , I've been through ajax, the page, enter verification code to verify incoming background , and then determine the correct or not. Jump right off the page and remove the session of checkCode, an error is an error and replace the verification code .
------ For reference only -------------------------------------- -

my problem is that will be saved in the session of checkCode on the web side, hidden fields , and then want to determine the web -side validation code is entered correctly , this has led to the first time the page is entered Get the checkCode session is null, since I first entered the page, and then in the page code input box blur event bound to get authentication code and save it in the session .
I solved way is the way to obtain verification code unchanged when the form is submitted via Ajax will enter the verification code passed the background check verification code method, check verification code method to get user input while session in the verification code and verification code , compare the two , if they are equal then back true, otherwise it is false, then get the true web -side , then on into the registration process, otherwise prompt verification code input errors and automatically replace the verification code .
I do not know whether this treatment reasonable ?
------ For reference only -------------------------------------- -

have added a timestamp of
------ For reference only ----------------------- ----------------
page loads, using ajax to the server and read the verification code into the session , ajax returns displayed on the page ,
this page and the session has a verification code , you want to verify what way can .
------ For reference only -------------------------------------- -
There are so complicated it

------ For reference only ---------------------------------------
feel very obvious first request when your code did not generate it, so your hidden field is empty, you should first ensure the verification code into Mr. bar
------ For reference only ---------- -----------------------------

does not build , I read the session , and is verification code input focus leaves the box when it generates
------ For reference only ---------------------------- -----------
how that trouble you ! ! ! ! !
make direct use of a random number js simple point ' ? ? ?
is not for you in the pursuit of a higher realm authentication oh

------ For reference only ---------------------------------------
Can you change the source code complete Share what ah ? ? ? So just say do not understand ah ...... AJax just learning to use Front verify it ? ? ?
------ For reference only -------------------------------------- -
also encountered this problem studied
------ For reference only ------------------- --------------------
just removed the page and servlet-generated servlet does not correspond with the use of a judge like

没有评论:

发表评论