一.定义拦截器类,实现Interceptor接口,重写里面的方法:
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor implements Interceptor {
public String intercept(ActionInvocation invocation) throws Exception {
Object user = ActionContext.getContext().getSession().get("userkey");
if(user != null)
return invocation.invoke(); //表示被拦截到的方法继续会执行action
ActionContext.getContext().put("requestKey", "�㻹û�е�½");
return "success";
}
public void init() {
}
public void destroy() {
}
}
二.配置struts2的配置文件:
<struts>
<!-- 禁止对action方法的动态调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<!-- 指定访问action的后缀类型 -->
<constant name="struts.action.extension" value="action"></constant>
<!-- 将struts2的ui设置为simple -->
<constant name=”struts.ui.theme”value=”simple”/>
<!-- 将struts2的ObjectFactory交给spring管理 -->
<constant name="struts.ObjectFactory" value="spring"></constant>
<package name="default" namespace="/myaction" extends="struts-default">
<!--
在bean.xml中定义拦截器:
写入自己定义的拦截器
编写拦截器栈,包括系统默认的拦截器和自己定义的拦截器
最后再想调用拦截器的action中加入拦截器栈
-->
<interceptors>
<interceptor name="mi" class="com.interceptor.MyInterceptor"></interceptor>
<interceptor-stack name="mistack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="mi"></interceptor-ref>
</interceptor-stack>
</interceptors>
———— <default-interceptor-ref的意思是设置mistack为该包下的默认拦截器。(如果action中有则执行action中的拦截器不执行默认的)
<default-interceptor-ref name="mistack"></default-interceptor-ref>
<global-results>
<result name="success">/WEB-INF/page/hello.jsp</result>
</global-results>
<action name="hello_*" class="com.action.Hello" method="{1}">
<interceptor-ref name="mistack"></interceptor-ref>
</action>
</package>
<!-- Add packages here -->
</struts>