- 首先定义拦截类,该类实现 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>
- 在要跳转的action配置中引入拦截器栈。因为拦截器先执行所以可以通过拦截把需要的数据先查询出来再跳转,也可用来校验是否登陆等功能。
<action name="main">
<!--引入上面定义的拦截器栈-->
<interceptor-ref name="myStack"/>
<!--要跳转的页面-->
<result type="redirectAction">toIndex!selectBanner.go</result>
</action>