struts2 文字过滤拦截器

来源:互联网 发布:C语言下列叙述错误的是 编辑:程序博客网 时间:2024/06/02 01:58

假设我拦截掉文本中的“脑残”二字

MyInterceptor类 该类为文字拦截器类
该类继承AbstractInterceptor

package com.xxx.interceptor;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;import com.xxx.action.PublicAction;public class MyInterceptor extends AbstractInterceptor {    @Override    public String intercept(ActionInvocation ai) throws Exception {        //获取action实例          Object obj = ai.getAction();          if(obj!=null){              if(obj instanceof PublicAction){                  PublicAction action = (PublicAction)obj;                  String content = action.getContent();                    System.out.println("intercept方法,修改前[content]="+content);                if(content.contains("脑残")){                      content = content.replaceAll("脑残", "*");                      System.out.println("intercept方法,修改后[content]="+content);                    action.setContent(content);                  }                  return ai.invoke();              }else{                  return Action.LOGIN;              }               }else{              return Action.LOGIN;          }      }}

文本输入html页面
提交后也跳转到这页面看看数据

<%@taglib prefix="s" uri="/struts-tags"%>....<body>    <form action="public" method="post">        <p>            文本内容: <input type="text" name="content" />        </p>        <input type="submit" value="提交">    </form>    <p>        测试过滤后的文本:        <s:property value="content" />    </p></body>

com.xxx.action包下的PublicAction类

package com.xxx.action;import com.opensymphony.xwork2.ActionSupport;public class PublicAction extends ActionSupport {    private String content;//文字内容    /**忽略content属性的setXxx()和getXxx()方法 */    @Override    public String execute() throws Exception {        System.out.println("execute()方法[content=]"+content);        return SUCCESS;    }}

struts.xml配置

<struts>    <package name="xuexi" namespace="/" extends="struts-default">        <!-- 定义拦截器 -->        <interceptors>            <interceptor name="replace" class="com.xxx.interceptor.MyInterceptor" />        </interceptors>        <action name="public" class="com.xxx.action.PublicAction">            <result name="success">/NewFile1.jsp</result>            <result name="login">/NewFile1.jsp</result>            <!-- 使用拦截器 -->            <interceptor-ref name="defaultStack" />            <interceptor-ref name="replace" />        </action>    </package></struts>  

以上都配置好后 完成咯~
看得出 HTML数据→拦截器→(过滤)→Action

这里写图片描述

原创粉丝点击