This is the first day of my participation in Gwen Challenge

1. SpringBoot profile

SpringBoot is a new framework in the Spring family that simplifies the creation and development of Spring applications. It can also be said that Spring Boot can simplify the development process of SSM(SpringMVC + Spring + MyBatis) framework.

When we used SSM framework for development, we needed to build and integrate the three frameworks. We needed to do a lot of work, such as configuring Web. XML, configuring Spring, configuring MyBatis, and integrating them together, etc. Spring Boot framework revolutionized the development process. The tedious XML configuration process is completely abandoned and the development process is simplified with a large number of default configurations.

So using Spring Boot makes it very easy and fast to create applications based on the Spring framework, which makes coding easy, deployment easy, and monitoring easy.

2. SpringBoot features

  • Ability to quickly create Spring-based applications
  • You can directly start the embedded Tomcat server using the Java Main method to run the Spring Boot program without deploying the WAR package file
  • Provide a regular starter POM to simplify Maven configuration and simplify Maven configuration
  • Automatic configuration. SpringBoot automatically configures Spring, SpringMVC, and so on according to the project’s Maven dependency configuration
  • Provides the program health check and other functions
  • You can use annotations rather than XML configuration files

My first SpringBoot project

3.1 Creating a ProjectSelect type as Spring Initializr To quickly build

3.2 Select the Spring Boot version and dependencies to create a Spring Web project

3.3 Click Finish. If the project is created for the first time, a message will be displayed in the lower right corner indicating that dependencies are being downloaded.

3.4 Project directory structure and description

  • Main.java.com.xx: Stores Java code
  • main.resources
    • Static: Stores static resources, such as images, CSS, and JavaScript
    • Templates: Stores template files for Web pages
    • Application. The properties/application. Yml: used to store programs rely on the module configuration information, such as the service configuration, database connection port, etc
3.4.1 Explain the POM. XML file

      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <! -- Inheriting a parent project of the SpringBoot framework, all self-developed SpringBoot must inherit -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>

    <! -- GAV coordinates of current project -->
    <groupId>com.mufeng</groupId>
    <artifactId>springboot-001</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>

    <! Maven project name, can be deleted -->
    <name>springboot-001</name>
    <! -- Maven project description, can be deleted -->
    <description>Demo project for Spring Boot</description>

    <! -- Maven attribute configuration, can be referenced elsewhere with ${} -->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <! --SpringBoot Framework Web projects start dependencies and automatically associate other dependencies with this dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <! --SpringBoot framework test start dependencies, such as junit tests, can be removed if not needed -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <! --SpringBoot package compiler plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Copy the code
3.4.2 Project structure description
  • The MVN | MVNW | MVNW. CMD: use scripts to perform Maven command

  • Gitignore: When using the version control tool Git, set some commits to be ignored

  • The static | templates: the page template file directory

  • Application.properties: SpringBoot configuration file where many integrated configurations can be found

    Configuration, such as: Spring, springMVC, Mybatis, Redis, etc.

  • Application. Java: Entry point for SpringBoot program execution, which executes the main method in the program, SpringBoot

    Started the

3.5 Creating a Spring Boot Controller for Spring MVC

Create SpringBootController. Java

package com.mufeng.springboot;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SpringBootController {

    @RequestMapping(value = "/springBoot/index")
    @ResponseBody
    public String index(a){
        return "Hello World!"; }}Copy the code

Note: The first created class must be in the same or lower directory as Application, otherwise SpringBoot will not load

3.6 Running the Application Class

Or right-click in the Application class and run the main method.

From the console output, you can see that starting the SpringBoot framework will start an embedded Tomcat with port number 8080 by default and context root empty:

3.7 Entering information in a Browserhttp://localhost:8080/springBoot/indexIf the following information is displayed, the configuration is successful

3.8 Project Analysis

  • Spring-boot-starter -parent is a SpringBoot parent that provides Maven default dependencies. SpringBoot programs need to inherit this parent

  • To see which default JAR package dependencies Spring Boot provides, look at the parent dependency’s POM file

  • If you don’t want to use a default dependency version, you can override each one through the attribute configuration of the POM.xml file

    Dependencies, such as overwriting Spring versions

    <properties>
        <spring-framework.version>5.0.0. RELEASE < / spring - framework. Version ></properties>
    Copy the code
  • The @SpringBootApplication annotation is the core annotation of the SpringBoot project. Its main function is to enable Spring automatic configuration. If the annotation is removed from the Application class, the SpringBoot program will not be started

  • The main method acts as the entry point for the project to start running

  • @Controller and @responseBody are still SpringMVC, SpringBoot is still using SSM and so on

3.9 Spring Boot Core Configuration file

3.9.1 Core Configuration Format
1.. properties file (default)

Modify the default Tomcat port number and project context root by modifying the application.properties configuration file

The key-value pair properties file configuration mode

# set the embedded Tomcat port number
server.port=8888
Configure the project context root
server.servlet.context-path=/app
Copy the code

Restart after the configuration is successful

Change the page access path and retry

2. Yml file format

Yml is a configuration file in YAML format. It is configured in certain blank and newline formats.

Yaml is an intuitive, computer-readable data serialization format that is easy to read. Yaml is similar to XML, but the syntax is much more brief than XML. Values must be configured with a space before the colon, and the YAML suffix can also be used

# set the embedded Tomcat port number
server:
  port: 8888
  servlet:
    Set the context root
    context-path: /app
Copy the code

Note: When both format profiles exist, the.properties profile is used, which can be renamed to demonstrate YML and re-run Application to see the port and context root

3.9.2 Configuring multiple Environments

In actual development, a project will go through many phases (development-test-live), and the configuration of each phase will be different, such as port, context root, database, etc. At this time, SpringBoot provides multiple environment configurations to facilitate switching between different environments

1. For each environment to create a configuration file named must to application – environmental logo. The properties | yml

application-dev.properties

# Development environment
# set the embedded Tomcat port number
server.port=8081
Configure the project context root
server.servlet.context-path=/dev
Copy the code

application-test.properties

# Test environment
# set the embedded Tomcat port number
server.port=8082
Configure the project context root
server.servlet.context-path=/test
Copy the code

application-product.properties

# Production environment
# set the embedded Tomcat port number
server.port=8888
Configure the project context root
server.servlet.context-path=/product
Copy the code

Activate the environment in the general configuration file application.properties

#SpringBoot total configuration file # Activate the development environment
spring.profiles.active=dev
Activate the test environment
#spring.profiles.active=test
# Activate the production environment
#spring.profiles.active=product
Copy the code

The value on the right of the equals sign is the same as the environment identifier name of the configuration file. You can change the configuration of the overall configuration file, reroute Application, and view the port and context root that was started

Yml is written the same way

3.9.3 Reading customized SpringBoot Configurations

In the core configuration file of SpringBoot, in addition to using the built-in configuration items, we can also customize the configuration, and then use the following annotations to read the configuration property values

1. @ Value annotation

This annotation is used to read the configuration in application.properties one by one

  • In the core configuration file application.properties, add two custom configuration items user.name and user.url. You can see in IDEA that these two properties are not recognized by SpringBoot
# set the embedded Tomcat port number
server.port=8081
Configure the project context root
server.servlet.context-path=/dev

user.nickName=MuFeng
user.url=www.baidu.com
Copy the code
  • Define properties in SpringBootController and use the @value annotation to get custom configuration values and test them
package com.mufeng.springboot;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controllerpublic 
class SpringBootController {   
    @Value("${user.nickName}")    
    private String userName;    
    
    @Value("${user.url}")   
    private String userUrl;   
    
    @RequestMapping(value = "/springBoot/index")    
    @ResponseBody    
    public String index(a) {        
        return "userName= " + userName + "-------userUrl= "+ userUrl; }}Copy the code

Rerun the Application and test it in the browser

2. @ConfigurationProperties

Map the entire file to an object, which can be used to customize configuration items

  • Create the UserInfo class without the Component and ConfigurationProperties annotations and add the prefix attribute to the ConfigurationProperties annotation to distinguish the configuration of the same name
package com.mufeng.springboot;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "user")
public class UserInfo {    
    private String nickName;    
    
    private String url;    
    
    public String getNickName(a) {        
        return nickName;    
    }    
    
    public void setNickName(String nickName) {  
        this.nickName = nickName;  
    }   
    
    public String getUrl(a) {      
        return url;  
    }   
    
    public void setUrl(String url) {   
        this.url = url; }}Copy the code
  • Inject the UserInfo configuration class in SpringBootController
    @Autowired    
    private UserInfo userInfo;
Copy the code
  • Modify the test methods in the SpringBootController class
  @RequestMapping(value = "/springBoot/index") 
  @ResponseBody    
  public String index(a) {   
      return "userName= " + userInfo.getNickName() + "-------userUrl= " + userInfo.getUrl();  
  }
Copy the code
  • Rerun the Application and test it in the browser

3.10 SpringBoot front-end using JSP

3.10.1 Configure the following dependencies in pom.xml file
        <! Spring Boot is embedded in Tomcat for JSP parsing package, not to parse JSP pages -->  
        <! If you just use JSP pages, you can just add the dependency -->        
        <dependency>           
            <groupId>org.apache.tomcat.embed</groupId>  
            <artifactId>tomcat-embed-jasper</artifactId>  
        </dependency>
Copy the code
3.10.2 Configure the following information in the build tag of pom. XML

SpringBoot requires that the JSP file be compiled into the specified meta-INF /resources directory to be accessible, or it cannot be accessed. In fact, the official recommendation is to use templating technology

        <! SpringBoot requires that the JSP file be compiled into the specified meta-INF /resources directory to be accessible, otherwise it cannot be accessed. Other officials have suggested using template technology -->       
        <resources>           
            <resource>               
                <! -- Source file location -->              
                <directory>src/main/webapp</directory>     
                <! Compile to meta-INF /resources -->   
                <targetPath>META-INF/resources</targetPath>            
                <! ** indicates the webApp directory and subdirectories, *.* indicates all files -->   
                <includes>                   
                    <include>/ *. * * *</include>     
                </includes>           
            </resource>          
        
            <resource>              
                <directory>src/main/resources</directory>  
                <includes>                  
                    <include>/ *. * * *</include>    
                </includes>           
            </resource>        
        </resources>
Copy the code
3.10.3 Configure the SpringMVC view in the application.properties file to be displayed as a JSP, which corresponds to the SpringMVC configuration
Configure the SpringMVC view parser
SRC /main/webapp

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
Copy the code
3.10.4 Create and code the JspController class
package com.mufeng.springboot;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controllerpublic 
class JspController {   
    @RequestMapping(value = "/springBoot/jsp") 
    public String jsp(Model model){  
        model.addAttribute("data"."SpringBoot uses JSP pages");    
        return "index"; }}Copy the code
3.10.5 Create a WebApp directory under SRC /main and create a new index.jsp page under this directory
<%--  Created by IntelliJ IDEA. 
User: a  
Date: 2021/6/15  Time: 4:23In the afternoon Tothis template use File | Settings | File Templates.--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
    <head>   
        <title>Title</title>
    </head>
    <body>
    </body>
</html>
Copy the code
3.10.6 Get the data from the Controller in the JSP page
<%--  Created by IntelliJ IDEA.  User: a  Date: 2021/6/15  Time: 4:23In the afternoon Tothis template use File | Settings | File Templates.--%>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
    <head>  
        <title>Title</title>
    </head>
    <body>  
        ${data}
    </body>
</html>
Copy the code
3.10.7 Run the Application again and access it through the browser