---
title: "jsp页面图片验证码获取的session值始终显示前一个解决方案"
author: "liuxl1125"
date: "2013-07-17T17:13:00Z"
tags: []
categories: ["Web前端"]
slug: "jsp-session"
draft: false
lastmod: "2013-07-17T18:21:35Z"
id: 1908528
url: "https://liuxl1125.iteye.com/blog/1908528"
---

处理的思想是通过在当前的页面嵌入iframe，在iframe中获取session及相关的脚本处理，当验证码重置的时候iframe同步刷新。这样就保证了获取的session始终与展示的验证码图片一致。

代码如下：

a.jsp

  &lt;body&gt;  
   &lt;div style="left:250px;top:80px;width:300px;height:45px;position:absolute;color:red;" id="warning"&gt;&lt;/div&gt;  
   &lt;form action="&lt;%=path %&gt;/GIFT\_CARD/giftCardAction!activateGiftCard" method="post" onsubmit="return window.frames\['childframe'].giftCard.sub();"&gt;  
    卡号密码：&lt;input type="text" name="cardPsw" id="cardPsw" onkeypress="window.frames\['childframe'].giftCard.changeValue()"/&gt;&lt;br/&gt;  
    验证码：&lt;input type="text" name="verifyCode" id="verifyCode"/&gt;&lt;img id="imgverify" border="0" src="image.jsp?rad=&lt;%=new java.util.Date() %&gt;" onclick="window.frames\['childframe'].giftCard.changeVerifyCode();"/&gt;  
    &lt;input type="submit" value="提交"/&gt;  
   &lt;/form&gt;  
   &lt;iframe id="childframe" src="" width="0" height="0"&gt;&lt;/iframe&gt;  
  &lt;/body&gt;  
  &lt;script type="text/javascript"&gt;  
   function fn(){  
    document.getElementById("childframe").src="b.jsp";  
   }  
   setTimeout("fn()",1000);  
  &lt;/script&gt;  
&lt;/html&gt;

 

b.jsp（iframe页面）

&lt;body&gt;  
   &lt;script type="text/javascript"&gt;  
     var giftCard = {  
      changeValue:function (){  
       var pswvalue = parent.document.getElementById("cardPsw").value;  
       if(pswvalue.length==2 || pswvalue.length==7 || pswvalue.length==12 || pswvalue.length==17){  
        parent.document.getElementById("cardPsw").value = pswvalue+" ";  
       }  
      },  
      sub:function (){  
       var pswvalue = parent.document.getElementById("cardPsw").value;  
       var verifac = parent.document.getElementById("verifyCode").value;  
       pswvalue = pswvalue.replace(/\[ ]/g,"");  
       if(pswvalue.length!=18){  
        parent.document.getElementById("warning").innerHTML="请输入正确的礼品卡密码！";  
        return false;  
       }else if(verifac!="&lt;%=request.getSession().getAttribute("imagecode")%&gt;"){  
        parent.document.getElementById("warning").innerHTML="请输入正确的验证码！";  
        return false;  
       }  
      },  
      changeVerifyCode:function (){  
       parent.document.getElementById("imgverify").src="image.jsp?random="+Math.random();  
       parent.document.getElementById("childframe").src="b.jsp?random="+Math.random();  
      }   
     }  
    &lt;/script&gt;  
  &lt;/body&gt;

 

image.jsp

&lt;[%@page](mailto:%@page) import="java.io.InputStream"%&gt;  
&lt;%@ page contentType="image/JPEG"  
 import="java.awt.\*,java.awt.image.\*,java.util.\*,javax.imageio.\*"  
 pageEncoding="GBK"%&gt;&lt;%!Color getRandColor(int fc, int bc) {  
  Random random = new Random();  
  if (fc &gt; 255)  
   fc = 255;  
  if (bc &gt; 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);  
 }%&gt;  
&lt;%

 response.setHeader("Pragma", "No-cache");  
 response.setHeader("Cache-Control", "no-cache");  
 response.setDateHeader("Expires", 0);  
 response.flushBuffer();  
 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 &lt; 100; 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 &lt; 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.setAttribute("imagecode", sRand);  
 g.dispose();  
 ImageIO.write(image, "JPEG", response.getOutputStream());  
 out.clear();

   
%&gt;