1.自定义拦截器类
package com.baizhi.interceptor;
import org.apache.struts2.ServletActionContext;
import com.baizhi.entity.Admin;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
//自定义拦截器类继承拦截器抽象类
public class AdminInterceptor extends MethodFilterInterceptor{
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
//从session中取出登录用户标记
Admin admin = (Admin) ServletActionContext.getRequest().getSession().getAttribute("admin");
if(admin==null){
return "adminLogin";
}else{
invocation.invoke();//放行
}
return null;
}
}
2.配置拦截器栈
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "struts-2.1.7.dtd" >
<struts>
<package name="insert" extends="struts-default">
<interceptors>
<!-- 注册拦截器 定义了一个名为AdminInterceptor的拦截器 -->
<interceptor name="AdminInterceptor" class="com.baizhi.interceptor.AdminInterceptor">
<!-- 两种方法取一个 extends MethodFilterInterceptor类中的配置-->
<!-- add 和 delete都是方法名, 方法名中间用逗号隔开 -->
<!--
指定哪些方法不拦截
<param name="excludeMethods">add,delete</param>
-->
<!-- 指定哪些方法需要拦截 -->
<param name="includeMethods">queryAll</param>
</interceptor>
<!--注册拦截器栈 定义一个包含权限检查的拦截器栈 -->
<interceptor-stack name="AdminStack">
<!-- 定义拦截器栈包含AdminInterceptor拦截器 -->
<interceptor-ref name="AdminInterceptor"/>
<!-- 定义拦截器栈包含default-stack拦截器栈 -->
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<!-- 定义全局Result -->
<global-results>
<!-- 当返回adminLogin视图名时,转入/login.jsp页面 -->
<result name="adminLogin" >/login.jsp</result>
</global-results>
</package>
</struts>
3.配置拦截器
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "struts-2.1.7.dtd" >
<struts>
<!-- extends 配置拦截器栈的主struts -->
<package name="category" extends="insert" namespace="/category">
<action name="*" class="com.baizhi.action.CategoryAction" method="{1}">
<!-- 使用定义拦截器栈 -->
<interceptor-ref name="AdminStack"/>
<result name="queryAll" >/back/category/show.jsp</result>
<result name="add" type="redirectAction">queryAll</result>
<result name="queryBylevels" >/back/category/add-second.jsp</result>
<result name="delete" type="chain">queryAll</result>
</action>
</package>
</struts>