This blog is only a brief description of how to use, there will not be too deep analysis, I think a thing to be used first and then to learn the underlying principle, it will be more smooth.

configuration

Spring Boot uses Tomcat as an embedded Servlet container by default;

1. How do I customize and modify the configuration of the Servlet container?

1) Modify the propertis/ yML configuration file:

  • The sample
server.port=8080 server.tomcat.uri-encoding=UTF-8 ... .Copy the code

2) Code implementation

package com.carson.springboot.config;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyServerConfig {

    // Configure the servlet container
    @Bean
    public ConfigurableServletWebServerFactory configurableServletWebServerFactory(a){
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.setPort(8080);
        returnfactory; }}Copy the code

2. Register Servlet, Filter, and Listener components

  • Examples of Servlet code:

Create a class MyServlet that inherits HttpServlet

package com.carson.springboot.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 {

    // Process get requests

    @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"); }}Copy the code
  • Add another method from the MyServerConfig class
    // Register the three component servlets
    @Bean 
    public ServletRegistrationBean myServlet(a){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
        // MyServlet is the class I just wrote
        return registrationBean;
    }
Copy the code

Parameter description: new ServletRegistrationBean(which Servlet to pass, which path to intercept)

Verification is valid: Visit /myServlet to see the effect

You can see the contents of the output string, indicating that it has taken effect

  • Filter code example

package com.carson.springboot.filter;

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

public class MyFilter implements Filter {

    @Override / / initialization
    public void init(FilterConfig filterConfig) throws ServletException {}@Override / / filter
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("MyFilter RUN!!!!");
        filterChain.doFilter(servletRequest,servletResponse);
    }

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

Import javax.servlet.*; import javax.servlet. The Filter bag

I’m not going to write initialization and destruction, I’m just going to write runtime

  • Go back to the MyServerConfig class

Add the following code

 // 2. Register Filter
    @Bean
    public FilterRegistrationBean myFilter(a){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        // Set a Filter to the class I just defined
        filterRegistrationBean.setFilter(new MyFilter());
        // Set interception path (multiple paths can be set)
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/hello"."/myServlet"));
        return filterRegistrationBean;
    }
Copy the code

SetUrlPatterns requires a collection to be passed in by default, which I converted to an array

Try it out:

Visit http://localhost:8080/hello or http://localhost:8080/myServlet:

View the IDEA console at 👇

MyFilter RUN!!!! is printed DoFilter is executed.

  • Listener

Write a MyListener class:

package com.carson.springboot.listener;

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

public class MyListener implements ServletContextListener{

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("contextInitialized.. Web application startup");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("contextDestroyed.. Current Web project destruction"); }}Copy the code

To register (again, the MyServerConfig class):

Register the listener
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean(a){
        ServletListenerRegistrationBean mylistener = new ServletListenerRegistrationBean(new MyListener());
        return mylistener;
    }
Copy the code

Test:

  1. Start the project

We saw the boot

Let’s try destroying it again

Attention!!!!!! : Destruction here can not be directly pressed:

Press this and you won’t see the destruction string

Should press here:

Seeing the destruction indicates that my listener executed properly


When Spring Boot helps us automatically configure SpringMVC, it also helps us configure the front-end controller DispatcherServlet

The basic configuration principles are not too different from the three components, so I won’t go into details here


How do I use other Servlet containers?

In addition to Tomcat(the default), Spring Boot also supports:

  • Jetty (suitable for long time connection)
  • Undertow (no JSP support)

These two containers

To use another container, you need to get rid of Tomcat first!

Press CTRL + Alt + Shift + U in the POM. XML file to open the dependency web

Or right click 👇

Elimination method

Then add jetty’s dependencies:

 <! -- Introducing additional servlet containers -->
        <dependency>
            <artifactId>spring-boot-starter-jetty</artifactId>
            <groupId>org.springframework.boot</groupId>
        </dependency>
Copy the code

Modify the code in the MyServerConfig class:

// Configure the servlet container
    @Bean
    public ConfigurableServletWebServerFactory configurableServletWebServerFactory(a){
        //TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        JettyServletWebServerFactory jettyServletWebServerFactory = new JettyServletWebServerFactory();
        jettyServletWebServerFactory.setPort(9192);
       // factory.setPort(8080);
        return jettyServletWebServerFactory;
    }
Copy the code

As you can see from the name one is Tomcat and the other is Jetty

Run the program:

I found that the port number is the one I just set and the three components are still in effect

Even if switching Undertow is the same process, here I will write the code to have a look, so as not to go through again:

        UndertowServletWebServerFactory undertowServletWebServerFactory = new UndertowServletWebServerFactory();
        undertowServletWebServerFactory.setPort(8080);
Copy the code

I’m going to switch to another container, and I’m going to switch back to Tomcat in case anything goes wrong, because I wrote it based on Tomcat in the first place, right