项目中要用验证码,在网上找到的struts2验证码是把返回结果配置成文件流,通过类似于下载来实现的,不太理想。于是把孙修鹏网友的代码稍作修改,自己实现了一个。struts2也是遵循请求响应的模式,如果把响应直接写到response里面,则返回结果不做配置就可以了。
代码如下
action
其中makeImage方法的返回结果是void
package com.image;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Image extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
public void makeImage() throws Exception{
Map<String, Object> session = ActionContext.getContext().getSession();
HttpServletResponse res = ServletActionContext.getResponse();
BufferedImage img = new BufferedImage(68, 22,
BufferedImage.TYPE_INT_RGB);
// 得到该图片的绘图对象
Graphics g = img.getGraphics();
Random r = new Random();
Color c = new Color(200, 150, 255);
g.setColor(c);
// 填充整个图片的颜色
g.fillRect(0, 0, 68, 22);
// 向图片中输出数字和字母
StringBuffer sb = new StringBuffer();
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
int index, len = ch.length;
for (int i = 0; i < 4; i++) {
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小
g.drawString("" + ch[index], (i * 15) + 3, 18);// 写什么数字,在图片的什么位置画
sb.append(ch[index]);
}
session.put("piccode", sb.toString());
ImageIO.write(img, "JPG", res.getOutputStream());
}
}
配置文件,这里是关键
<action name="image" class="com.image.Image" method="makeImage"></action>
大家看到了,返回的结果是空的,返回的内容已经写到response中了,这里就没必要再配置了。
其实框架只是让我们用起来更方便更有效率,但是原理的东西永远不过过时的。