Filter usage scenario: sensitive word filtering


Case description: on the index.jsp page, submit a paragraph of text through the form, jump to Servlet01, but before jump to Servlet01, the request will be given to the filter encoding filter, sensitive word filter, and then jump to Servlet01, and print out the text submitted after filtering on the console.

-index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <form action="test" method="post">
      <textarea name="txt">

      </textarea>
      <input type="submit" value="Send out">

    </form>
  </body>
</html>

  • Encoding filter
@WebFilter("/*")
public class EncodingFilter implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //Unified solution to the problem of garbled code

        //1.Solve the Chinese code confusion of the response
        response.setContentType("text/html;charset=utf-8");
        //2.To solve the Chinese scrambling of the request: post mode
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            request.setCharacterEncoding("utf-8");
        }
        //3.Release request
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }
}

  • Sensitive word filter
@WebFilter(filterName="SensitiveWordFilter", urlPatterns="/*")
public class SensitiveWordFilter implements Filter {
    private List<String> list=new ArrayList<>();

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest= (HttpServletRequest) req;
        Myreq myreq = new Myreq(httpServletRequest,list);
        chain.doFilter(myreq, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        ServletContext servletContext = config.getServletContext();
        InputStreamReader inputStreamReader = null;
        InputStream resourceAsStream=null;
        BufferedReader bufferedReader=null;
        try {
            resourceAsStream = servletContext.getResourceAsStream("file/sensitiveWords.txt");
            //InputStreamReader: Convert InputStream to Reader
            inputStreamReader = new InputStreamReader(resourceAsStream,"UTF-8");
            //Create a buffer flow object: it is a processing flow and a node flow(FileReader)Packaging
             bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                list.add(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(resourceAsStream!=null){
                    resourceAsStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

//Decoration mode
/*
  Create a decoration class to enhance the getParameter method of request: get the string after replacing sensitive words

  HttpServletRequestWrapper Class is the decoration class of HttpServletRequest, which does not directly enhance any method of HttpServletRequest,
  We create a class that inherits HttpServletRequestWrapper and rewrites the method we want to enhance (for example, getParameter here, to make this method more functional).
  Then we create the object of this class, pass it to Servlet in chain.doFilter(myreq, resp), and call getParameter is our overridden method.

 */
class Myreq extends HttpServletRequestWrapper {

    private HttpServletRequest httpServletRequest;
    private List<String> list=new ArrayList<>();


//    public Myreq(HttpServletRequest request) {
//        super(request);
          //Assign request to decorated object
//        httpServletRequest=request;
//    }

    //
    public Myreq(HttpServletRequest request,List list) {
        super(request);
        httpServletRequest=request;
        this.list=list;
    }

    @Override
    public String getParameter(String name) {
        String txt = httpServletRequest.getParameter(name);
        //When txt is not empty
        if(txt!=null&&!txt.isEmpty()){
            //Cycle each sensitive word separately
            for (int i = 0; i <list.size() ; i++) {

                //If the sensitive word of this loop is found in txt, it will be replaced with "* *", otherwise, the replacement method will not be executed
                if(txt.indexOf(list.get(i))!=-1) {
                    txt=txt.replaceAll(list.get(i), "**");
                }

                //It can also be replaced directly
               // txt = txt.replace(list.get(i), "**");
            }
        }
        return txt;
    }
}

/*
1.replace Brief introduction with replaceAll: replace and replaceAll are common methods of replacing characters in JAVA.
replace: Replace a character or string in the source string with the specified character or string.
replaceAll: Replace a character or string in the source string with the specified character or string, based on the replacement of the rule expression.
replaceFirst: Replace only the first occurrence of the string, based on the replacement of the rule expression.
Note: the parameters used for replaceAll() and replaceFirst() are not based on regular expressions, so they have the same effect as replace() replacing strings.

2.indexOf(String str): Returns the starting index at the first occurrence of the specified string str in the method caller, or - 1 if there is no such character in the string.
 */
  • Servlet01
@WebServlet(name = "Servlet01",urlPatterns = "/test")
public class Servlet01 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String txt = request.getParameter("txt");
        System.out.println("Servlet01 Information received:"+txt);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

Test effect:

Browser input, send:

Servlet01 obtains the request message, and the console outputs:

19 original articles published, 7 praised, 427 visited
Private letter follow

Tags: JSP encoding Java

Posted on Tue, 04 Feb 2020 12:11:32 -0500 by Rojay