Ext随机验证码实现

来源:互联网 发布:编程时说a having been 编辑:程序博客网 时间:2024/05/22 01:55

上几篇文章,主要学习了 Extjs4 Grid 的使用方法,从本篇开始,我们开始其他组件的
学习,使用。在登录、注册甚至是发表文章或帖子的时候,都会用到验证码这个东西,那
么在 EXTJS 中,可以使用验证码功能么?答案是肯定的,在 EXTJS4 之前,也有很多验证
码的实现,在 Extjs4 中,验证码到底如何实现呢?
        暂时,我们将验证码组件,命名为 CheckCode。此组件继承自 Ext.form.field.Text,在
实现之前,我们需要写两个样式,分别用来控制验证码的输入框和验证码图片的大小。
CSS 样式为:

Css代码 复制代码 收藏代码
  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代码 复制代码 收藏代码
  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.        
  8.     onRender: function(ct, position) {   
  9.         this.callParent(arguments);   
  10.         this.codeEl = ct.createChild({   
  11.             tag: 'img',   
  12.             src: Ext.BLANK_IMAGE_URL   
  13.         });   
  14.         this.codeEl.addCls('x-form-code');   
  15.         this.codeEl.on('click'this.loadCodeImg, this);   
  16.            
  17.         if(this.isLoader) {   
  18.             this.loadCodeImg();   
  19.         }   
  20.     },   
  21.        
  22.     aliasErrorIcon: function() {   
  23.         this.errorIcon.alignTo(this.codeEl, 'tl-tr', [2, 0]);   
  24.     },   
  25.        
  26.     loadCodeImg: function() {   
  27.         //如果浏览器发现url不变,就认为图片没有改变,就会使用缓存中的图片,而不是重新向服务器请求,所以需要加一个参数,改变url   
  28.         this.codeEl.set({   
  29.             src: this.codeUrl + '?id=' + Math.random()   
  30.         });   
  31.     }   
  32. });  
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代码 复制代码 收藏代码
  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.        
  9.     initComponent: function() {   
  10.            
  11.         var checkcode = Ext.create('SMS.view.CheckCode', {   
  12.             cls: 'key',   
  13.             fieldLabel: '验证码',   
  14.             name: 'checkcode',   
  15.             id: 'checkcode',   
  16.             allowBlank: false,   
  17.             isLoader: true,   
  18.             blankText: '验证码不能为空',   
  19.             codeUrl: 'rand.action',   
  20.             width: 160   
  21.         });   
  22.            
  23.         var form = Ext.widget('form', {   
  24.             border: false,   
  25.             bodyPadding: 10,   
  26.             fieldDefaults: {   
  27.                 labelAlign: 'left',   
  28.                 labelWidth: 55,   
  29.                 labelStyle: 'font-weight: bold'                   
  30.             },   
  31.             defaults: {   
  32.                 margins: '0 0 10 0'  
  33.             },   
  34.             items: [{   
  35.                 xtype: 'textfield',   
  36.                 id: 'username',   
  37.                 name: 'username',   
  38.                 fieldLabel: '用户名',   
  39.                 blankText: '用户名不能为空',   
  40.                 allowBlank: false,   
  41.                 width: 240   
  42.             }, {   
  43.                 xtype: 'textfield',   
  44.                 id: 'password',   
  45.                 name: 'password',   
  46.                 fieldLabel: '密   码',   
  47.                 allowBlank: false,   
  48.                 blankText: '密码不能为空',   
  49.                 width: 240,   
  50.                 inputType: 'password'  
  51.             }, checkcode],   
  52.                
  53.             buttons: [{   
  54.                 text: '登录',   
  55.                 handler: function() {   
  56.                 //获取当前的表单form   
  57.                 var form = this.up('form').getForm();   
  58.                 //判断否通过了表单验证,如果不能空的为空则不能提交   
  59.                 if (form.isValid()) {   
  60.                     //alert("可以提交");   
  61.                     form.submit({   
  62.                         clientValidation : true,   
  63.                         waitMsg : '请稍候',   
  64.                         waitTitle : '正在验证登录',   
  65.                         url : 'login.action',   
  66.                         success : function(form, action) {   
  67.                             //登录成功后的操作,这里只是提示一下   
  68.                             Ext.MessageBox.show({   
  69.                                 width : 150,   
  70.                                 title : "登录成功",   
  71.                                 buttons : Ext.MessageBox.OK,   
  72.                                 msg : action.result.msg   
  73.                             })   
  74.                         },   
  75.                         failure : function(form, action) {   
  76.                             Ext.MessageBox.show({   
  77.                                 width : 150,   
  78.                                 title : "登录失败",   
  79.                                 buttons : Ext.MessageBox.OK,   
  80.                                 msg : action.result.msg   
  81.                             })   
  82.                         }   
  83.                     })   
  84.                 }   
  85.                 }   
  86.             }, {   
  87.                 text: '取消',   
  88.                 handler: function() {   
  89.                     //点击取消,关闭登录窗口   
  90.                     // var form = this.up('form');   
  91.                     // form.close();   
  92.                 }   
  93.             }]   
  94.         });   
  95.            
  96.         Ext.apply(this, {   
  97.             height: 160,   
  98.             width: 280,   
  99.             title: '用户登录',   
  100.             closeAction: 'hide',   
  101.             closable: false,   
  102.             iconCls: 'login',   
  103.             layout: 'fit',   
  104.             modal: true,   
  105.             plain: true,    
  106.             resizable: false,   
  107.             items: form   
  108.         });   
  109.         this.callParent(arguments);   
  110.     }   
  111. });  
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代码 复制代码 收藏代码
  1. Ext.application({   
  2.     name: 'SMS',   
  3.        
  4.     appFolder: 'app',   
  5.        
  6.     launch: function() {   
  7.         requires: ['SMS.view.Login']   
  8.         var win;   
  9.         win = Ext.create('SMS.view.Login').show();   
  10.     }      
  11.        
  12. });  
Ext.application({    name: 'SMS',        appFolder: 'app',        launch: function() {        requires: ['SMS.view.Login']        var win;        win = Ext.create('SMS.view.Login').show();    }       });

 

 

login.jsp:

Jsp代码 复制代码 收藏代码
  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.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">   
  8. <html>   
  9.   <head>   
  10.     <base href="<%=basePath%>">   
  11.        
  12.     <title>用户登录</title>   
  13.            
  14.     <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" />   
  15.     <script type="text/javascript" src="extjs/ext-all.js"></script>   
  16.     <script type="text/javascript" src="extjs/ext-lang-zh_CN.js"></script>   
  17.     <script type="text/javascript" src="app.js"></script>   
  18.   
  19.     <style type="text/css">   
  20.         #checkcode {   
  21.             float: left;   
  22.         }   
  23.            
  24.         .x-form-code {   
  25.             width: 73px;   
  26.             height: 20px;   
  27.             vertical-align: middle;   
  28.             cursor: pointer;   
  29.             float: left;   
  30.             margin-left: 7px;   
  31.         }   
  32.     </style>   
  33.   
  34.   </head>   
  35.      
  36.   <body>   
  37.   </body>   
  38. </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%>">        <title>用户登录</title><link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css" /><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代码 复制代码 收藏代码
  1. package org.changkong.sms.utils;   
  2.   
  3. import java.awt.Color;   
  4. import java.awt.Font;   
  5. import java.awt.Graphics;   
  6. import java.awt.image.BufferedImage;   
  7. import java.io.ByteArrayInputStream;   
  8. import java.io.ByteArrayOutputStream;   
  9. import java.util.Random;   
  10.   
  11. import javax.imageio.ImageIO;   
  12. import javax.imageio.stream.ImageOutputStream;   
  13.   
  14. /**  
  15.  * 生成验证码的类文件  
  16.  *   
  17.  */  
  18. public class RandomNumUtil {   
  19.     private ByteArrayInputStream image;     //图像  
  20.     private String str;     //验证码  
  21.   
  22.     private RandomNumUtil() {   
  23.         init();     //初始化属性   
  24.     }   
  25.   
  26.     /*  
  27.      * 取得RandomNumUtil实例  
  28.      */  
  29.     public static RandomNumUtil Instance() {   
  30.         return new RandomNumUtil();   
  31.     }   
  32.   
  33.     /*  
  34.      * 取得验证码图片  
  35.      */  
  36.     public ByteArrayInputStream getImage() {   
  37.         return this.image;   
  38.     }   
  39.   
  40.     /*  
  41.      * 取得图片的验证码  
  42.      */  
  43.     public String getString() {   
  44.         return this.str;   
  45.     }   
  46.   
  47.     private void init() {   
  48.         //在内存中创建图象   
  49.         //图像的高度和宽度   
  50.         int width = 55, height = 20;   
  51.         BufferedImage image = new BufferedImage(width, height,   
  52.                 BufferedImage.TYPE_INT_RGB);   
  53.         //获取图形上下文   
  54.         Graphics g = image.getGraphics();   
  55.         //生成随机类   
  56.         Random random = new Random();   
  57.         //设定背景色   
  58.         g.setColor(getRandColor(200250));   
  59.         g.fillRect(00, width, height);   
  60.         //设定字体   
  61.         g.setFont(new Font("Times New Roman", Font.PLAIN, 18));   
  62.         //随机产生155条干扰线,使图象中的认证码不易被其它程序探测到   
  63.         g.setColor(getRandColor(160200));   
  64.         for (int i = 0; i < 155; i++) {   
  65.             int x = random.nextInt(width);   
  66.             int y = random.nextInt(height);   
  67.             int xl = random.nextInt(12);   
  68.             int yl = random.nextInt(12);   
  69.             g.drawLine(x, y, x + xl, y + yl);   
  70.         }   
  71.         //取随机产生的认证码(6位数字)   
  72.         String sRand = "";   
  73.         for (int i = 0; i < 4; i++) {   
  74.             String rand = String.valueOf(random.nextInt(10));   
  75.             sRand += rand;   
  76.             //将认证码显示到图象中   
  77.             g.setColor(new Color(20 + random.nextInt(110), 20 + random   
  78.                     .nextInt(110), 20 + random.nextInt(110)));   
  79.             //调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成   
  80.             g.drawString(rand, 13 * i + 616);   
  81.         }   
  82.         //赋值验证码   
  83.         this.str = sRand;   
  84.   
  85.         //图象生效   
  86.         g.dispose();   
  87.         ByteArrayInputStream input = null;   
  88.         ByteArrayOutputStream output = new ByteArrayOutputStream();   
  89.         try {   
  90.             ImageOutputStream imageOut = ImageIO   
  91.                     .createImageOutputStream(output);   
  92.             ImageIO.write(image, "JPEG", imageOut);   
  93.             imageOut.close();   
  94.             input = new ByteArrayInputStream(output.toByteArray());   
  95.         } catch (Exception e) {   
  96.             System.out.println("验证码图片产生出现错误:" + e.toString());   
  97.         }   
  98.         this.image = input;/* 赋值图像 */  
  99.     }   
  100.   
  101.     /*  
  102.      * 给定范围获得随机颜色  
  103.      */  
  104.     private Color getRandColor(int fc, int bc) {   
  105.         Random random = new Random();   
  106.         if (fc > 255)   
  107.             fc = 255;   
  108.         if (bc > 255)   
  109.             bc = 255;   
  110.         int r = fc + random.nextInt(bc - fc);   
  111.         int g = fc + random.nextInt(bc - fc);   
  112.         int b = fc + random.nextInt(bc - fc);   
  113.         return new Color(r, g, b);   
  114.     }   
  115. }  
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代码 复制代码 收藏代码
  1. package org.changkong.sms.action;   
  2.   
  3. import java.io.ByteArrayInputStream;   
  4.   
  5. import org.changkong.sms.utils.RandomNumUtil;   
  6. import org.springframework.context.annotation.Scope;   
  7. import org.springframework.stereotype.Controller;   
  8.   
  9. import com.opensymphony.xwork2.ActionContext;   
  10. import com.opensymphony.xwork2.ActionSupport;   
  11.   
  12. /**  
  13.  * 验证码的Action  
  14.  * 使用SSH集成开发,Action由Spring管理  
  15.  */  
  16. @Controller("sercurityCodeAction")   
  17. @Scope("prototype")   
  18. public class SecurityCodeAction extends ActionSupport {   
  19.        
  20.     private ByteArrayInputStream inputStream;   
  21.   
  22.     public String execute() throws Exception {   
  23.            
  24.         RandomNumUtil rdnu = RandomNumUtil.Instance();   
  25.            
  26.         //取得带有随机字符串的图片   
  27.         this.setInputStream(rdnu.getImage());      
  28.            
  29.         //取得随机字符串放入HttpSession   
  30.         ActionContext.getContext().getSession().put("random", rdnu.getString());       
  31.         return SUCCESS;   
  32.     }   
  33.   
  34.     public void setInputStream(ByteArrayInputStream inputStream) {   
  35.         this.inputStream = inputStream;   
  36.     }   
  37.   
  38.     public ByteArrayInputStream getInputStream() {   
  39.         return inputStream;   
  40.     }   
  41.        
  42. }  
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());//取得随机字符串放入HttpSessionActionContext.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代码 复制代码 收藏代码
  1. package org.changkong.sms.action;   
  2.   
  3. import org.apache.struts2.ServletActionContext;   
  4. import org.springframework.context.annotation.Scope;   
  5. import org.springframework.stereotype.Controller;   
  6.   
  7. import com.opensymphony.xwork2.ActionContext;   
  8.   
  9. /**  
  10.  * 登录Action  
  11.  */  
  12. @Controller("loginAction")   
  13. @Scope("prototype")   
  14. public class LoginAction {   
  15.   
  16.     private String username;   
  17.     private String password;   
  18.     private String checkcode; // 表单中的rand  
  19.   
  20.     //从session中取出RandomAction.java 中生成的验证码random   
  21.     String arandom = (String) (ActionContext.getContext().getSession().get("random"));   
  22.   
  23.     public String execute() {   
  24.            
  25.         if(!arandom.equals(checkcode)) {   
  26.             System.out.println("验证码不正确");   
  27.         } else if(!"admin".equals(username)) {   
  28.             System.out.println("用户不存在");   
  29.         } else if("admin".equals(password)) {   
  30.             System.out.println("密码错误");   
  31.         }   
  32.         return "success";   
  33.   
  34.     }   
  35.   
  36.     public String logout() {   
  37.         ServletActionContext.getRequest().getSession().invalidate();   
  38.         return "logout";   
  39.     }   
  40.   
  41.     public String getCheckcode() {   
  42.         return checkcode;   
  43.     }   
  44.   
  45.     public void setCheckcode(String checkcode) {   
  46.         this.checkcode = checkcode;   
  47.     }   
  48.   
  49.     public String getUsername() {   
  50.         return username;   
  51.     }   
  52.   
  53.     public void setUsername(String username) {   
  54.         this.username = username;   
  55.     }   
  56.   
  57.     public String getPassword() {   
  58.         return password;   
  59.     }   
  60.   
  61.     public void setPassword(String password) {   
  62.         this.password = password;   
  63.     }   
  64. }  
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 中生成的验证码randomString 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代码 复制代码 收藏代码
  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.            
  10.         <!-- Random验证码 -->  
  11.         <action name="rand" class="sercurityCodeAction">  
  12.             <result type="stream">        
  13.                 <param name="contentType">image/jpeg</param>        
  14.                 <param name="inputName">inputStream</param>        
  15.             </result>     
  16.         </action>  
原创粉丝点击