自定义拦截器
Posted 伊小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义拦截器相关的知识,希望对你有一定的参考价值。
1 package com.itheima.interceptors; 2 3 import javax.servlet.http.HttpSession; 4 5 import org.apache.struts2.ServletActionContext; 6 7 import com.itheima.domain.User; 8 import com.opensymphony.xwork2.ActionInvocation; 9 import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; 10 //执行动作方法前检查用户是否已经登录 11 public class SessionCheckInterceptors extends MethodFilterInterceptor{ 12 13 @Override 14 protected String doIntercept(ActionInvocation invocation) throws Exception { 15 String result = "login";//对应的就是一个结果 16 HttpSession session = ServletActionContext.getRequest().getSession(); 17 User user = (User)session.getAttribute("user"); 18 if(user!=null) 19 result = invocation.invoke(); 20 return result; 21 } 22 23 }
在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"></constant> <package name="mypackage" extends="struts-default" abstract="true"> <interceptors> <interceptor name="sessionCheck" class="com.itheima.interceptors.SessionCheckInterceptors"> <!-- 说明test2动作方法不需要拦截 --> <param name="excludeMethods">test2</param> </interceptor> <interceptor-stack name="myDefaultStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="sessionCheck"></interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="myDefaultStack"></default-interceptor-ref> </package> <package name="p1" extends="mypackage"> <action name="test1" class="com.itheima.action.HelloAction1" method="test1"> <result>/1.jsp</result> <result name="login">/login.jsp</result> </action> <action name="test2" class="com.itheima.action.HelloAction1" method="test2"> <result>/2.jsp</result> </action> </package> </struts>
以上是关于自定义拦截器的主要内容,如果未能解决你的问题,请参考以下文章