天天看點

Ext随機驗證碼實作

上幾篇文章,主要學習了 Extjs4 Grid 的使用方法,從本篇開始,我們開始其他元件的

學習,使用。在登入、注冊甚至是發表文章或文章的時候,都會用到驗證碼這個東西,那

麼在 EXTJS 中,可以使用驗證碼功能麼?答案是肯定的,在 EXTJS4 之前,也有很多驗證

碼的實作,在 Extjs4 中,驗證碼到底如何實作呢?

        暫時,我們将驗證碼元件,命名為 CheckCode。此元件繼承自 Ext.form.field.Text,在

實作之前,我們需要寫兩個樣式,分别用來控制驗證碼的輸入框和驗證碼圖檔的大小。

CSS 樣式為:

Css代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. #CheckCode{ float:left;}    
  2. .x-form-code{width:73px;height:20px;vertical-align:middle;cursor:pointer; float:left; margin-left:7px;}   
#CheckCode{ float:left;} 
.x-form-code{width:73px;height:20px;vertical-align:middle;cursor:pointer; float:left; margin-left:7px;} 
           

         記住這兩個樣式的定義,後面,我們會用到它。

驗證碼的 JS 代碼(CheckCode.js):

Js代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. Ext.define('SMS.view.CheckCode', {   
  2.     extend: 'Ext.form.field.Text',   
  3.     alias: 'widget.checkcode',   
  4.     inputType: 'codefield',   
  5.     codeUrl: Ext.BLANK_IMAGE_URL,   
  6.     isLoader: true,   
  7.     onRender: function(ct, position) {   
  8.         this.callParent(arguments);   
  9.         this.codeEl = ct.createChild({   
  10.             tag: 'img',   
  11.             src: Ext.BLANK_IMAGE_URL   
  12.         });   
  13.         this.codeEl.addCls('x-form-code');   
  14.         this.codeEl.on('click', this.loadCodeImg, this);   
  15.         if(this.isLoader) {   
  16.             this.loadCodeImg();   
  17.         }   
  18.     },   
  19.     aliasErrorIcon: function() {   
  20.         this.errorIcon.alignTo(this.codeEl, 'tl-tr', [2, 0]);   
  21.     },   
  22.     loadCodeImg: function() {   
  23.         //如果浏覽器發現url不變,就認為圖檔沒有改變,就會使用緩存中的圖檔,而不是重新向伺服器請求,是以需要加一個參數,改變url    
  24.         this.codeEl.set({   
  25.             src: this.codeUrl + '?id=' + Math.random()   
  26.         });   
  27.     }   
  28. });  
Ext.define('SMS.view.CheckCode', {
    extend: 'Ext.form.field.Text',
    alias: 'widget.checkcode',
    inputType: 'codefield',
    codeUrl: Ext.BLANK_IMAGE_URL,
    isLoader: true,
    
    onRender: function(ct, position) {
        this.callParent(arguments);
        this.codeEl = ct.createChild({
            tag: 'img',
            src: Ext.BLANK_IMAGE_URL
        });
        this.codeEl.addCls('x-form-code');
        this.codeEl.on('click', this.loadCodeImg, this);
        
        if(this.isLoader) {
            this.loadCodeImg();
        }
    },
    
    aliasErrorIcon: function() {
        this.errorIcon.alignTo(this.codeEl, 'tl-tr', [2, 0]);
    },
    
    loadCodeImg: function() {
        //如果浏覽器發現url不變,就認為圖檔沒有改變,就會使用緩存中的圖檔,而不是重新向伺服器請求,是以需要加一個參數,改變url 
        this.codeEl.set({
            src: this.codeUrl + '?id=' + Math.random()
        });
    }
});      

         以上代碼中,定義了一個―類‖,名字是:SMS.view.CheckCode,其實這個名字,相當

于 extjs 3.x 之中的命名空間,以前也提到過。它繼承自 Ext.form.field.Text,在它的

onRender 中,我們寫了一些代碼。其中 this.callParent(arguments);  代替了

xxxx.superclass.onRender.call(this, ct, position);在 Ext.form.field.Text 的基礎上,使用

createChild 方法,建立了一個圖檔,并為其添加了一個名為 x-form-code,而後,給其建立

了一個 click 事件,這個事件實作的功能是,當我們點選驗證碼圖檔時,換另外一張圖檔,

也就是常說的:―看不清?換一張功能。‖,最後,如果 isLoader 為 True 時,調用

loadCodeImg 方法。至此,驗證碼功能全部完成了。下面,我們看看如何使用。

建立 Login.js 檔案,定義―類‖SMS.view.Login,其全部代碼為(Login.js):

Js代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. Ext.define('SMS.view.Login', {   
  2.     extend: 'Ext.window.Window',   
  3.     alias: 'widget.loginForm',   
  4.     requires: [   
  5.         'Ext.form.*',    
  6.         'SMS.view.CheckCode'  
  7.     ],   
  8.     initComponent: function() {   
  9.         var checkcode = Ext.create('SMS.view.CheckCode', {   
  10.             cls: 'key',   
  11.             fieldLabel: '驗證碼',   
  12.             name: 'checkcode',   
  13.             id: 'checkcode',   
  14.             allowBlank: false,   
  15.             isLoader: true,   
  16.             blankText: '驗證碼不能為空',   
  17.             codeUrl: 'rand.action',   
  18.             width: 160   
  19.         });   
  20.         var form = Ext.widget('form', {   
  21.             border: false,   
  22.             bodyPadding: 10,   
  23.             fieldDefaults: {   
  24.                 labelAlign: 'left',   
  25.                 labelWidth: 55,   
  26.                 labelStyle: 'font-weight: bold'                   
  27.             },   
  28.             defaults: {   
  29.                 margins: '0 0 10 0'  
  30.             },   
  31.             items: [{   
  32.                 xtype: 'textfield',   
  33.                 id: 'username',   
  34.                 name: 'username',   
  35.                 fieldLabel: '使用者名',   
  36.                 blankText: '使用者名不能為空',   
  37.                 allowBlank: false,   
  38.                 width: 240   
  39.             }, {   
  40.                 xtype: 'textfield',   
  41.                 id: 'password',   
  42.                 name: 'password',   
  43.                 fieldLabel: '密   碼',   
  44.                 allowBlank: false,   
  45.                 blankText: '密碼不能為空',   
  46.                 width: 240,   
  47.                 inputType: 'password'  
  48.             }, checkcode],   
  49.             buttons: [{   
  50.                 text: '登入',   
  51.                 handler: function() {   
  52.                 //擷取目前的表單form   
  53.                 var form = this.up('form').getForm();   
  54.                 //判斷否通過了表單驗證,如果不能空的為空則不能送出   
  55.                 if (form.isValid()) {   
  56.                     //alert("可以送出");   
  57.                     form.submit({   
  58.                         clientValidation : true,   
  59.                         waitMsg : '請稍候',   
  60.                         waitTitle : '正在驗證登入',   
  61.                         url : 'login.action',   
  62.                         success : function(form, action) {   
  63.                             //登入成功後的操作,這裡隻是提示一下   
  64.                             Ext.MessageBox.show({   
  65.                                 width : 150,   
  66.                                 title : "登入成功",   
  67.                                 buttons : Ext.MessageBox.OK,   
  68.                                 msg : action.result.msg   
  69.                             })   
  70.                         },   
  71.                         failure : function(form, action) {   
  72.                             Ext.MessageBox.show({   
  73.                                 width : 150,   
  74.                                 title : "登入失敗",   
  75.                                 buttons : Ext.MessageBox.OK,   
  76.                                 msg : action.result.msg   
  77.                             })   
  78.                         }   
  79.                     })   
  80.                 }   
  81.                 }   
  82.             }, {   
  83.                 text: '取消',   
  84.                 handler: function() {   
  85.                     //點選取消,關閉登入視窗   
  86.                     // var form = this.up('form');   
  87.                     // form.close();   
  88.                 }   
  89.             }]   
  90.         });   
  91.         Ext.apply(this, {   
  92.             height: 160,   
  93.             width: 280,   
  94.             title: '使用者登入',   
  95.             closeAction: 'hide',   
  96.             closable: false,   
  97.             iconCls: 'login',   
  98.             layout: 'fit',   
  99.             modal: true,   
  100.             plain: true,    
  101.             resizable: false,   
  102.             items: form   
  103.         });   
  104.         this.callParent(arguments);   
  105.     }   
  106. });  
Ext.define('SMS.view.Login', {
    extend: 'Ext.window.Window',
    alias: 'widget.loginForm',
    requires: [
    	'Ext.form.*', 
    	'SMS.view.CheckCode'
    ],
    
    initComponent: function() {
        
        var checkcode = Ext.create('SMS.view.CheckCode', {
            cls: 'key',
            fieldLabel: '驗證碼',
            name: 'checkcode',
            id: 'checkcode',
            allowBlank: false,
            isLoader: true,
            blankText: '驗證碼不能為空',
            codeUrl: 'rand.action',
            width: 160
        });
        
        var form = Ext.widget('form', {
            border: false,
            bodyPadding: 10,
            fieldDefaults: {
                labelAlign: 'left',
                labelWidth: 55,
                labelStyle: 'font-weight: bold'                
            },
            defaults: {
                margins: '0 0 10 0'
            },
            items: [{
                xtype: 'textfield',
                id: 'username',
                name: 'username',
                fieldLabel: '使用者名',
                blankText: '使用者名不能為空',
                allowBlank: false,
                width: 240
            }, {
                xtype: 'textfield',
                id: 'password',
                name: 'password',
                fieldLabel: '密   碼',
                allowBlank: false,
                blankText: '密碼不能為空',
                width: 240,
                inputType: 'password'
            }, checkcode],
            
            buttons: [{
                text: '登入',
                handler: function() {
                //擷取目前的表單form
                var form = this.up('form').getForm();
                //判斷否通過了表單驗證,如果不能空的為空則不能送出
                if (form.isValid()) {
                    //alert("可以送出");
                    form.submit({
                        clientValidation : true,
                        waitMsg : '請稍候',
                        waitTitle : '正在驗證登入',
                        url : 'login.action',
                        success : function(form, action) {
                            //登入成功後的操作,這裡隻是提示一下
                            Ext.MessageBox.show({
                                width : 150,
                                title : "登入成功",
                                buttons : Ext.MessageBox.OK,
                                msg : action.result.msg
                            })
                        },
                        failure : function(form, action) {
                            Ext.MessageBox.show({
                                width : 150,
                                title : "登入失敗",
                                buttons : Ext.MessageBox.OK,
                                msg : action.result.msg
                            })
                        }
                    })
                }
                }
            }, {
                text: '取消',
                handler: function() {
                    //點選取消,關閉登入視窗
                    // var form = this.up('form');
                    // form.close();
                }
            }]
        });
        
        Ext.apply(this, {
            height: 160,
            width: 280,
            title: '使用者登入',
            closeAction: 'hide',
            closable: false,
            iconCls: 'login',
            layout: 'fit',
            modal: true,
            plain: true, 
            resizable: false,
            items: form
        });
        this.callParent(arguments);
    }
});      

 程式的入口(app.js):

Js代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. Ext.application({   
  2.     name: 'SMS',   
  3.     appFolder: 'app',   
  4.     launch: function() {   
  5.         requires: ['SMS.view.Login']   
  6.         var win;   
  7.         win = Ext.create('SMS.view.Login').show();   
  8.     }      
  9. });  
Ext.application({
    name: 'SMS',
    
    appFolder: 'app',
    
    launch: function() {
        requires: ['SMS.view.Login']
        var win;
        win = Ext.create('SMS.view.Login').show();
    }   
    
});      

login.jsp:

Jsp代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   
  2. <%   
  3. String path = request.getContextPath();   
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   
  5. %>   
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   
  7. <html>   
  8.   <head>   
  9.     <base href="<%=basePath%>">   
  10.     <title>使用者登入</title>   
  11.     <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" />   
  12.     <script type="text/javascript" src="extjs/ext-all.js"></script>   
  13.     <script type="text/javascript" src="extjs/ext-lang-zh_CN.js"></script>   
  14.     <script type="text/javascript" src="app.js"></script>   
  15.     <style type="text/css">   
  16.         #checkcode {   
  17.             float: left;   
  18.         }   
  19.         .x-form-code {   
  20.             width: 73px;   
  21.             height: 20px;   
  22.             vertical-align: middle;   
  23.             cursor: pointer;   
  24.             float: left;   
  25.             margin-left: 7px;   
  26.         }   
  27.     </style>   
  28.   </head>   
  29.   <body>   
  30.   </body>   
  31. </html>  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <base href="<%=basePath%>" target="_blank" rel="external nofollow" >
    
    <title>使用者登入</title>
		
	<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" target="_blank" rel="external nofollow"  />
	<script type="text/javascript" src="extjs/ext-all.js"></script>
	<script type="text/javascript" src="extjs/ext-lang-zh_CN.js"></script>
	<script type="text/javascript" src="app.js"></script>

	<style type="text/css">
		#checkcode {
			float: left;
		}
		
		.x-form-code {
			width: 73px;
			height: 20px;
			vertical-align: middle;
			cursor: pointer;
			float: left;
			margin-left: 7px;
		}
	</style>

  </head>
  
  <body>
  </body>
</html>
      

生成随機驗證碼的類( RandomNumUtil.java):

Java代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. package org.changkong.sms.utils;   
  2. import java.awt.Color;   
  3. import java.awt.Font;   
  4. import java.awt.Graphics;   
  5. import java.awt.image.BufferedImage;   
  6. import java.io.ByteArrayInputStream;   
  7. import java.io.ByteArrayOutputStream;   
  8. import java.util.Random;   
  9. import javax.imageio.ImageIO;   
  10. import javax.imageio.stream.ImageOutputStream;   
  11. public class RandomNumUtil {   
  12.     private ByteArrayInputStream image;     //圖像   
  13.     private String str;     //驗證碼   
  14.     private RandomNumUtil() {   
  15.         init();     //初始化屬性   
  16.     }   
  17.     public static RandomNumUtil Instance() {   
  18.         return new RandomNumUtil();   
  19.     }   
  20.     public ByteArrayInputStream getImage() {   
  21.         return this.image;   
  22.     }   
  23.     public String getString() {   
  24.         return this.str;   
  25.     }   
  26.     private void init() {   
  27.         //在記憶體中建立圖象   
  28.         //圖像的高度和寬度   
  29.         int width = 55, height = 20;   
  30.         BufferedImage image = new BufferedImage(width, height,   
  31.                 BufferedImage.TYPE_INT_RGB);   
  32.         //擷取圖形上下文   
  33.         Graphics g = image.getGraphics();   
  34.         //生成随機類   
  35.         Random random = new Random();   
  36.         //設定背景色   
  37.         g.setColor(getRandColor(200, 250));   
  38.         g.fillRect(0, 0, width, height);   
  39.         //設定字型   
  40.         g.setFont(new Font("Times New Roman", Font.PLAIN, 18));   
  41.         //随機産生155條幹擾線,使圖象中的認證碼不易被其它程式探測到   
  42.         g.setColor(getRandColor(160, 200));   
  43.         for (int i = 0; i < 155; i++) {   
  44.             int x = random.nextInt(width);   
  45.             int y = random.nextInt(height);   
  46.             int xl = random.nextInt(12);   
  47.             int yl = random.nextInt(12);   
  48.             g.drawLine(x, y, x + xl, y + yl);   
  49.         }   
  50.         //取随機産生的認證碼(6位數字)   
  51.         String sRand = "";   
  52.         for (int i = 0; i < 4; i++) {   
  53.             String rand = String.valueOf(random.nextInt(10));   
  54.             sRand += rand;   
  55.             //将認證碼顯示到圖象中   
  56.             g.setColor(new Color(20 + random.nextInt(110), 20 + random   
  57.                     .nextInt(110), 20 + random.nextInt(110)));   
  58.             //調用函數出來的顔色相同,可能是因為種子太接近,是以隻能直接生成   
  59.             g.drawString(rand, 13 * i + 6, 16);   
  60.         }   
  61.         //指派驗證碼   
  62.         this.str = sRand;   
  63.         //圖象生效   
  64.         g.dispose();   
  65.         ByteArrayInputStream input = null;   
  66.         ByteArrayOutputStream output = new ByteArrayOutputStream();   
  67.         try {   
  68.             ImageOutputStream imageOut = ImageIO   
  69.                     .createImageOutputStream(output);   
  70.             ImageIO.write(image, "JPEG", imageOut);   
  71.             imageOut.close();   
  72.             input = new ByteArrayInputStream(output.toByteArray());   
  73.         } catch (Exception e) {   
  74.             System.out.println("驗證碼圖檔産生出現錯誤:" + e.toString());   
  75.         }   
  76.         this.image = input;  
  77.     }   
  78.     private Color getRandColor(int fc, int bc) {   
  79.         Random random = new Random();   
  80.         if (fc > 255)   
  81.             fc = 255;   
  82.         if (bc > 255)   
  83.             bc = 255;   
  84.         int r = fc + random.nextInt(bc - fc);   
  85.         int g = fc + random.nextInt(bc - fc);   
  86.         int b = fc + random.nextInt(bc - fc);   
  87.         return new Color(r, g, b);   
  88.     }   
  89. }  
package org.changkong.sms.utils;

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;

/**
 * 生成驗證碼的類檔案
 * 
 */
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 = 55, 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 < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			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);
	}
}
           

 驗證碼的Action(SecurityCodeAction.java):

Java代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. package org.changkong.sms.action;   
  2. import java.io.ByteArrayInputStream;   
  3. import org.changkong.sms.utils.RandomNumUtil;   
  4. import org.springframework.context.annotation.Scope;   
  5. import org.springframework.stereotype.Controller;   
  6. import com.opensymphony.xwork2.ActionContext;   
  7. import com.opensymphony.xwork2.ActionSupport;   
  8. @Controller("sercurityCodeAction")   
  9. @Scope("prototype")   
  10. public class SecurityCodeAction extends ActionSupport {   
  11.     private ByteArrayInputStream inputStream;   
  12.     public String execute() throws Exception {   
  13.         RandomNumUtil rdnu = RandomNumUtil.Instance();   
  14.         //取得帶有随機字元串的圖檔   
  15.         this.setInputStream(rdnu.getImage());      
  16.         //取得随機字元串放入HttpSession   
  17.         ActionContext.getContext().getSession().put("random", rdnu.getString());       
  18.         return SUCCESS;   
  19.     }   
  20.     public void setInputStream(ByteArrayInputStream inputStream) {   
  21.         this.inputStream = inputStream;   
  22.     }   
  23.     public ByteArrayInputStream getInputStream() {   
  24.         return inputStream;   
  25.     }   
  26. }  
package org.changkong.sms.action;

import java.io.ByteArrayInputStream;

import org.changkong.sms.utils.RandomNumUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 驗證碼的Action
 * 使用SSH內建開發,Action由Spring管理
 */
@Controller("sercurityCodeAction")
@Scope("prototype")
public class SecurityCodeAction extends ActionSupport {
	
	private ByteArrayInputStream inputStream;

	public String execute() throws Exception {
		
		RandomNumUtil rdnu = RandomNumUtil.Instance();
		
		//取得帶有随機字元串的圖檔
		this.setInputStream(rdnu.getImage());	
		
		//取得随機字元串放入HttpSession
		ActionContext.getContext().getSession().put("random", rdnu.getString());	
		return SUCCESS;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}
	
}
           

 登入Action(LoginAction.java):

Java代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. package org.changkong.sms.action;   
  2. import org.apache.struts2.ServletActionContext;   
  3. import org.springframework.context.annotation.Scope;   
  4. import org.springframework.stereotype.Controller;   
  5. import com.opensymphony.xwork2.ActionContext;   
  6. @Controller("loginAction")   
  7. @Scope("prototype")   
  8. public class LoginAction {   
  9.     private String username;   
  10.     private String password;   
  11.     private String checkcode; // 表單中的rand   
  12.     //從session中取出RandomAction.java 中生成的驗證碼random   
  13.     String arandom = (String) (ActionContext.getContext().getSession().get("random"));   
  14.     public String execute() {   
  15.         if(!arandom.equals(checkcode)) {   
  16.             System.out.println("驗證碼不正确");   
  17.         } else if(!"admin".equals(username)) {   
  18.             System.out.println("使用者不存在");   
  19.         } else if("admin".equals(password)) {   
  20.             System.out.println("密碼錯誤");   
  21.         }   
  22.         return "success";   
  23.     }   
  24.     public String logout() {   
  25.         ServletActionContext.getRequest().getSession().invalidate();   
  26.         return "logout";   
  27.     }   
  28.     public String getCheckcode() {   
  29.         return checkcode;   
  30.     }   
  31.     public void setCheckcode(String checkcode) {   
  32.         this.checkcode = checkcode;   
  33.     }   
  34.     public String getUsername() {   
  35.         return username;   
  36.     }   
  37.     public void setUsername(String username) {   
  38.         this.username = username;   
  39.     }   
  40.     public String getPassword() {   
  41.         return password;   
  42.     }   
  43.     public void setPassword(String password) {   
  44.         this.password = password;   
  45.     }   
  46. }  
package org.changkong.sms.action;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

/**
 * 登入Action
 */
@Controller("loginAction")
@Scope("prototype")
public class LoginAction {

	private String username;
	private String password;
	private String checkcode; // 表單中的rand

	//從session中取出RandomAction.java 中生成的驗證碼random
	String arandom = (String) (ActionContext.getContext().getSession().get("random"));

	public String execute() {
		
		if(!arandom.equals(checkcode)) {
			System.out.println("驗證碼不正确");
		} else if(!"admin".equals(username)) {
			System.out.println("使用者不存在");
		} else if("admin".equals(password)) {
			System.out.println("密碼錯誤");
		}
		return "success";

	}

	public String logout() {
		ServletActionContext.getRequest().getSession().invalidate();
		return "logout";
	}

	public String getCheckcode() {
		return checkcode;
	}

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
           

 Struts.xml:

Xml代碼

Ext随機驗證碼實作
Ext随機驗證碼實作
Ext随機驗證碼實作
  1. <!-- 使用者登陸 -->  
  2.         <action name="login" class="loginAction">  
  3.             <!-- LoginAction無需經過LoginInterceptor -->  
  4.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  5.             <result name="success" type="redirect">/main.jsp</result>  
  6.             <result name="fail">/login.jsp</result>  
  7.             <result name="logout">/login.jsp</result>  
  8.         </action>  
  9.         <!-- Random驗證碼 -->  
  10.         <action name="rand" class="sercurityCodeAction">  
  11.             <result type="stream">        
  12.                 <param name="contentType">image/jpeg</param>        
  13.                 <param name="inputName">inputStream</param>        
  14.             </result>     
  15.         </action>