image.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript" src="js/jquery-1.4.min.js"></script><script type="text/javascript">$(function(){ $("#valiCode").blur(function(){ $.post( "valid",//請求url {"valiCode":$(this).val()},//請求參數 function(data){//回呼函數 if(data.ok){ $("#msg").html("<font style='color:red'>驗證碼填寫正確</font>"); }else{ $("#msg").html("<font style='color:red'>驗證碼填寫錯誤</font>"); $("#image").attr("src","image?date="+new Date().getTime()); } }, "json"//返回資料data的格式為json ); });});</script></head><body><img id="image" src="image"><br><input type="text" name="valiCode" id="valiCode"><span id="msg"></span></body></html>
struts.xml :
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts> <package name="demo" extends="json-default"> <action name="image" class="action.ImageAction"> <result name="success" type="stream"> <param name="inputName">image</param> </result> </action> <action name="valid" class="action.ValidImageAction"> <result name="success" type="json"></result> </action> </package></struts>
ImageUtil.java :
public class ImageUtil {private static final String[] chars={"0","1","2","3","4","5","6","7","8","9","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"};private static final int WIDTH=200;private static final int HEIGHT=100;private static final int SIZE=5;private static final int LINES=15;private static final int FONT_SIZE=45;public static Map<String,BufferedImage> getImage(){StringBuffer sb=new StringBuffer();BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);Graphics g=image.getGraphics();g.setColor(Color.LIGHT_GRAY);g.fillRect(0,0,WIDTH,HEIGHT);Random random=new Random();for(int i=1;i<=SIZE;i++){g.setColor(getRandomColor());int j=random.nextInt(chars.length);g.setFont(new Font(null,Font.BOLD,FONT_SIZE));g.drawString(chars[j],(i-1)*WIDTH/SIZE,HEIGHT/2);sb.append(chars[j]);}for(int i=0;i<LINES;i++){g.setColor(getRandomColor());g.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(WIDTH),random.nextInt(HEIGHT));}Map<String,BufferedImage> map=new HashMap<String,BufferedImage>();map.put(sb.toString(),image);return map;}private static Color getRandomColor(){Random random=new Random();return new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));}}
ImageAction.java :
public class ImageAction extends ActionSupport {private InputStream image;public InputStream getImage() {return image;}public void setImage(InputStream image) {this.image = image;}public String execute() throws ImageFormatException, IOException{Map<String,BufferedImage> map=ImageUtil.getImage();String str=map.keySet().iterator().next();ActionContext.getContext().getSession().put("str",str);BufferedImage bi=map.get(str);ByteArrayOutputStream baos=new ByteArrayOutputStream();JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(baos);encoder.encode(bi);image=new ByteArrayInputStream(baos.toByteArray());return "success";}}
ValidImageAction.java :
public class ValidImageAction extends ActionSupport {private String valiCode;private boolean ok;@JSON(serialize=false)public String getValiCode() {return valiCode;}public void setValiCode(String valiCode) {this.valiCode = valiCode;}public boolean isOk() {return ok;}public void setOk(boolean ok) {this.ok = ok;}public String execute(){String str=(String)ActionContext.getContext().getSession().get("str");if(str.equals(getValiCode())){ok=true;}else{ok=false;}return "success";}}