How to use the three major components of Servlet in SpringBoot [Servlet, Filter, Listener]

This article mainly explains the use of the three major components of Servlet in SpringBoot, which has a certain reference learning value for everyone's study or work. Friends who need it, let's learn and learn together with the editor!

The role of the three major components

1、Servlet

Servlet is a dynamic resource used to process client requests, that is, when we type an address in the browser and press Enter to jump, the request will be sent to the corresponding Servlet for processing.
The tasks of Servlet are:

1. Receiving request data: We all know that the client request will be encapsulated into an HttpServletRequest object, which contains various information such as request headers and parameters.
2. Processing request: Usually we will receive parameters in the service, doPost or doGet method, and call the service layer (service) method to process the request.
3. Complete response: After processing the request, we generally forward or redirect to a page. Forwarding is the method in HttpServletRequest, and redirection is the method in HttpServletResponse. There is a big difference between the two of.

HttpServlet

Indirectly implements the Servlet interface. When a Servlet is implemented by inheriting HttpServlet, we only need to rewrite different methods according to the type of processing request (method value), handle get requests, rewrite doGet requests; handle post requests, rewrite doPost request.

2、Filter

In the process from the client to the server, when a request is sent, if there is non-compliant information, it will be intercepted by the filter. If it is met, it will be released. When the server responds to the client, it will also be judged if there is a non-compliant information. The information will be intercepted by the filter, and will be released if it meets the requirements.

What is oop? (expand)

Object-oriented programming, java is object-oriented transformation, encapsulation, inheritance, multiple and abstraction.

What is aop? (Extension)

Aspect-oriented programming. Used to filter requests. Filter the request before it reaches the servlet.

It is a new function introduced after version 2.3 of Sun's srvlet. There is no such function in the version before 2.3. To define a filter, you need to implement the Filter interface, which is implemented here is javax.servlet.Filter.

The life cycle of the filter:

When the project starts, the filter starts to initialize. When a request comes, it starts to execute the doFilter method automatically, and the filter starts to stop when the project is closed.

3、Listener

Listener is the listener. When we develop in JavaSE or Android, we often add a listener to the button. When the button is clicked, the listener event will be triggered and the onClick method is called, which is essentially a method callback. The Listener in JavaWeb is the same principle, but it monitors different content. It can monitor Application, Session, and Request objects. When these objects change, it will call the corresponding monitoring method.

Listener: equivalent to the event learned before.
Source: who is listening.
Action: trigger condition.
Response: function that will be executed when the condition is met.

ServletContext object:
life cycle: it is created when the project is started, and destroyed when the project is closed.
The life cycle can be understood as: listener>filter>servlet

Code example

When we don't use the springboot project, we want to use these functions in web.xml. By default, SpringBoot starts the embedded Servlet container in the jar package to start the SpringBoot web application. There is no web.xml file.
Here I directly demonstrate to you through a small demo and show the effect

1. Import dependencies

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
</dependencies>

2. Create a Listener (create a class to implement the ServletContextListener interface)

package com.gzl.cn.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {
    
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
    
    
        System.out.println("contextInitialized...web应用启动");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    
    
        System.out.println("contextDestroyed...当前web项目销毁");
    }
}

3. Create a servlet (create a class to implement the HttpServlet interface)

package com.gzl.cn.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyServlet extends HttpServlet {
    
    

    //处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        resp.getWriter().write("Hello MyServlet");
    }
}

4. Create a filter (create a class to implement the filter interface)

package com.gzl.cn.filter;

import javax.servlet.*;
import java.io.IOException;

public class MyFilter implements Filter {
    
    

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    
        System.out.println("MyFilter process...");
        chain.doFilter(request,response);

    }

    @Override
    public void destroy() {
    
    

    }
}

5. Create a configuration class

Register the three major components in the following way and inject them into the container to take effect.

package com.gzl.cn.config;

import java.util.Arrays;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.gzl.cn.filter.MyFilter;
import com.gzl.cn.listener.MyListener;
import com.gzl.cn.servlet.MyServlet;

@Configuration
public class MyServerConfig {
    
    

    //注册三大组件
    @Bean
    public ServletRegistrationBean myServlet(){
    
    
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean myFilter(){
    
    
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());
        registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return registrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
    
    
        ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return registrationBean;
    }

}

6. Test results

When the project started, the Listener listened to it and printed out the log

The path we configured in our configuration class is to access myServlet to trigger the filter and servlet,
so here we directly access http://localhost:8080/myServlet

The filter prints out when visiting

Guess you like

Origin blog.csdn.net/weixin_43888891/article/details/112550155