struts2的基本配置以及jar包的导入就不说了只写关键部分:
<struts> <package name="userPackage" extends="struts-default">
<interceptors>
<!-- 自己写的一个拦截器 --> <interceptor name="loginCheck" class="com.xinzhi.interceptor.MyInterceptor"></interceptor> <interceptor-stack name="login_interceptor"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="loginCheck"></interceptor-ref> </interceptor-stack> </interceptors>
<action name="user_*" class="com.xinzhi.action.UserAction" method="{1}" >
<!-- 执行拦截器,写在action外面是拦截所有资源,写在里面是针对action内部资源进行拦截 --> <interceptor-ref name="login_interceptor"></interceptor-ref>
<!-- 获取的拦截器返回值及跳转页面 --> <result name="loginDefaulUser">/login.jsp</result>
<result name="loginUser" type="redirectAction">user_list</result> <result name="listUser">/WEB-INF/list.jsp</result> </action> </package> </struts>
自己写的一个拦截器的类要继承AbstractInterceptor
package com.xinzhi.interceptor; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class MyInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { ActionContext invocationContext = invocation.getInvocationContext();//拿到ActionContext String method = invocation.getProxy().getMethod();//调用代理获取方法名称 if (!"login".equals(method)) { Object object = invocationContext.getSession().get("userInfo"); if (object != null) { return invocation.invoke();//执行方法 } else { return "loginDefaulUser"; } } else { return invocation.invoke(); } } }