struts2中的拦截器接口:<<interface>> Interceptor,方法有:void destroy(),void init(),String intercept(ActionInvocation invocation),其中init方法和destroy方法是用于初始化和销毁的,只会执行一次。所以拦截器时单例的。intercept方法是拦截器的核心方法,执行任何动作方法都会经过该方法。
Iterceptor接口又有一个抽象的实现类<<class>> AbstractInterceptor,自定义接口时,可以继承此类,再重写String intercept(ActionInvocation invocation)方法,但是不推荐。
<<class>> MethodFilterInterceptor又有一个子类:<<class>> MethodFilterInterceptor,其方法中有一个protected abstract String doIntercept(ActionInvocation invocation) 。我们自定义拦截器时
一般选择继承这个类,并重写doIntercept,下面上一段拦截器代码(以检查用户是否登录为例)
public class CheckLoginInterceptor extends MethodFilterInterceptor {
public String doIntercept(ActionInvocation invocation) throws Exception {
//1.获取HttpSession
HttpSession session = ServletActionContext.getRequest().getSession();
//2.获取session域中的登录标记
Object obj = session.getAttribute("user");
//3.判断是否有登录标记
if(obj == null){
//用户没有登录
return "input";
}
//4.用户登录了,放行
String rtValue = invocation.invoke();
return rtValue;
}
}
之后在struts的配置文件中,配置需要拦截哪些方法,和需要放过哪些方法。(下面代码中的配置方法只要给出不需要拦截的方法)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="p1" extends="struts-default">
<interceptors><!-- 配置自定义拦截器,name=拦截器命,class=包名+类名-->
<interceptor name="checkLoginInterceptor" class="com.helloDev.web.interceptor.CheckLoginInterceptor" />
<interceptor-stack name="myDefaultStack"><!--自定义拦截器栈-->
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="checkLoginInterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!--修改struts2默认的拦截器栈为我们自定义的拦截器栈-->
<default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
<global-results><!--设置出错回显页面-->
<result name="input">/login.jsp</result>
</global-results>
<action name="login" class="com.helloDev.web.action.Demo2Action" method="login">
<interceptor-ref name="myDefaultStack">
<!-- 在引用自定义拦截器栈的时候,为了给登录方法设置为不拦截,给指定的拦截器注入参数。方式就是:拦截器名称.属性名称 -->
<param name="checkLoginInterceptor.excludeMethods">login</param>
</interceptor-ref>
<result type="redirectAction">showMain</result>
</action>
<action name="showMain" class="com.helloDev.web.action.mainAction" >
<result>/main.jsp</result>
</action>
<action name="showOther" class="com.helloDev.web.action.otherpageAction" >
<result>/otherpage.jsp</result>
</action>
</package>
</struts>