點擊刷新驗證碼結合js和struts示例

js代碼
<script language="javascript" type="text/javascript">
      function reloadImage(imgurl){
          var getimagecode=document.getElementById("codeimg");
          getimagecode.src= imgurl + "?id=" + Math.random();
      }
  </script>
jsp調用js、strut中的rand.action 代碼是我自己編寫的,如果copy 特別要注意路徑問題
<td height="35" width="20%">                                         <span class="login_txt STYLE1">驗證碼:</span>                    </td>      <td height="35" colspan="2" class="top_hui_text">                  <input type="text" class="wenbenkuang" id="code" name="code" maxlength="4" size="20">
  <img border="0" id="codeimg" name="codeimg" src="../rand.action">
 <a href="javascript:reloadImage('../rand.action')"><font color="red">看不清</font></a><br>
 </td>
接下來就是rand.action
package com.hz.bbs.action;

import java.io.ByteArrayInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.hz.bbs.util.RandomNumUtil;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class RandomAction extends ActionSupport{ 
    private ByteArrayInputStream inputStream; 
    public String execute() throws Exception{ 
       
        RandomNumUtil rdnu=RandomNumUtil.Instance(); 
       this.setInputStream(rdnu.getImage());//取得帶有隨機字符串的圖片 
       String str = rdnu.getString().toString();
       HttpServletRequest request = ServletActionContext.getRequest();       
         HttpSession session = request.getSession();
         session.setAttribute("randoms", str);//取得隨機字符串放入HttpSession
        return SUCCESS; 
    } 
    public void setInputStream(ByteArrayInputStream inputStream) { 
        this.inputStream = inputStream; 
    } 
   public ByteArrayInputStream getInputStream() { 
        return inputStream; 
    }
}

大家一定會覺得 那麼生產驗證碼的圖片 寫在那裏呢?別急,下面就是,我也是在網上copy的 只是拿來改改了
package com.hz.bbs.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
public class RandomNumUtil { 
    private ByteArrayInputStream image;//圖像 
    private String str;//驗證碼 
    //驗證碼序列。
    private static final char[] randomSequence = new char[] { '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', '0','1', '2', '3', '4', '5', '6',
        '7','8', '9' };
     
   private RandomNumUtil(){ 
        init();//初始化屬性 
    } 
    
    public static RandomNumUtil Instance(){ 
        return new RandomNumUtil(); 
   } 
    
    public ByteArrayInputStream getImage(){ 
       return this.image; 
   } 
    
    public String getString(){ 
        return this.str; 
    } 
     
    private void init() { 
        //       在內存中創建圖象 
        int width=60, height=20; 
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
        //       獲取圖形上下文 
        Graphics g = image.getGraphics(); 
        //      生成隨機類 
        Random random = new Random(); 
        //       設定背景色 
        g.setColor(getRandColor(200,250)); 
        g.fillRect(0, 0, width, height);
      //創建字體,字體的大小應該根據圖片的高度來定。
        Font font = new Font("Times New Roman", Font.PLAIN, height-2);
        //設置字體。
        g.setFont(font);
        //隨機產生155條幹擾線,使圖象中的認證碼不易被其它程序探測到 
        g.setColor(getRandColor(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); 
        } 
        //       取隨機產生的認證碼(6位數字) 
        String sRand=""; 
        for (int i=0;i<4;i++ ){ 
          int index = random.nextInt(35);
             String rand = String.valueOf(randomSequence[index]);
            sRand +=rand; 
            // 將認證碼顯示到圖象中 
            g.setColor(new Color(20 + random.nextInt(110), 20 + random  
                    .nextInt(110), 20 + random.nextInt(110)));
            //      調用函數出來的顏色相同,可能是因爲種子太接近,所以只能直接生成 
            g.drawString(rand, 13 * i + 6, 16);
        
        } 
     
        this.str=sRand;
       
    
        //       圖象生效 
        g.dispose(); 
        ByteArrayInputStream input=null; 
        ByteArrayOutputStream output = new ByteArrayOutputStream(); 
        try{ 
            ImageOutputStream imageOut = ImageIO.createImageOutputStream(output); 
            ImageIO.write(image, "JPEG", imageOut); 
            imageOut.close(); 
            input = new ByteArrayInputStream(output.toByteArray()); 
        }catch(Exception e){ 
            System.out.println("驗證碼圖片產生出現錯誤:"+ e.toString()); 
        } 
         
        this.image=input;
    } 
    
    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); 
   } 
 
}
最後一步,就是配置strut.xml了
 <action name="rand" class="com.hz.bbs.action.RandomAction">
   <result type="stream">
    <param name="contentType">image/jpeg</param>
    <param name="inputName">inputStream</param>
   </result>
  </action>
好了 大功告成了 呵呵
圖片展示:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章