现在的位置: 首页 > 综合 > 正文

过滤掉有害字符放哪里好呢?

2018年04月27日 ⁄ 综合 ⁄ 共 9478字 ⁄ 字号 评论关闭
先做一个配置文件,支持正则表达式哦,注意定义是输入时代替还是输出时代替,还是另的什么:

java代码: 

<?xml version="1.0" encoding="GBK"?>
<sentences>
        <sentence>
                <srcWord>(S|s)(C|c)(R|r)(I|i)(P|p)(T|t)</srcWord>
                <destWord>script</destWord>
                <flow>in</flow>
        </sentence>
        <sentence>
                <srcWord>法.轮.功</srcWord>
                <destWord> *** </destWord>
                <flow>in</flow>
        </sentence>

       <!-- 以下为系统解决回符问题 -->
        <sentence>
                <srcWord>/r/n</srcWord>
                <destWord>&br&</destWord>
                <flow>out</flow>
        </sentence>
</sentences>

做个STRUTS插件,这样重用性就很好了.

java代码: 

package iclass.plugin;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import javax.servlet.ServletException;

import iclass.filtrate.BeanFiltrate;

/**
* struts插件
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/

public class InitFiltrate implements PlugIn {

    private static BeanFiltrate beanFiltrate = new BeanFiltrate();
    private String fileName;
    /**
     *
     * @param servlet ActionServlet
     * @param config ModuleConfig
     * @throws ServletException
     */

    public void init(ActionServlet servlet, ModuleConfig config) throws
            ServletException {
        try {
            String realFileName = servlet.getServletContext().getRealPath(
                    fileName);
            beanFiltrate.setFileName(realFileName);
        } catch (Exception ex) {
            throw new ServletException("初始化PlugIn出错! " + ex);
        }

    }

    /**
     *
     */

    public void destroy() {
         beanFiltrate = null;
    }

    /**
     *
     * @return BeanFiltrate
     */

    public static BeanFiltrate getBeanFiltrate() {
        return beanFiltrate;
    }

    /**
     *
     * @param fileName String
     */

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

}

又是性能问题呀,过滤的字串一般不会很多,放到内存中去吧,少不得搞个cache.搞个静态变量.每次服务启动一次时,保证只会读一次硬盘.

java代码: 

package iclass.filtrate;

import java.util.Collection;
import java.util.Vector;
import java.util.Iterator;
import java.io.File;

public class Filtrate {

  private static Collection collection=new Vector();
  private static String fileName;

  /**
   * 初始化
   */

  private void init()throws Exception{
    if (collection.isEmpty()) {
      Sentences sentences = new SentenceParse().getSentences(fileName);
      collection = sentences.getSentences();
    }
}

  /**
   * 输入时过滤, 清除有害信息
   * @param message String
   * @return String
   */

  public String inExchange(String message) throws Exception {
    init();

    Iterator iterator = collection.iterator();
    message = message.replaceAll("  ", " ");//两个半角空格改为一个全角空格
    while (iterator.hasNext()) {
      Sentence sentence = (Sentence) iterator.next();
      if(sentence.getFlow()!=null&&sentence.getFlow().equalsIgnoreCase("in"))
        message = message.replaceAll(sentence.getSrcWord(), sentence.getDestWord());
      }
    return message;
  }
  /**
   * 输出时过滤, 解决回符在网页上µ奈侍â
   * @param message String
   * @throws Exception
   * @return String
   */

  public String outExchange(String message) throws Exception {
    init();
    Iterator iterator = collection.iterator();
    while (iterator.hasNext()) {
      Sentence sentence = (Sentence) iterator.next();
      if(sentence.getFlow()!=null&&sentence.getFlow().equalsIgnoreCase("out"))
         message = message.replaceAll(sentence.getSrcWord(), sentence.getDestWord());
    }
    return message;
  }
  /**
   * 修改时过滤,解决回符在网页修改框里µ奈侍â
   * @param message String
   * @throws Exception
   * @return String
   */

  public String updateExchange(String message) throws Exception {
    if(message!=null){
      message = message.replaceAll("<br>", "/r/n");
    }
    else message="";
    return message;
  }

  /**
   *
   * @return Collection
   */

  public Collection getCollection() {
    return collection;
  }

  /**
   *
   * @return Collection
   */

  public void clearCollection() {
    collection.clear();
  }

  /**
   *
   * @param fileName String
   */

  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

}

用起来不爽吧.如果有一个类,有N个属性,可不能一个一个地get取出来,变换后再set吧.用类的反射机制搞一下吧.

java代码: 

package iclass.filtrate;

import java.util.*;

import org.apache.commons.beanutils.*;

/**
* <p>Title: 利用类反射机制,对BEAN的所有属性进行过滤</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2004</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/

public class BeanFiltrate extends Filtrate {
    /**
     * state状态: in out update
     * @param bean Object
     * @param state String
     */

    public void filtrate(Object bean, String state) throws Exception {

        //把class的属性放到MAP中
        Map map = BeanUtils.describe(bean);

        Iterator keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String newValue = "";
            //取得MAP的KEY, 在MAP中自动为String
            String key = (String) keys.next();

            //取得MAP的值, 在MAP中自动为String
            String value = (String) map.get(key);

            //取得MAP的KEY所对应的class的属性类型
            Object object = PropertyUtils.getProperty(bean, key);
            if (object != null) {
                String property = object.getClass().getName();
                //如果是日期,则从MAPÖ泄说ô

                if (property.equals("java.util.Date")||property.equals("java.sql.Date")||property.equals("java.sql.Time")||property.equals("java.sql.Timestamp")) {
                    //iterator中 利用Map或者CollectionÀ瓷境谌Ý是不合法的
                    //map.remove(key);
                    keys.remove();

                }
                //如果是字串型,开始过滤
                if (property.equals("java.lang.String")) {
                    if (value != null) {
                        if (state.equalsIgnoreCase("in")) {
                            newValue = super.inExchange(value);
                        }
                        if (state.equalsIgnoreCase("out")) {
                            newValue = super.outExchange(value);
                        }
                        if (state.equalsIgnoreCase("update")) {
                            newValue = super.updateExchange(value);
                        }
                        map.put(key, newValue);
                    }
                }
            }
        }
        BeanUtils.populate(bean, map);

    }

}


可以这样调用了

java代码: 

package count.web;

import java.util.*;

import javax.servlet.http.*;

import common.spring.web.*;
import iclass.page.*;
import iclass.plugin.*;
import count.pojo.*;
import org.apache.commons.beanutils.*;
import org.apache.log4j.*;
import org.apache.struts.action.*;

/**
* <p>Title: 注册需要计数的程序名到计数器数据库</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author 段洪杰
* @version 1.0
*/

public class AppAction extends BaseAction {

    private static Logger log = Logger.getLogger(AppAction.class);
    private int rowsPerPage = 20; //分页时,显示的每页行数

    /**
     * 初始化 service
     * @param actionServlet ActionServlet
     */

    public void setServlet(ActionServlet actionServlet) {
        super.setServlet(actionServlet);
    }

    /**
     * 数据录入
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws Exception
     */

    public ActionForward set(ActionMapping mapping,
                             ActionForm form,
                             HttpServletRequest request,
                             HttpServletResponse response) throws
            Exception {

        AppForm appForm = (AppForm) form;

        appForm.setCreateDate(new Date());
        App app = new App();
        PropertyUtils.copyProperties(app, appForm);
        //输入时,对app的信息进行过滤
        InitFiltrate.getBeanFiltrate().filtrate(app, "in");
        getCountService().setApp(app);

        request.setAttribute("message", "信息录入完成!");
        request.setAttribute("locationFile",
                             "<A HREF=/"javascript:history.back()/">返回</A>");
        return (mapping.findForward("message"));
    }

    /**
     * 查看一条记录
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws Exception
     */

    public ActionForward view(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws
            Exception {

        String id = request.getParameter("id");
        App app = (App) getCountService().getAppById(id);

        //输出时,对app的信息进行过滤
        InitFiltrate.getBeanFiltrate().filtrate(app, "out");
        request.setAttribute("app", app);
        return (mapping.findForward("view"));
    }

    /**
     * 删除一条记录
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws Exception
     */

    public ActionForward remove(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws
            Exception {
        String url = request.getHeader("Referer");
        if (url == null || url.equals("")) {
            url = "javascript:history.back()";
        }
        //取得用户注册名
        SessionBean sessionBean = (SessionBean) request.getSession().
                                  getAttribute("sessionBean");
        String registerName = sessionBean.getRegisterName();

        String id = request.getParameter("id");
        getCountService().removeAppById(id);
        request.setAttribute("message", "信息删除完成!");
        request.setAttribute("locationFile", "<A HREF=/"" + url + "/">返回</A>");
        return (mapping.findForward("message"));

    }

    /**
     * 按用户注册名分页显示所有内容
     * @param mapping ActionMapping
     * @param form ActionForm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return ActionForward
     * @throws Exception
     */

    public ActionForward list(ActionMapping mapping,
                                            ActionForm form,
                                            HttpServletRequest request,
                                            HttpServletResponse response) throws
            Exception {

        //分页控制
        PageControl pageControl = null;
        //取得的集合
        Iterator apps = null;
        //总记录数,当前页
        int maxRowCount, curPage;
        //得当前页号
        String currentpage = request.getParameter("currentpage");

        //实例化DAO
        if (currentpage == null) {
            //当前页设为1
            curPage = 1;
        } else {
            //把取得的参数转为整型
            curPage = Integer.parseInt(currentpage);
        }
        //计算记录总数
        maxRowCount = getCountService().getAppsCount();
        //分页控制类
        pageControl = PageControlFactory.getPageControlLink("AppAction.do",
                "method=listByRegisterName", maxRowCount, curPage, rowsPerPage);
        apps = getCountService().getApps(pageControl.getPosition(), this.rowsPerPage);

        request.setAttribute("pageControl", pageControl);
        request.setAttribute("apps", apps);
        return (mapping.findForward("list"));
    }
}

抱歉!评论已关闭.