您的位置:首页 > 编程语言 > Java开发

严重: Servlet.service() for servlet jsp threw exception java.lang.IllegalStateException: getOutputStream() has already been called

2013-09-02 19:24 911 查看

错误:

严重: Servlet.service() for servlet jsp threw exception java.lang.IllegalStateException: getOutputStream() has already been called

输出验证码的类:

package com.jxc.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
* 验证码输出类
* @author Pan
*
*/
public class GraphisVerfCode {

private HttpServletResponse response;
private Point point;
private int linesize;
private String code="";
public GraphisVerfCode(HttpServletResponse response,Point p,int linesize){

this.response=response;
this.point=p;
this.linesize=linesize;
code=RandomCode.getRandomString(4);
}
public String getCode() {
return this.code;
}
public void Draw() throws IOException{
//输出类型
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
response.setHeader("Cache-Control", "no-cache");
//创建对象
BufferedImage bImage=new BufferedImage(point.x, point.y,BufferedImage.TYPE_INT_RGB);
Graphics2D g=bImage.createGraphics();
//前景色

//填充矩形
g.fillRect(0, 0, point.x, point.y);

drowString(g);
//干扰线
drowLine(g,this.linesize);
//输出图片
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bImage, "jpeg", out);
out.flush();
out.close();
}
//干扰线条
private void drowLine(Graphics g,int linesize){
Random random=new Random(System.currentTimeMillis());

for (int i = 0; i < linesize; i++) {
int x = random.nextInt(point.x);
int y = random.nextInt(point.y);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.drawLine(x, y, x+xl, y+yl);
}
}

private void drowString(Graphics g){
g.setFont(new Font("微软雅黑",Font.BOLD,22));
Random random=new Random(System.currentTimeMillis());
//循环绘制每个字的颜色
for(int i=0;i<code.length();i++){
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.drawString(code.charAt(i)+"", 20*i, 25);
}
}
}


最开始使用的时候,没有调用 out.flush();这个方法,就一直报错。加上就好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐