Struts2 Action中输出验证码报错解决办法
错误:
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();这个方法,就一直报错。加上就好了。