在struts2下实现了图片验证码的实例,基本思想如下:
1.实现产生图片验证码的action
2.配置action,将上述action返回的逻辑结果设置为文件流类型
3.写一个测试的html页面,使其请求上面的action,得到返回的图片结果。
4.运行结果,点击图片可以改变验证码。
1.实现产生图片验证码的action
public class VerifyCode extends ActionSupport {
private ByteArrayInputStream inputStream;
public String execute() throws Exception{
RandomNumUtil rdnu=RandomNumUtil.Instance();
this.setInputStream(rdnu.getImage());//取得带有随机字符串的图片
ActionContext.getContext().getSession().put("random", rdnu.getString());//取得随机字符串放入HttpSession
return SUCCESS;
}
public void setInputStream(ByteArrayInputStream inputStream) {
this.inputStream = inputStream;
}
public ByteArrayInputStream getInputStream() {
return inputStream;
}
}
public class RandomNumUtil {
private ByteArrayInputStream image;//图像
private String str;//验证码
private RandomNumUtil(){
init();//初始化属性
}
/*
* 取得RandomNumUtil实例