Servlet里向Session里放变量,在jsp中取数据的问题

servlet中

doGet和doPost都执行doPost

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB); 

Graphics g = bi.getGraphics();

Color c = new Color(200,150,255);

g.setColor(c);

g.fillRect(0, 0, 68,22);

char[] code = "ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789".toCharArray();

Random r= new Random();

int len = code.length,index;

StringBuffer sb = new StringBuffer();

for(int i =0; i < 4; i ++){

index = r.nextInt(len);

g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));

g.drawString(code[index] + "", (i*15)+3,18 );

sb.append(code[index]);

}

request.getSession().setAttribute("picode", sb.toString());

ImageIO.write(bi,"jpg",response.getOutputStream());

}


jsp中

<form action="ls" method = "get">

   <input type="text" id = "text1" name ="code" />

   <img  id="img1" alt="验证码" src="<%=request.getContextPath() %>/is" />

   <a href="javascript:reCode()">看不清楚,换一张</a>

   <br/>

   验证码:<%=(String)session.getAttribute("picode") %>

   <input type="submit" id="btn1" value="验证"/>

    </form>

这里第一次是在页面显示"验证码:null"之后每一次显示的验证码都是上一次的验证码

比如这次显示的图片是:809Y 验证码:null

下一次就是图片是:8278 验证码:809Y

这是什么原因。不太明白。


应龙
浏览 2954回答 3
3回答

qq_独行_者_1

你这这个页面执行实际不对,应该在打开这个页面之前先执行验证码。然后页面显示的时候才会显示session里面的

yemaa

=(String)session.getAttribute("picode")这个会先执行,然后在执行=request.getContextPath() %>/is;可以测试的加个for循环你就可以看到是哪个先执行for(int i=0;i<1000000;i++){            System.out.println(i);        }        request.getSession().setAttribute("picode", sb.toString());        ImageIO.write(bi,"jpg",response.getOutputStream());

HansonQ

你这这个页面执行实际不对,应该在打开这个页面之前先执行验证码。然后页面显示的时候才会显示session里面的
打开App,查看更多内容
随时随地看视频慕课网APP