struts2自定义拦截器类

这篇博客介绍一下自定义拦截器类的两种实现方法,并使用其中一种方法给出一个实现文字过滤的例子

实现自定义拦截器类有两种方法

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值