struts2拦截器

一.struts2框架整体流程

struts2-3.jpg
Paste_Image.png
Paste_Image.png

二.第一个demo

1.创建被拦截的action

package com.lxf.timerintercepter;
/**
 * 做一个耗时的actioin,用拦截器统计该action执行的时间
 */

import com.opensymphony.xwork2.ActionSupport;

public class TimerAction extends ActionSupport{

    @Override
    public String execute() throws Exception {
            for(int i=0;i<10000;i++)
            {
                System.out.println("I LOVE IMOOC");
            }
            return SUCCESS;
    }
    
}

2.创建拦截器

package com.lxf.timerintercepter;
/**
 * 拦截器,用来计算timerAction的执行时间
 */

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class TimerIntercepter extends AbstractInterceptor {

    /**
     * 自动调用此方法,进行拦截操作
     */
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
           //1.执行Action之前
           long start = System.currentTimeMillis(); //获得当前的毫秒值
           //2.执行下一个拦截器,如果已经是最后一个拦截器,则执行目标action
           String res = invocation.invoke();
           //3.执行Action之后
           long end = System.currentTimeMillis(); 
           System.out.println("执行Action话费的时间:" + (end - start) + "ms");
           //将最终调用Action之后的结果视图返回   
           return res;
    }

}

3.在Timer.xml中注册和在对应action中引用拦截器

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default2" namespace="/myTimer" extends="struts-default">
        <!-- 注册拦截器 -->
        <interceptors>
            <interceptor name="mytimer"  class="com.lxf.timerintercepter.TimerIntercepter"></interceptor>
        </interceptors>
        <action name="timerAction" class="com.lxf.timerintercepter.TimerAction">
            <result>/result.jsp</result>
            <!-- 引用拦截器 -->
            <interceptor-ref name="mytimer"></interceptor-ref>
        </action>
    </package>
</struts>   

4.在struts.xml中包含timer.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <!-- 使用include标签引入各个模块xml配置文件 -->
    <include file="helloworld.xml"></include>
    <include file="helloworld2.xml"></include>
    <!-- 引入测试action执行时间xml的配置文件 -->
     <include file="timer.xml"></include>
    
    
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    
    <!-- 使用感叹号方式配置多个method -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
    <!-- 配置action后缀 -->
    <constant name="struts.action.extension" value="html,action,do"></constant>
</struts>   

5.将项目部署到tomcat上,访问地址:

http://localhost:8081/struts2-test1/myTimer/timerAction.action

查看控制台拦截器产生作用:

...
I LOVE IMOOC
I LOVE IMOOC
I LOVE IMOOC
执行Action话费的时间:29ms

三.struts2内置拦截器

Paste_Image.png
Paste_Image.png
  • 内置拦截器我们可以查看struts2核心jar包struts2-core-2.3.1.jar中的struts-default.xml

  • 在struts-default.xml中配置了默认拦截器栈


    Paste_Image.png
  • 所以推荐在自己显示为某个action引用拦截器之前,将默认拦截器栈先手动引用

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default2" namespace="/myTimer" extends="struts-default">
        <!-- 注册拦截器 -->
        <interceptors>
            <interceptor name="mytimer"  class="com.lxf.timerintercepter.TimerIntercepter"></interceptor>
        </interceptors>
        <action name="timerAction" class="com.lxf.timerintercepter.TimerAction">
            <result>/result.jsp</result>
            <!-- 为Action显示引用拦截器后,默认的拦截器defaultStack不在生效,需要手工引用 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <!-- 引用拦截器 -->
            <interceptor-ref name="mytimer"></interceptor-ref>
        </action>
    </package>
</struts>   

四.使用拦截器实现对用户登录验证

1.在WEB_INF目录中简历/page/manager.jsp,作为用户后台页面.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
后台管理页面,只有已登录的页面才能够访问!
</body>
</html>

2.写loginNew.jsp登录页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>用户登陆</h2>
${loginError}
<form  action="loginNew.action" method="post">
    用户名:<input type="text" name="username"  />
    密码:<input type="password" name="password" />
    <input type="submit" value="登录" />
</form>
</body>
</html> 

3.写登录LoginNewAction.java

package com.lxf.action;
/**
 * 用户登录页面,用来判断用户是否登录
 */

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class LoginNewAction extends ActionSupport implements SessionAware{
    private String username;
    private String password;
    private Map<String,Object> session;
    /**
     * 实现SessionAware中的接口
     */
    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
        // TODO Auto-generated method stub
    }
    
    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;
    }
    
    /**
     * 处理登录请求
     */
    public String loginNew()    
    {
        if("admin".equals(username) && "123".equals(password))
        {
            session.put("loginInfo", username);
            return SUCCESS;
        }else
        {
            session.put("loginError", "用户名或密码不正确!");
            return ERROR;
        }
    }
}

4.写AuthIntercepter.java拦截器

package com.lxf.timerintercepter;
/**
 * 拦截器,用来验证用户登录
 */

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthIntercepter extends AbstractInterceptor {

    /**
     * 自动调用此方法,进行拦截操作
     */
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
           ActionContext context = ActionContext.getContext();
           Map<String,Object> session = context.getSession();
           //用户已登录
           if(session.get("loginInfo") !=null)
           {
               String result = invocation.invoke();
               return result;
           }else
            //用户未登录
           {
               return "login";
           }
    }
}

4.配置自定义manager.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
 <!-- 后台管理配置文件,判断用户登录 -->
<struts>
    <package name="default5" namespace="/manager" extends="struts-default">
        <!-- 注册拦截器 -->
        <interceptors>
            <interceptor name="auth" class="com.lxf.timerintercepter.AuthIntercepter"></interceptor>
            <!-- 自定义拦截器栈myStack,组合了defaultStack和auth -->
            <interceptor-stack name="myStack">
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="auth"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        
        <!-- 通过Action访问后台管理页面,需要判断用户是否已登录,如果未登录则跳转到登录页 -->
        <action name="auth">
            <result>/WEB-INF/page/manager.jsp</result>
            <result name="login">/loginNew.jsp</result>
            <!-- 引用自定义拦截器栈 -->
            <interceptor-ref name="myStack"></interceptor-ref>
        </action>
        
        <!-- 登录action -->
        <action name="loginNew" class="com.lxf.action.LoginNewAction" method="loginNew">
            <result>/WEB-INF/page/manager.jsp</result>
            <result name="error">/loginNew.jsp</result>
        </action>
    </package>
</struts>   

5.在struts.xml中引用manager.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <!-- 使用include标签引入各个模块xml配置文件 -->
    <include file="helloworld.xml"></include>
    <include file="helloworld2.xml"></include>
    <!-- 引入测试action执行时间xml的配置文件 -->
     <include file="timer.xml"></include>
    <!-- 引入后台管理配置文件,判断用户登录xml -->
     <include file="manager.xml"></include>
    
    
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    
    <!-- 使用感叹号方式配置多个method -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
    <!-- 配置action后缀 -->
    <constant name="struts.action.extension" value="html,action,do"></constant>
    <!-- 打开开发模式 -->
    <constant name="struts.devMode" value="true"></constant>
</struts>   

6.在没有登录的情况下,访问:

http://localhost:8081/struts2-test1/manager/auth.action

过滤器会判断是否登录,如果登录了则跳转套manager.jsp页面,否则跳转套登录页面

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容