Struts2 下拦截器的简单使用

GitHub 地址

访问GitHub下载最新源码:https://github.com/JYG0723/Struts2_Action


简介:

环境与基本配置与上一篇一致。这里简单的利用一个拦截器拦截一个对 Aciton 的请求,计算了一下访问一次该 Action 所花费的时间。拦截器的作用还请自行百度


第一个拦截器实例:访问 Action 时间记录

TimerAction

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;
    }
}

TimerInteceptor

public class TimerInterceptor extends AbstractInterceptor {

    // 执行 Action 的时候,会自动调用该方法
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        // 执行 Action 之前,获取当前系统时间
        long start = System.currentTimeMillis();

        // 执行下一个拦截器,如果已经是最后一个拦截器,则执行目标 Action
        String result = actionInvocation.invoke();

        // 执行 Action 之后,获取当前系统时间
        long end = System.currentTimeMillis();

        System.out.println("执行Action花费的时间: " + (end - start));
        return result;
    }

}

struts.xml

<package name="default" namespace="/" extends="struts-default">
    <!-- 注册拦截器 -->
    <interceptors>
        <interceptor name="timerInterceptor" class="interceptor.TimerInterceptor"></interceptor>
    </interceptors>

    <action name="timer" class="action.TimerAction">
        <!-- 引用拦截器 -->
        <interceptor-ref name="timerInterceptor"></interceptor-ref>
        <result>/success.jsp</result>
    </action>
</package>

index.jsp

<a href="timer">点击计算访问一次 Action 所花费的时间</a>

Struts2 内建拦截器

  • params 拦截器
    • 负责将请求参数设置为 Action 属性
  • staticParams 拦截器
    • 将配置文件中 action 元素的子元素 param 参数设置为 Action 属性
  • servletConfig 拦截器
    • 将源于 Servlet API 的各种对象注入到 Action,必须实现对应接口
  • fileUpload 拦截器
    • 对文件上传提供支持,将文件和元数据设置到对应的 Action 属性中
  • exception 拦截器
    • 捕获 Struts2 中发生的异常, 并且将异常映射到用户自定义的页面
  • validation 拦截器
    • 调用验证框架进行数据验证

struts-default.xml

<interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
<interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
<interceptor name="chain" class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/>
<interceptor name="conversionError" class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/>
<interceptor name="cookie" class="org.apache.struts2.interceptor.CookieInterceptor"/>
<interceptor name="cookieProvider" class="org.apache.struts2.interceptor.CookieProviderInterceptor"/>
<interceptor name="clearSession" class="org.apache.struts2.interceptor.ClearSessionInterceptor" />
<interceptor name="createSession" class="org.apache.struts2.interceptor.CreateSessionInterceptor" />
<interceptor name="debugging" class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />
<interceptor name="execAndWait" class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/>
<interceptor name="exception" class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/>
<interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>
<interceptor name="i18n" class="org.apache.struts2.interceptor.I18nInterceptor"/>
<interceptor name="logger" class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/>
<interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>
<interceptor name="scopedModelDriven" class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/>
<interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>
<interceptor name="actionMappingParams" class="org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/>
<interceptor name="prepare" class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/>
<interceptor name="staticParams" class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>
<interceptor name="scope" class="org.apache.struts2.interceptor.ScopeInterceptor"/>
<interceptor name="servletConfig" class="org.apache.struts2.interceptor.ServletConfigInterceptor"/>
<interceptor name="timer" class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/>
<interceptor name="token" class="org.apache.struts2.interceptor.TokenInterceptor"/>
<interceptor name="tokenSession" class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/>
<interceptor name="validation" class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/>
<interceptor name="workflow" class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/>
<interceptor name="store" class="org.apache.struts2.interceptor.MessageStoreInterceptor" />
<interceptor name="checkbox" class="org.apache.struts2.interceptor.CheckboxInterceptor" />
<interceptor name="datetime" class="org.apache.struts2.interceptor.DateTextFieldInterceptor" />
<interceptor name="profiling" class="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />
<interceptor name="roles" class="org.apache.struts2.interceptor.RolesInterceptor" />
<interceptor name="annotationWorkflow" class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor" />
<interceptor name="multiselect" class="org.apache.struts2.interceptor.MultiselectInterceptor" />
<interceptor name="noop" class="org.apache.struts2.interceptor.NoOpInterceptor" />

可以看到 Struts2 的内建拦截器有很多。当然有的我们会用到,有的不会用到。但其还为我们声明了许多的拦截器栈,方便我们以组合的形式来使用。默认的,只要你的struts.xml文件中的package标签的extends="struts-default"。那么下面的defaultStack默认拦截器栈已经被你这个包下的所有 Action 所使用。

defaultStack

<interceptor-stack name="defaultStack">
    <interceptor-ref name="exception"/>
    <interceptor-ref name="alias"/>
    <interceptor-ref name="servletConfig"/>
    <interceptor-ref name="i18n"/>
    <interceptor-ref name="prepare"/>
    <interceptor-ref name="chain"/>
    <interceptor-ref name="scopedModelDriven"/>
    <interceptor-ref name="modelDriven"/>
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="checkbox"/>
    <interceptor-ref name="datetime"/>
    <interceptor-ref name="multiselect"/>
    <interceptor-ref name="staticParams"/>
    <interceptor-ref name="actionMappingParams"/>
    <interceptor-ref name="params"/>
    <interceptor-ref name="conversionError"/>
    <interceptor-ref name="validation">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="workflow">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="debugging"/>
</interceptor-stack>

注意:

需要注意的就是,当为包中的某个 Action 显示的指定了某个拦截器,则默认的拦截器将不再起作用。

struts.xml

<action name="timer" class="action.TimerAction">
    <!--在拦截器调用的时候,配置的先后顺序决定了该 Action 的拦截器的调用顺序,一般先调用默认的拦截器栈-->
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <!-- 引用拦截器 -->
    <interceptor-ref name="timerInterceptor"></interceptor-ref>
    <result>/success.jsp</result>
</action>

第二个拦截器实例:权限验证

LoginAction

public class LoginAction extends ActionSupport implements SessionAware {

    private String username;
    private String password;
    // 封装了 session 的 Map 集合,需要实现 SessionAware 接口
    private Map<String, Object> session;

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    // getter/setter

    /**
     * 处理登录请求
     */
    public String login() {
        if ("admin".equals(username) && "admin".equals(password)) {
            session.put("loginInfo", username);
            return SUCCESS;
        } else {
            session.put("loginError", "用户名和密码不正确");
            return ERROR;
        }
    }
}

AuthInterceptor

public class AuthInterceptor extends AbstractInterceptor {

    public String intercept(ActionInvocation actionInvocation) throws Exception {

        ActionContext actionContext = ActionContext.getContext();
        Map<String, Object> session = actionContext.getSession();

        if (session.get("loginInfo") != null) {
            String result = actionInvocation.invoke();
            return result;
        } else {
            return "login";
        }
    }
}

struts.xml

<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>
    <constant name="struts.devMode" value="true"></constant>

    <package name="default" namespace="/" extends="struts-default">

        <interceptors>
            <interceptor name="auth" class="interceptor.AuthInterceptor"></interceptor>
            <!-- 自定义拦截器栈,组合了 auth Inteceptor 和 defaultStack -->
            <interceptor-stack name="myStack">
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="auth"></interceptor-ref>
            </interceptor-stack>
        </interceptors>

        <!-- 通过该 Action 访问后台管理页面,需要判断用户是否已登录,如果未登录则跳转到登录页面 -->
        <action name="auth"> 
            <!-- 这里没有实现类,会默认调用 ActionSupport 类,则结果一定返回 `success`,但经过拦截器就会被修改规则判定如果没有登录则返回 `login` -->
            <interceptor-ref name="myStack"></interceptor-ref>
            <result>/WEB-INF/page/admin.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
        
        <!-- 通过该 Action 处理表单登录验证,如果用户名和密码有误则跳转到登录页面 -->
        <action name="login" class="action.LoginAction" method="login">
            <result>/WEB-INF/page/admin.jsp</result>
            <result name="error">/login.jsp</result>
        </action>

    </package>
</struts>

login.jsp

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

推荐阅读更多精彩内容