Daily quotes

In the affairs of life or of business, it is not intellect that tells so much as character, not mind so much as heart, not genius so much as self-control, patience, and discipline, regulated by judgment. — From Hemingway

.

Although Spring MVC has sometimes involved configuring containers in the past, most students will see this as an operation or testing job, as long as it works, as long as their code runs. Actually, know more about the role of the principle is not only in order to complete the task, it can help you more positive to think about the principle of code to run, improve your thinking structure, because you used to know the why, whether you do after requirement analysis, architecture design, module refactoring optimization, performance tuning and so on, there will be a lot of help. This chapter covers simple and common container configuration changes. SSL support has become more and more important in recent years.

In actual combat

Servlet Container Configuration

In addition to automatic configuration, Spring Boot also integrates common Web containers into automatic configuration, so that users can build Web projects more quickly and achieve their business goals quickly. What is a container? In this case, the program that supports Java programs to run. This section only expands on the Tomcat configuration in detail, but is general for Jetty and Undertow, as mentioned below.

1- Configuration file configures Tomcat

Before us in the configuration section describes how to view the configuration of the definition, here, we can also in org. Springframework. Boot. Autoconfigure. Found in web ServerProperties, gm of servlet universal configuration is defined here, Tomcat is prefixed with “server”, whereas Tomcat, which is the default built-in container, is configured with server.tomcat as the prefix. Here are some examples:

/ / servlet container
server.port=9090# listen on port8080Server. context-path= # Access path, default is /Copy the code
/ / configure tomcatServer.tomcat. uri-encoding= # Tomcat encoding, which is UTF- by default8Server. Tomcat. Accesslog. Directory = # access log, the default for the logsCopy the code

The above is a brief description. For detailed configuration, you can enter server or server.tomcat in application.

2- Code to configure Tomcat

Spring Boot automatic configuration has a feature that allows you to modify the configuration through code, which makes it easy to change the configuration, and we only need to implement the interface defined by Spring Boot. Here, we need to register an implementation of a EmbeddedServletContainerCustomizer Bean. If the container is configured directly, it can be implemented using the corresponding factory class, which is as follows:

Tomcat   ---> TomcatEmbeddedServletContainerFactory
Jetty    ---> JettyEmbeddedServletContainerFactory
Undertow ---> UndertowEmbeddedServletContainerFactory
Copy the code

Common configuration

Create a public server configuration that can be modified:

package com.hjf.boot.demo.boot_ssl.config;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;

public class CustomerServlet implements EmbeddedServletContainerCustomizer {

    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
        configurableEmbeddedServletContainer.setPort(9090); / / 1
        configurableEmbeddedServletContainer.setContextPath("/test"); / / 2}}Copy the code

Note: 1: modifying the listening port 2: modifying the access path is similar to modifying the configuration file.

Special configuration

Add configuration classes and register beans

@Configuration
public class ServletConfig {}Copy the code

Tomcat configuration

@Bean
    public EmbeddedServletContainerFactory servletContainer(a){
        TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
        factory.setPort(9999);
        factory.setContextPath("/test");
        return factory;
    }
Copy the code

Jetty configuration

@Bean
    public EmbeddedServletContainerFactory servletContainer(a){
        JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();
        factory.setPort(9999);
        factory.setContextPath("/test");
        return factory;
    }
Copy the code

Undertow configuration

@Bean
    public EmbeddedServletContainerFactory servletContainer(a){
        UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
        factory.setPort(9999);
        factory.setContextPath("/test");
        return factory;
    }
Copy the code

Note: only one container can be configured for a project, do not register multiple containers repeatedly.

Replace the embedded container

Spring Boot uses Tomcat as the Servlet container by default. We can configure another container above, so we need to exclude Tomcat as the corresponding container:

Use the Jetty

Modify the following in pom.xml:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starte-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
    </dependencies>
Copy the code

Use the Undertow

Modify the following in pom.xml:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starte-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
    </dependencies>
Copy the code

Using SSL

What is SSL? Secure Sockets Layer (SSL) and its successor, Transport Layer Security (TLS), is a Security protocol that provides Security and data integrity for network communications. TLS and SSL encrypt network connections at the transport layer.

SSL is located between TCP/IP and various application-layer protocols and provides security support for data communication. The SSL Protocol is divided into two layers: SSL Record Protocol (SSL Record Protocol) : Based on reliable transport protocols (such as TCP), it supports basic functions such as data encapsulation, compression, and encryption for high-level protocols. SSL Handshake Protocol: Based on the SSL recording Protocol, it is used for identity authentication, encryption algorithm negotiation, and encryption key exchange between communication parties before data transmission.

Use SSL is usually two steps, first, to generate valid certificate, let you of the HTTP links have a foundation, the certificate is self-signed and can also be obtained from the SSL certificate authority center, general big site is authorized, for example, baidu, jingdong, etc., also has not authorized, such as: 12306, but doesn’t affect the use; Second, configure SSL in the Web container to enable SSL to take effect.

Generate a certificate

1, First find the Java JDK you are using, in the bin folder to find the tool keytool, if you set Java environment variables, directly from the command line (Windows and Linux are the same) :

keytool -genkey -alias mickjoust -keyalg RSA  //1
Copy the code

Description:

1: If the algorithm format is not specified, the old encryption format will be used. Containers with older versions will report errors that are not supported by the security format.

This generates a.keystore, which is the certificate file.

Configure SSL

Configuring SSL in Spring Boot is very simple, also under application.properties:

server.port=8443 //1 #server.session.timeout= #server.context-path= server.tomcat.uri-encoding=UTF-8 There was now no pression = # # server.tomcat.com the new server. The SSL. Key - store =. Keystore / / 2 server SSL. The key store password = 123456 / / 3 server.ssl.key-store-type=JKS //4 server.ssl.key-alias=mickjoust //5Copy the code

Note: 1: specifies the listening port. 2: specifies the name of the SSL storage file. 3: specifies the certificate password

Use code to configure HTTP to automatically jump to HTTPS

SSL is configured on the above, the only support SSL, that is to say, when you enter the same url with HTTPS, can access, but sometimes we used to just enter the url, the browser default is to use HTTP, we hope to be able to automatically jump at this moment, in order to achieve this function, we need to configure the container to the automatic redirection function. Using Tomcat as an example, Jetty is similar to Undertow and needs to check the corresponding documentation.

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class Http2HttpsConfig {

    @Bean
    public EmbeddedServletContainerFactory servletContainer(a) {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(){/ / 1
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/ *"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); }}; tomcat.addAdditionalTomcatConnectors(httpConnector());return tomcat;
    }

    @Bean
    public Connector httpConnector(a){/ / 2
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(9090);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        returnconnector; }}Copy the code

Note: 1: Overrides context Settings to add paths and security sets. 2: Create an HttpConnector for use.

Successful startup. See HTTPS port

Run the localhost:9090 test

Automatically jump to HTTPS

It is better to use Tomcat directly. Of course, if you use a certain method, there will be some sacrifice of a certain method. In this case, tomcat is configured by code, and usually we manually operate tomcat XML configuration, which is also mentioned above at the beginning. If you don’t have a certain amount of patience, you’re just getting things done, and you don’t know what to do with a configuration or task that’s a little bit difficult. Actually, wanted to understand a principle only, no matter what configuration is used, it is the means that achieves a goal just.

summary

This chapter introduces how to configure embedded Tomcat in Spring Boot and how to replace tomcat. It also introduces how to configure SSL in Spring Boot. The embedded configuration is done in code, which is different from the SSL configuration in common containers. I’m not going to cover anything like how Tomcat configures SSL. This chapter is relatively simple, which is the end of configuration. In fact, there are many Spring Boot configurations, which need to be experienced when using them.


Example address: boot-ssl


page 174 of 366 in chapter 2016