posts - 89, comments - 241, trackbacks - 0, articles - 1
   :: 首页 ::  :: 联系 :: 聚合  :: 管理

一个不会报错的jsp彩色验证码程序

Posted on 2009-09-22 14:52 saobaolu 阅读(497) 评论(3)  编辑  收藏 所属分类: javaweb
一个不会报错的jsp彩色验证码程序
一般的,会报servlet错误:
getOutputStream() has already been called for this response
但是这个程序不会报错,原因是把里面的空格都删除
-------------------------------------------------------------
在tomcat中jsp编译成servlet之后在函数_jspService(HttpServletRequest request, HttpServletResponse response)的最后
有一段这样的代码
finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
这里是在释放在jsp中使用的对象,会调用response.getWriter(),因为这个方法是和
response.getOutputStream()相冲突的!所以会出现以上这个异常。

然后当然是要提出解决的办法,其实挺简单的(并不是和某些朋友说的那样--
将jsp内的所有空格和回车符号所有都删除掉),

在使用完输出流以后调用以下两行代码即可:
out.clear();
out = pageContext.pushBody();

--------------------------------------------------------
分割线内为引用~

 1<%@ page  import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
 2<%@ page import="java.io.OutputStream" %>
 3<%!
 4Color getRandColor(int fc,int bc){
 5Random random = new Random();
 6if(fc>255) fc=255;
 7if(bc>255) bc=255;
 8int r=fc+random.nextInt(bc-fc);
 9int g=fc+random.nextInt(bc-fc);
10int b=fc+random.nextInt(bc-fc);
11return new Color(r,g,b);
12}

13%>
14<%
15try{
16response.setHeader("Pragma","No-cache");
17response.setHeader("Cache-Control","no-cache");
18response.setDateHeader("Expires"0);
19int width=60, height=20;
20BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
21OutputStream os=response.getOutputStream();
22Graphics g = image.getGraphics();
23Random random = new Random();
24g.setColor(getRandColor(200,250));
25g.fillRect(00, width, height);
26
27g.setFont(new Font("Times New Roman",Font.PLAIN,18));
28g.setColor(getRandColor(160,200));
29for (int i=0;i<155;i++)
30{
31int x = random.nextInt(width);
32int y = random.nextInt(height);
33int xl = random.nextInt(12);
34int yl = random.nextInt(12);
35g.drawLine(x,y,x+xl,y+yl);
36}

37String sRand="";
38for (int i=0;i<4;i++){
39String rand=String.valueOf(random.nextInt(10));
40sRand+=rand;
41g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
42g.drawString(rand,13*i+6,16);
43}

44session.setAttribute("rand",sRand);
45g.dispose();
46
47ImageIO.write(image, "JPEG",os);
48os.flush();
49os.close();
50os=null;
51response.flushBuffer();
52out.clear();
53out = pageContext.pushBody();
54}

55catch(IllegalStateException e)
56{
57System.out.println(e.getMessage());
58e.printStackTrace();
59}
%>
60


没有所谓的命运,只有不同的选择!