一:书写拦截器类java
package cn.itcast.myintercepter; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; /** * @author 做者 * @version 建立时间:2018年7月26日 下午2:42:24 * 类说明:拦截器建立方式 * 继承:MethodFilterIntercepter方法过滤拦截器 * 功能:定制拦截器拦截的方法 * 定制哪些方法须要拦截哪些方法不须要拦截 */ public class MyInterceptor extends MethodFilterInterceptor { @Override protected String doIntercept(ActionInvocation invocation) throws Exception { //1.得到session Map<String, Object> session = ActionContext.getContext().getSession(); //2.得到登录标识 Object object = session.get("user"); //3.判断登录标识是否存在 if(object==null) { //说明没有登录,重定向到登录页面 return "toLogin"; }else { //说明登录=》放行 return invocation.invoke(); } } }
二:配置struts文件web
<?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> <package name="crm" namespace="/" extends="struts-default"> <!-- 配置拦截器步骤 --> <interceptors> <!-- 1.注册拦截器 --> <interceptor name="myIntercator" class="cn.itcast.myintercepter.MyInterceptor"></interceptor> <!-- 2.注册拦截器栈--> <interceptor-stack name="myStack"> <!-- 自定义拦截器栈 --> <interceptor-ref name="myIntercator"> <!-- 不须要拦截的方法名 --> <param name="excludeMethods">login</param> </interceptor-ref> <!-- 引用默认的拦截器栈(20个) --> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 3.指定默认的拦截器栈 --> <default-interceptor-ref name="myStack"></default-interceptor-ref> <!-- 定义全局结果集 --> <global-results> <result name="toLogin" type="redirect">/login.jsp</result> </global-results> <global-exception-mappings> <!-- 若是出现java.lang.RuntimeException异常,就将跳转到名为error的结果 --> <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping> </global-exception-mappings> <action name="UserAction_*" class="cn.itcast.web.UserAction" method ="{1}"> <result name="toHome" type="redirect">/index.htm</result> </action> </package> </struts>