java 文件
package com.liuc.web.common;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import com.opensymphony.xwork2.ActionContext;
/**
* 图片验证码
*/
public class CheckCodeAction {
private int width = 70; //图片宽度
private int height = 18; //图片高度
private int count = 4; //码数
//验证码源
private char[] codes = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private InputStream inputStream;
public String execute() throws Exception {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height); //画背景
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1); //画边框
//设置画笔的颜色和字体
g.setFont(new Font("Fixedsys",Font.PLAIN, 14));
StringBuilder sb = new StringBuilder(); //用来保存产生的码值
Random random = new Random();
for(int i = 0; i < count; i++){
char c = codes[random.nextInt(codes.length)];
sb.append(c);
//产生随机颜色
g.setColor(new Color(random.nextInt(200), random.nextInt(200), random.nextInt(200)));
g.drawString(String.valueOf(c), i * (width/count)+2, height-3);
}
//随机数的干扰线
for(int i = 0; i < 20; i++){
g.setColor(new Color(160 + random.nextInt(96),
160 + random.nextInt(96), 160 + random.nextInt(96)));
int x = 2+random.nextInt(width);
int y = 2+random.nextInt(height);
int x1 = random.nextInt(6);
int y1 = random.nextInt(6);
g.drawLine(x, y, x+x1 > width - 3 ? width-3 : x+x1, y+y1 > height-3 ? height - 3 : y+y1);
}
//把产生的验证码值保存到当前会话中。
//ServletActionContext.getRequest().getSession().setAttribute("checkCode", sb.toString());
ActionContext.getContext().getSession().put("checkCode", sb.toString());
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
ImageIO.write(bi, "JPEG", imageOut); //把内存图片写到输出流
imageOut.close();
this.inputStream = new ByteArrayInputStream(output.toByteArray());
return "success";
}
public InputStream getInputStream(){
return inputStream;
}
}
struts2 配置文件
image/jpeg
inputStream
页面文件
loginAction 文件
String realCC = (String)ActionContext.getContext().getSession().get("checkCode");