Filter (function + usage)

Filter

Features:

  1. Used to intercept incoming requests and outgoing responses.
  2. Modify or process in some way the data stream being exchanged between the client and the server.

how to use?

Similar to using Servlet, Filter is an interface provided by Java WEB, and developers only need to customize a class and implement the interface.

package com.Chase.filter;
import javax.servlet.*;
import java.io.IOException;

public class MyFilter implements Filter {
 @Override
 public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws IOException, ServletException
{
 servletRequest.setCharacterEncoding("UTF-8");
 filterChain.doFilter(servletRequest,servletResponse);
 }
}

Configure filter in web.xml

<filter>
 <filter-name>my_filter</filter-name>
 <filter-class>com.Chase.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>my_filter</filter-name>
 <url-pattern>/login</url-pattern>
 <url-pattern>/test</url-pattern>
</filter-mapping>

Note: After processing the business logic in the doFilter method, you must add filterChain.doFilter(servletRequest,servletResponse);
Otherwise the request/response cannot be passed backwards and stays in the filter.

Filter life cycle

(Similar to servlet, the difference is that the servlet needs access to be initialized)

When Tomcat starts, the parameterless constructor of Filter is called to create an instantiated object through the reflection mechanism, and the init method is called to initialize it. The doFilter method is called multiple times. When the Tomcat server is shut down, destroy is called to destroy the Filter object.

No-argument constructor: Called only once, when Tomcat starts (Filter must be configured, that is, either web.xml starts, or through reflection mechanism)

init method: Called only once, when the instantiated object of Filter is created.

doFilter: Called multiple times, the business logic of accessing Filter is written in Filter

destory: called only once, called when Tomcat shuts down

Configure multiple filters at the same time. If configured in web.xml, the calling order is from top to bottom; the annotation mechanism call is uncertain.

Filter usage scenarios:

1. Unified processing of Chinese garbled characters

2. Block sensitive words

@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        String username = servletRequest.getParameter("username");
        username = username.replaceAll("sensitive word","***");
        servletRequest.setAttribute("username",username);

        filterChain.doFilter(servletRequest,servletResponse);
    }

3. Control access to resources

@WebServlet("/login")    //Login to access servlet
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username =(String) req.getAttribute("username");
        String  str_password = req.getParameter("password");
        Integer password = Integer.parseInt(str_password);
        if(username.equals("admin")&&password.equals(123123)){
            HttpSession session  = req.getSession();
            session.setAttribute("name","admin");
            resp.sendRedirect("welcome.jsp");
        }else{
            resp.sendRedirect("login.jsp");
        }
    }
}

@WebFilter("/welcome.jsp") //jsp page interception directly enters the interception page, servlet page interception needs to be intercepted through mapping
public class downloadFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession httpSession = httpServletRequest.getSession();
        String name = (String)httpSession.getAttribute("name");
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        if(name!=null){
    //If you directly access the welcome.jsp page, you need to determine whether the user name has been logged in, here it is saved with session
    //If the user name is already logged in, you can release it, and no forwarding operation is required.
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }else{
            httpServletResponse.sendRedirect("login.jsp");
        }
    }
}
Text reference online tutorial + practical operation, only for personal notes, if there is any infringement, please contact to delete

Tags: Java filter

Posted by ed01 on Sun, 22 May 2022 01:20:51 +0300