struts2生成中文验证码的Action

struts2 的Action类 ValidateImgAction.java


java 代码
 
package cn.gx80.control.action.basic;  
  
import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.util.Map;  
  
import org.apache.struts2.interceptor.SessionAware;  
  
import cn.gx80.service.util.ValidateImageService;  
import cn.gx80.util.Key;  
  
/** 
 * 生成验证码 
 * @author
 * 
 */  
@SuppressWarnings("unchecked")  
public class ValidateImgAction extends StreamBasicAction implements SessionAware{  
  
    private static final long serialVersionUID = 6894525175454169331L;  
  
    private static final String Default_ValidateCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
      
    private Map session;  
      
    private int width;  
    private int height;  
    private int fontSize;  
    private int codeLength;  
      
    private ValidateImageService validateImageService;  
      
       
    public ValidateImgAction(){  
        this.contentType = "image/jpeg";      
        width = 80;  
        height = 20;  
        fontSize = 16;  
        codeLength = 4;  
    }  
        
    public void setSession(Map session) {  
        this.session = session;  
    }   
      
      
    public void setWidth(int width) {  
        this.width = width;  
    }  
  
    public void setHeight(int height) {  
        this.height = height;  
    }  
  
  
    public void setFontSize(int fontSize) {  
        this.fontSize = fontSize;  
    }  
  
    public void setCodeLength(int codeLength) {  
        this.codeLength = codeLength;  
    }  
  
    public void setValidateImageService(ValidateImageService validateImageService) {  
        this.validateImageService = validateImageService;  
    }  
  
    public String execute() throws Exception {    
        session.put(Key.ValidateCodeByLogin, createInputStream(ValidateImageService.Disturb_Type_Simple));  
        return SUCCESS;  
    }  
      
      
    private String createInputStream(int disturbType) throws IOException{  
        ByteArrayOutputStream bos =new ByteArrayOutputStream();  
        String validateCode = null;  
        validateCode = validateImageService.createValidateCode(disturbType,fontSize, bos, width, height, getText("System.validateCode",Default_ValidateCode), codeLength);  
        inputStream = new ByteArrayInputStream(bos.toByteArray());  
        bos.close();  
        return validateCode;  
    }                           
}  


验证码生成接口 ValidateImageService.java


java 代码
 
package cn.gx80.service.util;  
  
import java.io.ByteArrayOutputStream;  
  
/** 
 * 验证码生成服务类 
 * @author 飞天色鼠 
 * 
 */  
public interface ValidateImageService {  
    /** 
     * 默认验证字符串 
     */  
    String Default_ValidateCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
    /** 
     * 默认绘制干扰线的类型(不绘制干扰线) 
     */  
    int Disturb_Type_Default = 0;  
    /** 
     * 绘制单一色调的干扰线 
     */  
    int Disturb_Type_Simple = 1;  
    /** 
     * 绘制复杂的干扰线 
     */  
    int Disturb_Type_Complex = 2;  
      
    /** 
     * 生成验证图片并返回验证码 
     * @param disturbType 
     * @param fontSize 
     * @param bos 
     * @param width 
     * @param height 
     * @param validateCode 
     * @param codeLength 
     * @return 
     */  
    public abstract String createValidateCode(int disturbType, int fontSize, ByteArrayOutputStream bos, int width, int height, String validateCode,int codeLength);  
      
}  


验证码生成的实现 ValidateImageServiceImp.java


java 代码
 
package cn.gx80.service.util;  
  
import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics;  
import java.awt.image.BufferedImage;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.util.Random;  
  
import javax.imageio.ImageIO;  
import javax.imageio.stream.ImageOutputStream;  
  
  
public class ValidateImageServiceImp implements ValidateImageService{  
      
    public String createValidateCode(int disturbType, int fontSize, ByteArrayOutputStream bos, int width, int height, String validateCode,int codeLength){  
        BufferedImage bImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);  
        Graphics g = bImg.getGraphics();  
        Random random = new Random();  
          
        if(null == validateCode || validateCode.isEmpty()){  
            validateCode = Default_ValidateCode;  
        }  
        if(fontSize >= height){  
            fontSize = height-1;  
        }  
          
        drawOutline(g,width,height);  
        switch (disturbType) {  
        case Disturb_Type_Simple:  
            drawSimpleDisturb(g,random,width,height);  
            break;  
        case Disturb_Type_Complex:  
            drawDisturb(g,random,width,height);  
            break;  
        default:  
            break;  
        }  
          
        String code = drawCode(g,random,validateCode,codeLength,width,height,fontSize);  
        g.dispose();  
        try {                
            ImageOutputStream   imOut   =ImageIO.createImageOutputStream(bos);    
            ImageIO.write(bImg,"JPEG",imOut);  
            imOut.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return code;  
    }  
      
    /** 
     * 绘制边框 
     * @param g 
     * @param width 
     * @param height 
     */  
    private static void drawOutline(Graphics g, int width, int height){  
        g.setColor(Color.white);  
        g.fillRect(0,0,width,height);  
        g.setColor(Color.BLACK);  
        g.drawRect(0,0,width-1,height-1);  
    }  
      
    /** 
     * 绘制比较复杂的干扰线 
     * @param g 
     * @param random 
     * @param width 
     * @param height 
     */  
    private static void drawDisturb(Graphics g, Random random, int width, int height){  
        int x,y,x1,y1;  
        for(int i=0;i<width;i++){  
            x = random.nextInt(width);  
            y = random.nextInt(height);  
            x1 = random.nextInt(12);  
            y1 = random.nextInt(12);  
            g.setColor(getRandomColor(random,120,255));  
            g.drawLine(x,y,x+x1,y+y1);  
            g.fillArc(x,y,x1,y1,random.nextInt(360),random.nextInt(360));  
        }  
    }  
      
    /** 
     * 绘制简单的干扰线 
     * @param g 
     * @param random 
     * @param width 
     * @param height 
     */  
    private static void drawSimpleDisturb(Graphics g, Random random, int width, int height){  
        g.setColor(getRandomColor(random,160,200));  
        for (int i=0;i<155;i++)  
        {  
            int x = random.nextInt(width);  
            int y = random.nextInt(height);  
                int xl = random.nextInt(12);  
                int yl = random.nextInt(12);  
            g.drawLine(x,y,x+xl,y+yl);  
        }  
    }  
      
    /** 
     * 取得随机颜色 
     * @param random 
     * @param pMin 
     * @param pMax 
     * @return 
     */  
    private static Color getRandomColor(Random random, int pMin,int pMax){  
        pMax = (Math.abs(pMax) > 255 ? 255 : Math.abs(pMax));  
        pMin = (Math.abs(pMin) > 255 ? 255 :Math.abs(pMin));  
      
        int r = pMin + random.nextInt(Math.abs(pMax - pMin));  
        int g = pMin + random.nextInt(Math.abs(pMax - pMin));  
        int b = pMin + random.nextInt(Math.abs(pMax - pMin));  
      
        return new Color(r,g,b);  
    }   
      
    /** 
     * 绘制验证码 
     * @param g 
     * @param random 
     * @param validateCode 
     * @param codeLength 
     * @param width 
     * @param height 
     * @param fontSize 
     * @return 
     */  
    private static String drawCode(Graphics g, Random random, String validateCode,int codeLength, int width, int height, int fontSize){   
        int validateCodeLength = validateCode.length();  
        Font font1 = new Font("Verdana",Font.BOLD,fontSize);  
        Font font2 = new Font("serif",Font.BOLD,fontSize);  
          
        StringBuffer sb = new StringBuffer();       
        int x,y;  
        for(int i=0;i<codeLength;i++){  
            x = (width/codeLength-1) * i + random.nextInt(width/(codeLength * 2));  
            y = random.nextInt(height - fontSize) + fontSize;  
            sb.append(getRandomChar(validateCode,validateCodeLength,random));  
            g.setColor(getRandomColor(random,70,150));  
            if(sb.substring(i).getBytes().length > 1)  
            g.setFont(font2);  
            else  
            g.setFont(font1);  
            g.drawString(sb.substring(i),x,y);  
        }  
        return sb.toString();       
    }  
      
    /** 
     * 取得随机字符 
     * @param validateCode 
     * @param validateCodeLength 
     * @param random 
     * @return 
     */  
    private static char getRandomChar(String validateCode,int validateCodeLength,Random random){  
        return validateCode.charAt(random.nextInt(validateCodeLength));  
    }  
}  

struts.xml 配置


xml 代码
 
<package name="gx80-test" namespace="/test" extends="gx80-default">  
  
    <action name="validateCode" class="cn.gx80.control.action.basic.ValidateImgAction">  
        <interceptor-ref name="gx80DefaultStack"/>  
        <interceptor-ref name="staticParams"/>  
        <param name="width">100</param>  
        <param name="height">30</param>  
        <param name="fontSize">18</param>  
        <param name="codeLength">5</param>  
        <result name="success" type="stream">  
            <param name="contentType">image/jpeg</param>  
        </result>  
    </action>  
  
</package>  


当然还有语言文件中的验证码字符串 global.properties


java 代码
System.validateCode = abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/u4E00/u4E8C/u4E09/u56DB/u4E94/u516D/u4E03/u516B/u4E5D/u5341/u767E/u5343/u4E07/u5E7F/u897F/u5357/u5B81/u79D1/u56ED/u5927/u9053/u8F6F/u4EF6/u4E2D/u56FD/u4EBA/u6C11/u4E07/u5C81  


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/xiamizy/archive/2008/05/23/2473363.aspx

你可能感兴趣的:(struts2生成中文验证码的Action)