Filter your site’s data

  • Handle Chinese garbled characters
  • Login authentication
  • .

A flowchart

  • Write a class that inherits the Filter interface (Fliter in servlet)
  • Override methods in the interface
  • How to handle REQ and RESP (filtering)
  • And here’s the thingchain.doFilter(request, response);Can’t forget
  • Configure filter in web. XML

The general shape is as follows:

public class CharacterEncodingFilter implements Filter {
    int i=0;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
         / / initialization
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          response.setCharacterEncoding("UTF8");
          request.setCharacterEncoding("UTF8");
          response.setContentType("text/html; charset=UTF-8");
          chain.doFilter(request, response);/ /!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }

    @Override
    public void destroy(a) {}}Copy the code

Write any servlet that needs filtering

public class ServletFilter extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("Chinese has been filtered.");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code

web.xml

<servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>servlet.ServletFilter</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/s/filter</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>/filter</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>f</filter-name>
    <filter-class>filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>f</filter-name>
<! -- Will filter urls ending in /s/*
    <url-pattern>/s/*</url-pattern>
  </filter-mapping>
Copy the code

Filters urls ending in /s/*

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =