在注册页面上我们通常需要要做一个图片验证码来防止恶意注册。 实现如下: 开发环境:struts2+tomcat 1.HTML页面: -------------------------------------------------------------------- 你需要有一个验证码图片和一个输入框 验证码图片: name="vcodeImg" id="vcodeImg" align="absmiddle" style="cursor: pointer;" title="看不清楚?换一张" onclick="src='validateCode.action?s='+Math.random()" onerror="this.onerror=null;this.src='validateCode.action? s='+Math.random();" /> 图片的src是一个链接:validateCode.action 对应struts.xml中的action onclick事件是当图片上的验证码看不清楚时可以点击更改验证码;方法将更改img 的src的内容,s='+Math.random() 用来生 成随机字符串,浏览器将识别为一个新的链接地址。 onerror的功能与onclick的功能差不多。 输入框: type="text" maxlength="35" size="35"/> 2.struts.xml文件中的配置 ------------------------------------------------------------------- 生成的验证码图片以及字符串的内容都可以在struts.xml中配置 "-//Apache Software Foundation//DTD Struts Configuration 2.0// EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> class="action.accounts.ValidateImageAction"> 150 35 8 $0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ param> inputStream image/jpeg 3. action --> ValidateImageAction.java ------------------------------------------------------------------------ 我修改了get方法,这样做是为了防止struts.xml中如果没有配置,相当于默认值。 package action.accounts; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import com.opensymphony.xwork2.ActionContext; import function.RandomImage; /** *
* 产生图片验证码 * * Login Page
* @author Michael Zheng 2008-11-18
*/
public class ValidateImageAction {
private InputStream inputStream;
private String randomString; //图片上的字符串
private int length; //图片上字符的个数
private int width; //图片的宽度
private int height; //图片的高度
public String getRandomString() {
if(randomString == null){
randomString =
"$0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
return randomString;
}
public void setRandomString(String randomString) {
this.randomString = randomString;
}
public int getLength() {
if(length == 0){
length = 6;
}
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
if(width == 0){
width = 80;
}
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
if(height == 0){
height = 35;
}
return height;
}
public void setHeight(int height) {
this.height = height;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String execute(){
RandomImage validateImage = new RandomImage(getRandomString(),
getLength(), getWidth(), getHeight());
ByteArrayOutputStream bos =new ByteArrayOutputStream();
try {
ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
ImageIO.write(validateImage.getValidateImage(), "JPEG", ios);
inputStream = new ByteArrayInputStream(bos.toByteArray());
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
Map session = ActionContext.getContext().getSession(); //获得
session
session.put("validateString", validateImage.getValidateString
().toLowerCase());
//将验证码转小写放入session
return "success";
}
}
4. function.RandomImage生成图片工厂类
------------------------------------------------------------------
package function;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
public class RandomImage {
private String validateString; //生成的验证字符串
private BufferedImage validateImage; //生成的验证图片
private String randomString; //图片上的字符串
private int length; //图片上字符的个数
private int width; //图片的宽度
private int height; //图片的高度
public RandomImage(String randomString, int length, int width, int
height){
this.randomString = randomString;
this.length = length;
this.width = width;
this.height = height;
}
//获取生成的验证字符串
public String getValidateString() {
if(validateString==null){
getValidateImage();
}
return validateString;
}
//获取生成的验证图片
public BufferedImage getValidateImage(){
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);// 在内存中创建图象
Graphics2D raphics = (Graphics2D) image.getGraphics();// 获取图形上下
文
raphics.setColor(Color.WHITE);// 设定为白色背景色
raphics.fillRect(0, 0, width, height);
raphics.setFont(new Font("Times New Roman",Font.ITALIC,28));//设
定字体 style:HANGING_BASELINE
raphics.setColor(getRandColor(160,200));//给定范围获得随机颜色
Random random = new Random(); //生成随机类
//随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
for (int i=0;i<255;i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
//int xl = random.nextInt(12);
//int yl = random.nextInt(12);
raphics.drawLine(x,y,x,y);
}
// 取随机产生的认证码(length位数字)
String rand = "";
StringBuffer vString = new StringBuffer();
for (int i=0;i
rand=String.valueOf(randomString.charAt(random.nextInt (randomString.length()))); vString.append(rand); raphics.setColor(Color.BLACK);//设置为黑色字体 //raphics.rotate(0.01,20,20); raphics.drawString(rand, 15*i+10, 25); } validateString = vString.toString(); // 将认证码存入 validateString raphics.dispose(); //图象生效 return image; } private Color getRandColor(int fc,int bc){ //给定范围获得随机颜色 Random random = new Random(); if(fc>255) fc=255; if(bc>255) bc=255; int r=fc+random.nextInt(bc-fc); int g=fc+random.nextInt(bc-fc); int b=fc+random.nextInt(bc-fc); return new Color(r,g,b); } } 注:以上类及包名如有不对请自行修改,其核心代码都已在上面,细节部分可自行加上。 没有写更多细节的注释,太烦了,如果你看不懂,那就应该再好好去看看Core Java了。