下面开发一个自己的拦截器
1.编写拦截器类
public interface Interceptor extends Serializable {
/**
* Called to let an interceptor clean up any resources it has allocated.
*/
void destroy();
/**
* Called after an interceptor is created, but before any requests are processed using
* {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving
* the Interceptor a chance to initialize any needed resources.
*/
void init();
/**
* Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the
* request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code.
*
* @param invocation the action invocation
* @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself.
* @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}.
*/
String intercept(ActionInvocation invocation) throws Exception;
}
上面是拦截器的接口 初始化 拦截 销毁
自己写的拦截器类使用的是抽象的拦截器类继承的方法,仅仅需要实现一个方法就成了
public class SimpleInterceptor extends AbstractInterceptor {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String intercept(ActionInvocation arg0) throws Exception {
// TODO Auto-generated method stub
System.out.println("before");
String result=arg0.invoke();
if(arg0.isExecuted())
{
System.out.println("isexcuted");
}
System.out.println("after");
return result;
}
}
目的:为的是测试执行前后的拦截效果,,invoke就执行了
2.写简单的Action
package org.actions;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
}
什么也没有
3.写配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
<constant name="struts.devMode" value="false" />
<constant name="struts.i18n.encoding" value="GBK"/>
<package name="actions" extends="struts-default" namespace="/actions">
<interceptors>
<interceptor name="mysimple" class="org.interceptor.SimpleInterceptor">
<param name="name" >拦截器</param>
</interceptor>
</interceptors>
<action name="user" class="org.actions.TestAction">
<result >/success.jsp</result>
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="mysimple"/>
</action>
</package>
</struts>
4.网页--略过了,,可以观察到下面的效果
before
isexcuted
after