严重: Servlet.service() for servlet jsp threw exception java.lang.IllegalStateException: getOutputStre...

错误:

严重: 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();这个方法,就一直报错。加上就好了。


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值