这篇博客介绍一下自定义拦截器类的两种实现方法,并使用其中一种方法给出一个实现文字过滤的例子
实现自定义拦截器类有两种方法
1、实现Interceptor接口
2、继承AbstractInterceptor类
Interceptor接口的声明格式如下
public interface Interceptor extends Serializable{
void destory();
void init();
String intercept (ActionInvocation invocation) throws Exception;
}
init()方法,在拦截器执行前调用,用于初始化系统资源,destory方法在执行之后销毁资源,intercept是核心方法,实现具体的拦截操作。
AbstractInterceptor类声明格式如下
public abstract class AbstractInterceptor implements Interceptor{
public void init();
public void destory();
public abstract String intercept (ActionInvocation invocation) throws Exception;
}
实例:文字过滤
register.jsp文件
注册<br>
<s:form action="reg" mothod="post">
<s:textfield name="userName" label="注册姓名" maxlength="20"></s:textfield>
<s:password name="userPassword" label="注册密码" maxlength="30"></s:password>
<s:textarea name="userInfo" cols="40" rows="5" label="个人说明"></s:textarea>
<s:submit value="提交"></s:submit>
</s:form>
myregister.jsp文件(跳转后的页面)
注册姓名:<s:property value="userName"/><br>
注册密码:<s:property value="userPassword"/><br>
个人说明:<s:property value="userInfo"/><br>
RegisterInterceptor类,(自定义的拦截器类)
public class RegisterInterceptor extends AbstractInterceptor{
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation ai) throws Exception {
Object object=ai.getAction();
if(object!=null){
if(object instanceof RegisterAction){
RegisterAction action =(RegisterAction)object;
String userInfo= action.getUserInfo();
if(userInfo.contains("坏")){
userInfo=userInfo.replace("坏", "*");
action.setUserInfo(userInfo);
}
return ai.invoke();
}else{
return Action.LOGIN;
}
}else{
return Action.LOGIN;
}
}
}
RegisterAction类(action类)
public class RegisterAction extends ActionSupport{
private String userName;
private String userPassword;
private String userInfo;
//getset方法
public String execute(){
return SUCCESS;
}
}
struts.xml文件中
<interceptors>
<interceptor name="userdefinedInterceptor"
class="wuyuhao.annotations.interceptor.RegisterInterceptor">
</interceptor>
<interceptor-stack name="replace">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="userdefinedInterceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="reg" class="wuyuhao.annotations.interceptor.RegisterAction">
<result name="success">/myRegister.jsp</result>
<result name="login">/register.jsp</result>
<interceptor-ref name="replace"></interceptor-ref>
</action>