自定义Struts2拦截器以及配置

//PS:可以直接继承 AbstractInterceptor 抽象类  
//(帮我们空实现了 初始化和销毁2个方法   让我们只要关注 —拦截—这个方法)
public class MyInterceptor implements Interceptor {
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("MyInterceptor 正在销毁");
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		System.out.println("执行拦截");
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("MyInterceptor 正在初始化");
		
		String result=invocation.invoke();	//判断如果有下一个拦截器  就调用下一个
							//如果没有了  执行action的execute()
		return result;
	}
}


----------------------配置如下-------------------------------------
<!-- 配置拦截器 -->
		<interceptors>
				<!--name为 拦截器的名字		class为 拦截器的类全名 -->
			<interceptor name="myInterceptor" class="zl.MyInterceptor">		
				<!--  现在只是声明好了拦截器   要在具体的action里配置它的应用 -->
			</interceptor>
		</interceptors>

<!--配置拦截器栈 -->
	<interceptor-stack name="demoInterceptor">
		<interceptor-ref name="myInterceptor"></interceptor-ref>
		<interceptor-ref name="defaultStack"></interceptor-ref>
	</interceptor-stack>

<!--PS:也可以直接定义默认来拦截器栈 就可以不用在action里再配置-->
<default-interceptor-ref name="demoInterceptor" />

<!--如不设置默认,则action中配置-->
<!--配置Action-->
<action name="input3" class="zl.PointAction" method="exec3">
			<result>/output.jsp</result>
			<result name="input">/input.jsp</result>
			<!-- 在action里配置拦截器 -->
			<interceptor-ref name="demoInterceptor"></interceptor-ref>
		</action>

你可能感兴趣的:(jsp)