在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實例
*/
public static RandomNumUtil Instance(){
return new RandomNumUtil();
}
/*
* 取得驗證碼圖片
*/
public ByteArrayInputStream getImage(){
return this.image;
}
/*
* 取得圖片的驗證碼
*/
public String getString(){
return this.str;
}
private void init() {
// 在內存中創建圖象
int width=85, 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);
// 設定字體
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
// 隨機產生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<6;i++){
// String rand=String.valueOf(random.nextInt(10));
// sRand+=rand;
char selectChar[] = {'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',
'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'};//所有候選組成驗證碼的字符,當然也可以用中文的
for (int i=0;i<6;i++){
// String rand=String.valueOf(random.nextInt(10));
// sRand+=rand;
int charIndex = (int) Math.floor(Math.random()*62);
String rand = String.valueOf(selectChar[charIndex]);
sRand +=selectChar[charIndex];
// 將認證碼顯示到圖象中
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);
}
}
2.配置action,將上述action返回的邏輯結果設置爲文件流類型
struct.xml 代碼
<action name="rand" class="com.ection.utiltool.VerifyCode">
<result type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
</action>
3.寫一個測試的html頁面,使其請求上面的action,得到返回的圖片結果。
<script type="text/javascript">
function changeValidateCode(obj) {
//獲取當前的時間作爲參數,無具體意義
var timenow = new Date().getTime();
//每次請求需要一個不同的參數,否則可能會返回同樣的驗證碼
//這和瀏覽器的緩存機制有關係,也可以把頁面設置爲不緩存,這樣就不用這個參數了。
obj.src="rand.action?d="+timenow;
}
</script>
<img src="rand.action" οnclick="changeValidateCode(this)"/>
4.客戶端的驗證代碼。
public class CheckAction extends ActionSupport{
private String str;//客戶輸入的圖片驗證碼
public String execute(){
String str2=(String)(ActionContext.getContext().getSession().get("random"));//取得session保存中的字符串
//下面就是將session中保存驗證碼字符串與客戶輸入的驗證碼字符串對比了
if(str2.equalsIgnoreCase(this.getStr())){
return SUCCESS;
}else{
return LOGIN;
}
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}