在Struts2中配备自定义的拦截器的方法
在Struts2中配置自定义的拦截器的方法:
一、扩展拦截器接口的自定义拦截器配置
二、继承抽象拦截器的自定义拦截器配置
三、继承方法拦截器的自定义拦截器配置
接下来我们一个个去实现过去!(LoginAction.java,login.jsp,index.jsp参照struts2核心技术的代码)
扩展拦截器接口的自定义拦截器配置 1、配置struts.xml文件! 2、Action配置中拦截器参数定义 3、拦截器参数的设置
自定义拦截器类代码:
Struts.xml文件配置信息
接下:继承抽象拦截器的自定义拦截器配置<!--EndFragment--><!--EndFragment-->package struts.zdy.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class ExampleInterceptor implements Interceptor
{
//设置新参数
private String newParam;
public String getNewParam()
{
return newParam;
}
public void setNewParam(String newParam)
{
this.newParam = newParam;
}
//拦截器的销毁方法
public void destroy()
{
System.out.println("end doing......");
}
//拦截器的初始方法
public void init()
{
System.out.println("start doing......");
System.out.println("newParam is :"+newParam);
}
//拦截器拦截方法
public String intercept(ActionInvocation arg0) throws Exception
{
System.out.println("start invoking.....");
String result=arg0.invoke();
System.out.println("end invoking.......");
return result;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 声明DTD文件 -->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Action 所在包定义 name为项目名,扩展默认文件struts-default.xml配置文件-->
<package name="Struts2Test" extends="struts-default">
<!-- 拦截器配置定义 -->
<interceptors>
<interceptor name="example" class="struts.zdy.interceptor.ExampleInterceptor">
<!-- 参数设置 -->
<param name="newParam">test</param>
</interceptor>
</interceptors>
<!-- Action名字,类以及导航页面定义 -->
<!-- 通过Action类处理才导航的Action定义 -->
<action name="Login" class="struts.action.LoginAction">
<result name="input">login.jsp</result>
<result name="success">index.jsp</result>
<!-- Action 中拦截器定义 -->
<interceptor-ref name="example">
<!-- 改变拦截器参数值 -->
<param name="newParam">example</param>
</interceptor-ref>
</action>
</struts>
<!--EndFragment-->