web开发(二十一)之自定义拦截器的使用

时间:2023-03-09 04:55:49
web开发(二十一)之自定义拦截器的使用

转自博客:http://blog.****.net/pkgk2013/article/details/51985817

拦截器的作用

拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。  拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。

自定义拦截器

有的时候struts2提供的拦截器并不能满足我们的需求,所以我们会选择自定义拦截器。就以商城系统中,后台的数据管理为例,如果没有登录,就不能访问一系列后台的页面。

  1. 编写拦截器:
    • 编写一个类实现Interceptor接口.或者继承Interceptor的子类.
    • 配置拦截器.
public class PrivilegeInterceptor extends MethodFilterInterceptor{

    @Override
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
// 判断是否登录,如果登录,放行,没有登录,跳转到登录页面.
AdminUser adminUser = (AdminUser) ServletActionContext.getRequest()
.getSession().getAttribute("existAdminUser");
if(adminUser != null){
// 已经登录过
return actionInvocation.invoke();
}else{
// 跳转到登录页面:
ActionSupport support = (ActionSupport) actionInvocation.getAction();
support.addActionError("您还没有登录!没有权限访问!");
return ActionSupport.LOGIN;
}
} }

在struts.xml中进行配置

 
<!-- 配置自定义拦截器 -->
<interceptors>
<interceptor name="privilegeInterceptor" class="com.wgd.shop.interceptor.PrivilegeInterceptor"/>
</interceptors> //在这里,我们为了图方便,就直接写的是全局的访问
<global-results>
<result name="msg">/WEB-INF/jsp/msg.jsp</result>
<result name="login">/admin/index.jsp</result>
</global-results> //在相应的action中配置该拦截器
<!-- 后台一级分类管理Action -->
<action name="adminCategory_*" class="adminCategoryAction" method="{1}">
<result name="findAll">/admin/category/list.jsp</result>
<result name="saveSuccess" type="redirectAction">adminCategory_findAll</result>
<result name="deleteSuccess" type="redirectAction">adminCategory_findAll</result>
<result name="editSuccess">/admin/category/edit.jsp</result>
<result name="updateSuccess" type="redirectAction">adminCategory_findAll</result> <interceptor-ref name="privilegeInterceptor"/>
<interceptor-ref name="defaultStack"/>
</action>
//因为配置了自定义拦截器,默认的拦截器就没有了。所以得手动添加默认的拦截器