什么是拦截器?
java里的拦截器是动态拦截Action调用的对象。他提供了一种机制可以让开发人员定义在一个action执行的前后执行的代码,也可以在action执行前组织其执行,同时提供了一种可以提取action中可重用部分的方式。
大部分时候,拦截器方法都是通过代理的方式来调用的。Struts 2的拦截器实现相对简单。当请求到达Struts 2的ServletDispatcher时,Struts 2会查找配置文件,并根据其配置实例化相对的拦截器对象,然后串成一个列表(list),最后一个一个地调用列表中的拦截器。Struts2拦截器是可插拔的,拦截器是AOP的一种实现。Struts2拦截器栈就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,Struts2拦截器链中的拦截器就会按其之前定义的顺序被调用。
在项目中使用的效果
在执行一个Action的时候,拦截器会提前拦截Action,执行拦截器的方法,对Session进行判断,如果Session里面有内容,则进行正常的页面跳转,否则将会跳转到指定界面,也就是登录界面。这样有效的禁止了通过更改域名而进行的非法访问。
代码实现
PrivilegeInterceptor.java方法
package cn.itcast.shop.interceptor;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import cn.itcast.shop.adminuser.vo.AdminUser;
/**
* 后台权限校验的拦截器
* 对没有登录的用户,不可进行访问的
* @author Administrator
*
*/
public class PrivilegeInterceptor extends MethodFilterInterceptor{
@Override
//执行拦截方法
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
//判断session中是否保存了后台用户的信息
AdminUser existAdminUser = (AdminUser) ServletActionContext.getRequest().getAttribute("existAdminUser");
if(existAdminUser == null){
//没有登录进行访问
ActionSupport actionSupport = (ActionSupport) actionInvocation.getAction();
actionSupport.addActionError("亲!您还没有登录!没有权限访问!");
return "loginFail";
}else{
//已经登录过
return actionInvocation.invoke();
}
}
}
Struts2
<!-- 配置自定义拦截器 -->
<interceptors>
<interceptor name="privilegeInterceptor" class="cn.itcast.shop.interceptor.PrivilegeInterceptor"/>
</interceptors>
Struts2跳转页面时加入拦截器的代码
<!-- 后台一级分类管理Action -->
<action name="adminCategory_*" class="adminCategoryAction" method="{1}">
<interceptor-ref name="privilegeInterceptor"/>
<interceptor-ref name="defaultStack"/>
</action>
<!-- 后台二级分类管理Action -->
<action name="adminCategorySecond_*" class="adminCategorySecondAction" method="{1}">
<interceptor-ref name="privilegeInterceptor"/>
<interceptor-ref name="defaultStack"/>
</action>