Filter interface in servlet (filter interface)

I introduce

(1) It comes from the interface under Servlet specification and exists in Servlet API in Tomcat Jar package

(2) The developer is responsible for providing the Filter interface implementation class, but the Http server is not responsible for providing it

(3) The Filter interface intercepts the Http server before calling the resource file

II Specific role

1. Intercept the Http server and help the Http server detect the legitimacy of the current request

2. Intercept the Http server and enhance the current request

III Development steps of Filter interface implementation class

There are three development steps:

(1) Create a Java class to implement the Filter interface

(2) Rewrite the doFilter method in the Filter interface to complete the functions we want to implement.

(3)web.xml registers the filter interface implementation class to the Http server (here we are Tomcat), and can be set to inform our Tomcat that we need to use our filter class to intercept before calling what resource file.

IV Filter intercept address format

(1) Command format:

First, register our Filter interface implementation class to our tomcat container

         <!--Give the filter class file path to Tomcat-->
          <filter>
              <filter-name>oneFilter</filter-name>
              <filter-class>com.bjpowernode.filter.OneFilter</filter-class>
          </filter>
          <!--notice Tomcat What resource files need to be intercepted by the current filter when calling-->
          <filter-mapping>
              <filter-name>oneFilter</filter-name>
              <url-pattern>The path you want to intercept</url-pattern>
          </filter-mapping>

First use filter to register our filter interface implementation class to our tomcat, and then use filter mapping to specify which resource file our filter class registered to Tomcat needs to intercept.

(2) Let's introduce which interception paths can be put in < URL pattern >, assuming that the filter class we set at this time is OneFilter

Tomcat is required to call OneFilter interception before calling a specific file
                       <url-pattern>/img/mm.jpg</url-pattern>

Tomcat is required to call OneFilter interception before calling all resource files under a folder
                        <url-pattern>/img/*</url-pattern>

Tomcat is required to call OneFilter interception before calling a certain type of file under any folder
                        <url-pattern>*.jpg</url-pattern>

Tomcat is required to call OneFilter to intercept when calling any file in the website
                        <url-pattern>/*</url-pattern>

Tomcat is required to call OneFilter to intercept when calling a dynamic resource file (servlet implementation class) in the website

< URL pattern > / request resource alias < / url pattern > note: the request resource alias here refers to our website The request alias set by XML when accessing a servlet implementation class.

 

When we enter in the website http://localhost:8080/ Website name / resource file to be intercepted / this path will be intercepted first, and then access our resource file.

V code implementation

Code logic: when users log in at the front desk, they will enter their own name and password. After clicking submit, a Filter interface implementation class is needed to verify whether the name and password we enter are the same as our previously registered account and password. If they are the same, we will continue to access the address we want to access after clicking submit, Suppose that after clicking submit at this time, the access address of the browser is http://localhost:8080/myweb/one

1: First, we write a front-end page: we need to put the code of our login page in it, and specify the address we want to visit after submission in action.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login interface</title>
</head>
<body>
<form action="/myweb/one">
    User name:<input type="text" name="username" />
    User password:<input type="password" name="password"/>
    Submit button:<input type="submit" value="Submit">
</form>

</body>
</html>

2: Then write our Filter interface implementation class: suppose the name we registered before this time is Wang Wu and the password is 123.

public class OneFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        String name=servletRequest.getParameter("username");
        String password=servletRequest.getParameter("password");
        if(name.equals("Wang Wu")&&password.equals("123")){
            //Return the intercepted request object and response object to tomcat, and Tomcat will continue to call the resource file
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            servletResponse.setContentType("text/html;charset=utf-8");
            PrintWriter printWriter=servletResponse.getWriter();
            printWriter.print("Please re-enter");
        }
    }

    @Override
    public void destroy() {

    }
}

Note: after the verification in the if statement is successful, we need to return our intercepting request object and response object to tomcat, and Tomcat will continue to call the resource file. Therefore, at this time, we need our Filter chain object filterChain to call the doFilter method, and return the intercepting request object and response object to Tomcat. Note that the doFilter method called by filterChain is its own, It is not the doFilter method in the Filter interface class, as shown in the following figure:

We generally call this return action release.

If the name and password entered by the foreground user are incorrect, the user will be reminded to re-enter. At this time, our filter will reject the request instead of Http server

3: After writing our filter interface implementation class OneFilter, write our OneServlet interface implementation class. This class is the dynamic resource file that users continue to access after successful verification.

public class OneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name=req.getParameter("username");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter=resp.getWriter();
        printWriter.print("The user's name is"+name);
        System.out.println();
        printWriter.print("The user's password is entered correctly");
        printWriter.flush();
    }
}

After the user name is verified to be correct, the password can be displayed here.

4: Finally, on the web XML file for our configuration

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>onefilter</filter-name>
        <filter-class>com.bjpowernode.Filter.OneFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>onefilter</filter-name>
        <url-pattern>/one</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>OneServlet</servlet-name>
        <servlet-class>com.bjpowernode.controller.OneServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>OneServlet</servlet-name>
        <url-pattern>/one</url-pattern>
    </servlet-mapping>
</web-app>

Note: < URL pattern > in < filer mapping > should be filled in the resource path we want to intercept, because we want to verify when accessing OneServlet, so we can fill in our request alias / one here.

Keywords: Java servlet filter

Added by solaris77 on Mon, 31 Jan 2022 07:51:45 +0200