项目需求写了一个登录带验证码的小需求。页面取验证码的值是上次的随机出的,很疑惑。
(1)验证码的JSP
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'image.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->  </head>
  
  <body>
    
    <%!
    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);
            }
    %>
    <%
    //设置页面不缓存
    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(new Color());
    //g.drawRect(0,0,width-1,height-1);
    // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
    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);
    }    // 取随机产生的认证码(4位数字)
    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);
    }    // 将认证码存入SESSION
    session.setAttribute("rand",sRand);
    // 图象生效
    g.dispose();    // 输出图象到页面
    ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
    %>  </body>
</html>
(2) 登录页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>登录</title>
<script type="text/javascript">
function checkLogin(){
    var name = document.form.loginName.value;
    var psd = document.form.passWord.value;
    var rand = ${sessionScope.rand} ;
    var rand1 = document.form.rand.value;
    alert(rand1);
    alert(rand);

 
    if(name == ""){
     alert("请输入用户名");
     document.form.loginName.focus();
     return false;
    }
if(psd == ""){
alert("请输入密码");
     document.form.passWord.focus();
     return false;
}
    if(psd.length<6){
     alert("请输入6位有效密码");
     document.form.passWord.focus();
     return false;
    }
   if(rand!=rand1){
       alert("请输入正确的验证码");
       document.form.rand.focus();
       return false;
       
    }
  
return true;
}
</script>
</head>
<style>
* {
margin: 0 auto;
padding: 0;
}div {
position: relative;
}body {
text-align: center;
}#wrap {
width: 1004px;
height: 600px;
}table {
color: #042943;
font-size: 12px;
line-height: 36px;
position: absolute;
top: 280px;
left: 400px;
}input {
border-left: #1D1B1C solid 2px;
border-top: #1D1B1C solid 2px;
height: 18px;
}
</style>
<body>
<div id="wrap">
<form action="${pageContext.request.contextPath}/login.action" method="post" name="form" onSubmit="return checkLogin()" >
<img src="system/images/bg.gif" border="0" /> <table border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50px">
用户名
</td>
<td>
<input name="loginName" type="text" />
</td>
</tr>
<tr>
<td>
密码
</td>
<td>
<input name="passWord" type="password" />
</td>
</tr>
<tr>
<td>
验证码
</td>
<td>
<input name="rand" type="text" class="yzm" /> <a href="#" onfocus="this.blur();"><img src="./image.jsp"
border="0" align="absmiddle" /> </a>
</td>
</tr>
<tr>
 <td colspan="2" algin="center"><br />


 <br /></td>
</tr>
</table>
<input name="submit" type="submit"
style="background: url(system/images/icol.gif) no-repeat; width: 47px; height: 47px; position: absolute; top: 290px; left: 640px; border: 0; cursor: pointer;" /> </form>
</div>
</body>
</html>
请朋友们分析下。 为何本次的alert 验证码的值是上次的呢?

解决方案 »

  1.   

    这个应该执行顺序的问题吧,应该是先生成随机,再保存进session,看看你的逻辑代是不是有问题,仔细检测下
      

  2.   

    很简单的道理
      首先  看你的登录页面的代码:var rand = ${sessionScope.rand} ;
    var rand1 = document.form.rand.value;
    alert(rand1);
    alert(rand);你的这段代码在页面的最上面,在往下找你的验证码生成的页面连接,在这段代码的下面,所以执行顺序是,先执行js代码和读取session的值,读取的当然是上次保存的session值了,如果你把js代码放到登录页面的底部再执行那就没问题了
      

  3.   

    。我上面说的应该没问题,你这种实现形式你错误的!
    登录页面先执行,它的session对象已经被初始化,而你的验证码生成页面的session还没有初始化,所以你的验证码永远得不到;
    你这样做就相当于想穿越时空到达未来。3楼说的的确没问题,是逻辑顺序有误!
      

  4.   

    类似这样的验证最后放到后台验证,也就是在服务器端做验证,不要在前台js里做验证。
    最好的解决办法就是再写一个servlet或者js页面,来做验证;
    还有你一定要搞清楚验证码的含义是什么;
    验证码的校验最好 最好 是在后台!!!如果在js里校验,那验证码似乎也就是去了它的意义
      

  5.   

    就是说,当用户在页面都输入了验证码,也点了提交了
     然后再在第三个Action里做校验!
      

  6.   

    执行顺序问题。
    先打开login.jsp,执行sessionScope.rand
    然后再打开image.jsp还有验证码从来都不是在客户端匹配的。提交到服务器端,在session中匹配!!
      

  7.   

    你现在的执行顺序是
    先打开login.jsp
    执行sessionScope.rand(生成javascript所能读取的rand)
    然后再打开image.jsp(更换session)执行顺序是对的。但是匹配方法只能在服务器端
      

  8.   

    用这个!!http://topic.csdn.net/u/20100706/21/dd11f7fc-6c35-4c44-9ff8-c0e025163c75.html 
      

  9.   


    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ page import="java.awt.image.*" %>
    <%@ page import="java.awt.*" %>
    <%@page import="java.awt.Graphics"%>
    <%@page import="javax.imageio.ImageIO"%>
    <%!
        //获得随机颜色对象
        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);
        }
     %>
    <%
        
         //设置响应的内容类型为图片
         response.setContentType("image/jpg");
        //清除页面上的缓存(每次点击浏览器的后退按钮都会重新生成验证码)
        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(new Color());
        //g.drawRect(0,0,width-1,height-1);
        // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
        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);
        }
        // 取随机产生的认证码(4位数字)
        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);
        }
        // 将认证码存入session
        session.setAttribute("rand",sRand);
        // 图象生效
        g.dispose();
        ServletOutputStream responseOutputStream =response.getOutputStream();
        // 输出图象到页面
        ImageIO.write(image, "JPG", responseOutputStream);
        //以下关闭输入流!
        responseOutputStream.flush();
        responseOutputStream.close();
       out.clear();//要把内置对象清空
       out = pageContext.pushBody();   //然后在保存到pageContext中传给内置对象
    %><img src="./image.jsp" style="cursor:hand;" onClick="this.src='./image.jsp'">