Struts2之拦截器

拦截器:在Action执行之前和之后进行一些额外的操作,相当于过滤器

拦截器的工作方式 

1、拦截器

<interceptor name="privilege" class="com.test.interceptor.PrivilegeInterceptor"></interceptor>

  name-拦截器名称

  class-拦截器的实现类

2、拦截器栈

在实际开发中,需要在Action执行前执行多个拦截器,这时可以把多个拦截器组成一个拦截器栈,可以将栈内的多个拦截器当作一个整体来引用。

定义拦截器栈使用<interceptor-stack>

  name-拦截器栈名

定义多个拦截器使用<interceptor-ref>

<interceptor-stack name="myStack">
       <interceptor-ref name="defaultStack"></interceptor-ref>
       <interceptor-ref name="privilege"></interceptor-ref>
</interceptor-stack>

在Action中声明拦截器使用<interceptor-ref>

<action name="book_*" class="com.test.Action.BookAction" method="{1}">
            <result>/success2.jsp</result>
            <result name="login">/login.jsp</result>
            <interceptor-ref name="myStack"></interceptor-ref>
</action>

3、默认拦截器

如果相对一个包(package)中的Action使用相同的拦截器,使用默认拦截器更方便些

<default-interceptor-ref>

<default-interceptor-ref name="defaultStack"></interceptor-ref>

默认拦截器在包内声明,若包内Action未显示的指定拦截器,则使用默认浏览器,若Action指定了拦截器,则覆盖掉默认拦截器。

一个包下只有一个默认拦截器,若想要多个默认拦截器,先将需要设置为默认的拦截器设置为拦截器栈,再使用default指定拦截器栈。

4、自定义拦截器

 建立一个java类继承AbstractInterceptor重写

public String intercept(ActionInvocation invocation) throws Exception{return null;}
public class PrivilegeInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation invocation) throws Exception{
        ActionContext ac=invocation.getInvocationContext();
        Object user = ac.getSession().get("user");
        if (user!=null){
            return invocation.invoke();
        }else {
            ac.put("msg","未登录,请先登录");
            return Action.LOGIN;
        }
    }
}

 

<interceptor name="privilege" class="com.test.interceptor.PrivilegeInterceptor"></interceptor>

在<interceptor>的class元素中选择实现的拦截器类,就可以使用自定义拦截器了。

转载于:https://www.cnblogs.com/GG-Bond/p/10544672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值