Springboot基礎知識(08)- spring-boot-starter-web(Web啟動器)



1. spring-boot-starter-web 簡介

    Spring MVC 是 Spring 提供的一個基於 MVC 設計模式的輕量級 Web 開發框架,其本身就是 Spring 框架的一部分,可以與 Spring 無縫集成,性能方面具有先天的優越性,是當今業界最主流的 Web 開發框架之一。
    
    Spring Boot 是在 Spring 的基礎上創建一款開源框架,它提供了 spring-boot-starter-web(Web 啟動器) 來為 Web 開發予以支持。spring-boot-starter-web 為我們提供了嵌入的 Servlet 容器以及 SpringMVC 的依賴,並為 Spring MVC 提供了大量自動配置,可以適用於大多數 Web 開發場景。

    Spring Boot 為 Spring MVC 提供了自動配置,並在 Spring MVC 默認功能的基礎上添加了以下特性:

        (1) 引入了 ContentNegotiatingViewResolver 和 BeanNameViewResolver(視圖解析器)
        (2) 對包括 WebJars 在內的靜態資源的支持
        (3) 自動注冊 Converter、GenericConverter 和 Formatter (轉換器和格式化器)
        (4) 對 HttpMessageConverters 的支持(Spring MVC 中用於轉換 HTTP 請求和響應的消息轉換器)
        (5) 自動注冊 MessageCodesResolver(用於定義錯誤代碼生成規則)
        (6) 支持對靜態首頁(index.html)的訪問
        (7) 自動使用 ConfigurableWebBindingInitializer

    只要我們在 Spring  Boot 項目中的 pom.xml 中引入了 spring-boot-starter-web,即使不進行任何配置,也可以直接使用 Spring MVC 進行 Web 開發。


2. 創建 Maven Quickstart 項目

    1) 系統環境

        Spring Boot 版本及其環境配置要求如下表。

          Spring Boot      2.x
              JDK                 8.0 及以上版本
              Maven              3.x
              IntelliJ IDEA      14.0 以上

        本文將在 Windows 下使用 IntelliJ IDEA 和 Apache Maven 創建一個簡單的 Maven Quickstart 程序。在開始之前,確保已經正確搭建了 Spring 開發環境,參考 “ Spring基礎知識(1)- Spring簡介、Spring體系結構和開發環境配置 ”。

          Windows版本 : Windows 10 Home (20H2)   
          IntelliJ IDEA:Community Edition for Windows 2020.1.4
          Apache Maven:3.8.1

    2) 運行 IDEA 創建項目 

        點擊菜單 New 創建 Project:
        
        New Project -> Project Type: Maven -> Project SDK: 1.8 -> Check "Create from archtype" -> select "org.apache.maven.archtypes:maven-archtype-quickstart" -> Next

            Name: SpringbootWeb
            GroupId: com.example
            ArtifactId: SpringbootWeb

        -> Finish

    3) 生成的項目目錄結構和文件

        (1) 目錄結構

            |-- src
            |   |-- main
            |   |     |-- java
            |   |       |-- com
            |   |            |-- example
            |   |                   |-- App.java
            |   |-- test
            |        |-- java
            |               |-- com
            |                    |-- example
            |                           |-- AppTest.java
            |-- pom.xml

        (2) App.java 代碼

1             package com.example;
2 
3             public class App {
4                 public static void main( String[] args ) {
5                     System.out.println( "Hello World!" );
6                 }
7             }


        (3) AppTest.java 代碼      

 1             package com.example;
 2 
 3             import static org.junit.Assert.assertTrue;
 4 
 5             import org.junit.Test;
 6 
 7             public class AppTest {
 8 
 9                 @Test
10                 public void shouldAnswerWithTrue() {
11                     assertTrue( true );
12                 }
13             }


        (4) pom.xml 代碼

 1             <?xml version="1.0" encoding="UTF-8"?>
 2             <project xmlns="http://maven.apache.org/POM/4.0.0" 
 3                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4                         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
 5                                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
 6                 <modelVersion>4.0.0</modelVersion>
 7 
 8                 <groupId>com.example</groupId>
 9                 <artifactId>SpringbootWeb</artifactId>
10                 <version>1.0-SNAPSHOT</version>
11 
12                 <name>SpringbootWeb Maven Webapp</name>
13                 <!-- FIXME change it to the project's website -->
14                 <url>http://www.example.com</url>
15 
16                 <properties>
17                     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18                     <maven.compiler.source>1.7</maven.compiler.source>
19                     <maven.compiler.target>1.7</maven.compiler.target>
20                 </properties>
21 
22                 <dependencies>
23                     <dependency>
24                         <groupId>junit</groupId>
25                         <artifactId>junit</artifactId>
26                         <version>4.11</version>
27                         <scope>test</scope>
28                     </dependency>
29                 </dependencies>
30 
31                 ...
32 
33             </project>


3. 配置 Spring Boot Web

    1) 導入相關依賴包,並修改配置

        訪問 http://www.mvnrepository.com/,查詢 spring-boot-starter-parent 等

        修改 pom.xml:

 1             <project ... >
 2 
 3                 <!-- 把 Maven 默認的 JDK 版本從 1.7 改成 1.8 -->
 4                 <properties>
 5                     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 6                     <maven.compiler.source>1.8</maven.compiler.source>
 7                     <maven.compiler.target>1.8</maven.compiler.target>
 8                 </properties>
 9 
10                 ...
11 
12                 <parent>
13                     <groupId>org.springframework.boot</groupId>
14                     <artifactId>spring-boot-starter-parent</artifactId>
15                     <version>2.6.6</version>
16                     <relativePath/> <!-- lookup parent from repository -->
17                 </parent>
18 
19                 <dependencies>
20 
21                     ...
22 
23                     <dependency>
24                         <groupId>org.springframework.boot</groupId>
25                         <artifactId>spring-boot-starter-web</artifactId>
26                     </dependency>
27                     <dependency>
28                         <groupId>org.springframework.boot</groupId>
29                         <artifactId>spring-boot-starter-tomcat</artifactId>
30                         <scope>provided</scope>
31                     </dependency>
32                     <dependency>
33                         <groupId>org.springframework.boot</groupId>
34                         <artifactId>spring-boot-starter-test</artifactId>
35                         <scope>test</scope>
36                     </dependency>
37 
38                     ...
39 
40                 </dependencies>
41             
42                 ...    
43 
44             </project>


        在IDE中項目列表 -> SpringbootWeb -> 點擊鼠標右鍵 -> Maven -> Reload Project

        本文選擇了 spring-boot-starter-parent 2.6.6 相關依賴包,spring-boot-starter 和 spring-boot-starter-test 的版本由 spring-boot-starter-parent 控制。

        使用 spring-boot-starter-tomcat 將 tomcat 內嵌到 web項目中,打包成 jar 后可以直接用 Java 命令行運行,不需要再部署到額外的 tomcat 服務器上。

        也可以使用 Jetty 代替 Tomcat,兩者不能同時內嵌,使用 Jetty 可用如下配置代碼代替 Tomcat 的配置代碼:

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


    2) 修改 src/main/java/com/example/App.java 文件

 1         package com.example;
 2 
 3         import org.springframework.boot.SpringApplication;
 4         import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 
 6         @SpringBootApplication
 7         public class App {
 8             public static void main(String[] args) {
 9                 SpringApplication.run(App.class, args);
10                 System.out.println("Spring boot web project");
11             }
12         }


    3) 創建 src/main/java/com/example/ServletInitializer.java 文件

 1         package com.example;
 2 
 3         import org.springframework.boot.builder.SpringApplicationBuilder;
 4         import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
 5 
 6         public class ServletInitializer extends SpringBootServletInitializer {
 7 
 8             @Override
 9             protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
10                 return application.sources(App.class);
11             }
12 
13         }


    4) 創建 src/main/java/com/example/controller/IndexController.java 文件 

 1         package com.example.controller;
 2 
 3         import org.springframework.stereotype.Controller;
 4         import org.springframework.web.bind.annotation.RequestMapping;
 5         import org.springframework.web.bind.annotation.ResponseBody;
 6 
 7         @Controller
 8         public class IndexController {
 9             @ResponseBody
10             @RequestMapping("/hello")
11             public String hello() {
12                 return "Hello page";
13             }
14         }


        注: src/main/java/com/example/controller 目錄不存在,手動創建各級目錄,下同。

    5) 創建 src/main/resources/application.properties 文件

 1         spring.main.banner-mode=off
 2 
 3         # Web server
 4         server.display-name=SpringBootWeb-Test
 5         server.address=localhost
 6         server.port=9090      
 7 
 8         # Logging
 9         logging.level.com.example=trace
10         logging.file.path=logs
11         logging.pattern.console=%d{yyyy-MM-dd hh:mm:ss} [%thread] %-5level - %msg%n | %logger{50}
12       


    6) 運行

        (1) Run App.main()

            Open App.java, click mouse right button, select Run "App.main()"

        (2) Edit Configurations

            Click "+" add new configuration -> Select "Maven"

                Command line: clean spring-boot:run
                Name: SpringbootWeb [clean,spring-boot:run]

            -> Apply / OK

        Click Run "SpringbootWeb [clean,spring-boot:run]"

            ...

            Spring boot web project        

        訪問 http://localhost:9090/hello

            Hello page

 

        注:打包可以將 Command line 改成 clean package spring-boot:repackage


4. 使用 spring-boot-maven-plugin 插件打包

    1) jar 打包

        (1) 修改 pom.xml

 1             <build>
 2                 ...
 3 
 4                 <!-- 指定 jar 文件名 -->
 5                 <finalName>SpringbootWeb</finalName>
 6 
 7                 <!-- spring-boot-maven-plugin 插件代碼 -->
 8                 <plugins>
 9                     <plugin>
10                         <groupId>org.springframework.boot</groupId>
11                         <artifactId>spring-boot-maven-plugin</artifactId>
12                         <configuration>
13                             <mainClass>com.example.App</mainClass>
14                         </configuration>
15                         <executions>
16                         <execution>
17                             <goals>
18                             <goal>repackage</goal>
19                             </goals>
20                         </execution>
21                         </executions>
22                     </plugin>
23                 </plugins>
24                 ...
25             </build>


            finalName 屬性用來指定包文件的名稱;

            在IDE中項目列表 -> 點擊鼠標右鍵 -> Maven -> Reload Project

        (2) 打包

            菜單 View -> Tool Windows -> Maven -> SpringbootWeb -> Lifecycle -> Clean & Package

            jar 包生成在目錄 target/ 里

                SpringbootWeb.jar
                SpringbootWeb.jar.original  

            注:SpringbootWeb.jar  包含依賴包,可以直接運行。SpringbootWeb.jar.original 里不包含依賴的包(要手動配置依賴環境),運行前要把文件名上的 “.original” 去掉。    

        (3) 運行

            點擊 IDEA 底部 Terminal 標簽頁,執行如下命令。

             java -jar target/SpringbootWeb.jar

                 ...

                Spring boot web project     

            訪問 http://localhost:9090/hello,頁面顯示:

                Hello page

    2) war 打包

        (1) 修改 pom.xml

 1             <!-- war 類型設置 -->
 2             <packaging>war</packaging>
 3 
 4             <!-- 注釋掉這個依賴
 5             <dependency>
 6                 <groupId>org.springframework.boot</groupId>
 7                 <artifactId>spring-boot-starter-tomcat</artifactId>
 8                 <scope>provided</scope>
 9             </dependency>
10             -->
11 
12             <build>
13                 ...
14                 <!-- 指定 war 文件名 -->
15                 <finalName>SpringbootWeb</finalName>
16 
17                 <!-- spring-boot-maven-plugin 插件代碼 -->
18                 <plugins>
19                     <plugin>
20                         <groupId>org.springframework.boot</groupId>
21                         <artifactId>spring-boot-maven-plugin</artifactId>
22                         <configuration>
23                             <mainClass>com.example.App</mainClass>
24                         </configuration>
25                         <executions>
26                         <execution>
27                             <goals>
28                             <goal>repackage</goal>
29                             </goals>
30                         </execution>
31                         </executions>
32                     </plugin>
33                 </plugins>
34                 ...
35             </build>


            在IDE中項目列表 -> 點擊鼠標右鍵 -> Maven -> Reload Project
        
         (2) 打包

            菜單 View -> Tool Windows -> Maven -> SpringbootWeb -> Lifecycle -> Clean & Package

            war 包生成在目錄 target/ 里

                SpringbootWeb.war
                SpringbootWeb.war.original

        (3) 運行

            把 SpringbootWeb.war 復制到獨立運行的 Tomcat 下 webapp 目錄,默認設置的 Tomcat 運行在 8080 端口。

            Tomcat 會自動解壓 SpringbootWeb.war,在 webapp 下產生 SpringbootWeb 目錄,目錄產生了就可以訪問 http://localhost:8080/SpringbootWeb/hello ,頁面顯示:

                Hello page

--------------------------------------

示例代碼:https://gitee.com/slksm/public-codes/tree/master/demos/SpringbootWeb

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM