struts2自定义拦截器

  1. 首先定义拦截类,该类实现 Interceptor接口InterceptorUtil.java
@Component
public class InterceptorUtil implements Interceptor{
    @Autowired
    private IBrandService brandService;
    @Autowired
    private IStyleService styleService;
    @Autowired
    private IShopService shopService;
    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void init() {
        // TODO Auto-generated method stub

    }
     //在intercept方法中编写功能代码。比如网页的公共部分的数据显示,还有一些验证用户是否登录等
    public String intercept(ActionInvocation invocation) throws Exception {
    //该例子是网站导航条下拉菜单的动态显示
        List<Brand> brandList = brandService.selectBrand();
        System.out.println(brandList.size()+" ->brandList");
        List<Style> styleList = styleService.selectStyle();
        System.out.println(styleList.size()+" ->styleList");
        List<Shop> shopList = shopService.selectShop(0, 6);
        System.out.println(shopList.size()+" ->shopList");
        //保存查询的数据
        ActionContext.getContext().put("brandList", brandList);
        ActionContext.getContext().put("styleList", styleList);
        ActionContext.getContext().put("shopList", shopList);
        return invocation.invoke();  //执行接下来的方法
    }   
} 

2.在struts的配置文件中定义拦截器 index——struts.xml

<interceptors>
<!--引入自定义的拦截器类InterceptorUtil.java类。由于使用了@Component注解所以可以用类名首字母小写的形式-->
                <interceptor name="interceptorUtil" class="interceptorUtil"/>
                <!--拦截器栈-->
                <interceptor-stack name="myStack">
                    <!--引入上面的自定义拦截器-->
                    <interceptor-ref name="interceptorUtil"/>
                    <!--注意自定义拦截器必须要引入默认的拦截器,否则会报错-->
                    <interceptor-ref name="defaultStack"/>
                </interceptor-stack>
            </interceptors>
  1. 在要跳转的action配置中引入拦截器栈。因为拦截器先执行所以可以通过拦截把需要的数据先查询出来再跳转,也可用来校验是否登陆等功能。
            <action name="main">
                <!--引入上面定义的拦截器栈-->
                <interceptor-ref name="myStack"/>
                <!--要跳转的页面-->
                <result type="redirectAction">toIndex!selectBanner.go</result>
            </action>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值