码迷,mamicode.com
首页 > 其他好文 > 详细

自定义拦截器

时间:2016-04-03 00:25:36      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.itheima.interceptors;
 2 
 3 import javax.servlet.http.HttpSession;
 4 
 5 import org.apache.struts2.ServletActionContext;
 6 
 7 import com.itheima.domain.User;
 8 import com.opensymphony.xwork2.ActionInvocation;
 9 import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
10 //执行动作方法前检查用户是否已经登录
11 public class SessionCheckInterceptors extends MethodFilterInterceptor{
12 
13     @Override
14     protected String doIntercept(ActionInvocation invocation) throws Exception {
15         String result = "login";//对应的就是一个结果
16         HttpSession session = ServletActionContext.getRequest().getSession();
17         User user = (User)session.getAttribute("user");
18         if(user!=null)
19             result = invocation.invoke();
20         return result;
21     }
22     
23 }

在Struts配置文件中进行配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <constant name="struts.devMode" value="true"></constant>
    
    <package name="mypackage" extends="struts-default" abstract="true">
        <interceptors>
            <interceptor name="sessionCheck" class="com.itheima.interceptors.SessionCheckInterceptors">
                <!-- 说明test2动作方法不需要拦截 -->
                <param name="excludeMethods">test2</param>
            </interceptor>
            <interceptor-stack name="myDefaultStack">
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="sessionCheck"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
    </package>
    
    <package name="p1" extends="mypackage">
        <action name="test1" class="com.itheima.action.HelloAction1" method="test1">
            <result>/1.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
        <action name="test2" class="com.itheima.action.HelloAction1" method="test2">
            <result>/2.jsp</result>
        </action>
    </package>
</struts>

 

自定义拦截器

标签:

原文地址:http://www.cnblogs.com/lzy1991/p/5348594.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!