六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 48|回复: 0

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

[复制链接]

升级  52%

34

主题

34

主题

34

主题

秀才

Rank: 2

积分
128
 楼主| 发表于 2013-1-15 02:25:10 | 显示全部楼层 |阅读模式
一个不会报错的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();

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

<div style="border-right: #cccccc 1px solid; padding-right: 5px; border-top: #cccccc 1px solid; padding-left: 4px; font-size: 13px; padding-bottom: 4px; border-left: #cccccc 1px solid; width: 98%; padding-top: 4px; border-bottom: #cccccc 1px solid; background-color: #eeeeee;"> 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
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表