一、spring-boot-starter-web 依賴概述
在 Spring Boot 快速入門中,只要在 pom.xml 加入了 spring-boot-starter-web 依賴,即可快速開發 web 應用。可見,Spring Boot 極大地簡化了 Spring 應用從搭建到開發的過程,做到了「開箱即用」的方式。Spring Boot 已經提供很多「開箱即用」的依賴,如上面開發 web 應用使用的 spring-boot-starter-web ,都是以 spring-boot-starter-xx 進行命名的。
Spring Boot 「開箱即用」 的設計,對開發者非常便利。簡單來說,只要往 Spring Boot 項目加入相應的 spring-boot-starter-xx 依賴,就可以使用對應依賴的功能,比如加入 spring-boot-starter-data-jpa 依賴,就可以使用數據持久層框架 Spring Data JPA 操作數據源。相比 Spring 以前需要大量的XML配置以及復雜的依賴管理,極大的減少了開發工作量和學習成本。
當開發一個特定類型的應用程序時,特定的 Starter 提供所需的依賴關系,并且將對應的 Bean 注冊到 Spring 容器中。spring-boot-starter-web 依賴就是提供開發 Web 應用的。
1.1 spring-boot-starter-web 職責
spring-boot-starter-web 是一個用于構建 Web 的 Starter ,包括構建 RESTful 服務應用、Spring MVC 應用等。并且不需要額外配置容器,默認使用 Tomcat 作為嵌入式容器。
1.2 spring-boot-starter-web 依賴關系
spring-boot-starter-web 這么強大,它的組成如下表:
spring-boot-starter 核心包,包括了自動化配置支持、日志、YAML 文件解析的支持等。
spring-boot-starter-json 讀寫 JSON 包
spring-boot-starter-tomcat Tomcat 嵌入式 Servlet 容器包
hibernate-validator Hibernate 框架提供的驗證包
spring-web Spring 框架的 Web 包
spring-webmvc Spring 框架的 Web MVC 包
spring-boot-starter-web 包含了 Tomcat 和 Spring MVC ,那啟動流程是這樣的。 標識 @SpringBootApplication 的應用,初始化經過 spring-boot-starter 核心包中的自動化配置,構建了 Spring 容器,并通過 Tomcat 啟動 Web 應用。很多 Starters 只支持 Spring MVC,一般會將 spring-boot-starter-web 依賴加入到應用的 Classpath。
另外,spring-boot-starter-web 默認使用 Tomcat 作為嵌入式 Servlet 容器,在 pom.xml 配置 spring-boot-starter-jetty 和 spring-boot-starter-undertow 就可以替換默認容器。
二、Spring MVC on Spring Boot
Spring MVC 是 Spring Web 重要的模塊。內容包括 MVC 模式的實現和 RESTful 服務的支持。
2.1 Spring MVC 體系溫故知新
spring-webmvc 模塊里面包:
– org.springframework.web.servlet 提供與應用程序上下文基礎結構集成的 Servlet,以及 Spring web MVC 框架的核心接口和類。
– org.springframework.web.servlet.mvc Spring 附帶的 Servlet MVC 框架的標準控制器實現。
– org.springframework.web.servlet.mvc.annotation 用于基于注解的 Servlet MVC 控制器的支持包。
– org.springframework.web.servlet.mvc.condition 用于根據條件匹配傳入請求的公共 MVC 邏輯。
– org.springframework.web.servlet.mvc.method 用于處理程序方法處理的基于 Servlet 的基礎結構,基于在 org.springframework.web.method 包上。
– org.springframework.web.servlet.view 提供標準的 View 和 ViewResolver 實現,包括自定義實現的抽象基類。
– org.springframework.web.servlet.view.freemarker 支持將 FreeMarker 集成為 Spring Web 視圖技術的類。
– org.springframework.web.servlet.view.json 支持提供基于 JSON 序列化的 View 實現的類。
上面列出來核心的包。org.springframework.web.servlet.view 包中, View 視圖實現有常見的:JSON 、FreeMarker 等。org.springframework.web.servlet.mvc 包中,Controller 控制層實現包括了注解、程序方法處理等封裝。自然,看源碼先從 org.springframework.web.servlet 包看其核心的接口和類。
2.2 重要的類
DispatcherServlet 類:調度 HTTP 請求控制器(或者處理器 Handler)。
View 視圖層 ModelAndView 類:模型和視圖的持有者。
View 接口:MVC WEB 交互。該接口的實現負責呈現視圖或者暴露模型。
Controller 控制層 HandlerMapping 接口: 請求從 DispacherServlet 過來,該接口定義請求和處理程序對象之間的映射。
HandlerInterceptor 接口:處理程序的執行鏈接口。
Spring MVC 框架模型
2.3 Spring Boot MVC
以前 Spring MVC 開發模式是這樣的:
1. 在 web.xml 配置 DispatcherServlet,用于截獲并處理所有請求
2. 在 Spring MVC 配置文件中,聲明預定義的控制器和視圖解析器等
3. 編寫預定義的處理請求控制器
4. 編寫預定義的視圖對象,比如 JSP、Freemarker 等
在 Spring Boot MVC 中,Web 自動化配置會幫你減少上面的兩個步驟。默認使用的視圖是 ThymeLeaf,在下面小節會具體講
1. 編寫預定義的處理請求控制器
2. 編寫默認 ThymeLeaf 視圖對象
例如下面會展示用戶列表案例:
第一步:處理用戶請求控制器
UserController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
/** * 用戶控制層 * * Created by bysocket on 24/07/2017. */ @Controller @RequestMapping (value = "/users" ) // 通過這里配置使下面的映射都在 /users public class UserController { @Autowired UserService userService; // 用戶服務層 /** * 獲取用戶列表 * 處理 "/users" 的GET請求,用來獲取用戶列表 * 通過 @RequestParam 傳遞參數,進一步實現條件查詢或者分頁查詢 */ @RequestMapping (method = RequestMethod.GET) public String getUserList(ModelMap map) { map.addAttribute( "userList" , userService.findAll()); return "userList" ; } } @Controller 注解在 UserController 類上,標識其為一個可接收 HTTP 請求的控制器 @RequestMapping (value = “/users”) 注解 ,標識 UserController 類下所有接收的請求路由都是 /users 開頭的。注意:類上的 @RequestMapping 注解是不必需的 @RequestMapping (method = RequestMethod.GET) 注解,標識該 getUserList(ModelMap map) 方法會接收并處理 /users 請求,且請求方法是 GET getUserList(ModelMap map) 方法返回的字符串 userList ,代表著是視圖,會有視圖解析器解析成為一個具體的視圖對象,然后經過視圖渲染展示到瀏覽器 |
第二步:用戶列表 ThymeLeaf 視圖對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<!DOCTYPE html> <html lang= "zh-CN" > <head> <script type= "text/javascript" th:src= "@{https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js}" ></script> <link th:href= "@{https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css}" rel= "external nofollow" rel= "stylesheet" /> <link th:href= "@{/css/default.css}" rel= "external nofollow" rel= "stylesheet" /> <link rel= "icon" th:href= "@{/images/favicon.ico}" rel= "external nofollow" type= "image/x-icon" /> <meta charset= "UTF-8" /> <title>用戶列表</title> </head> <body> <div class = "contentDiv" > <h5> 《 Spring Boot 2 .x 核心技術實戰》第二章快速入門案例</h5> <table class = "table table-hover table-condensed" > <legend> <strong>用戶列表</strong> </legend> <thead> <tr> <th>用戶編號</th> <th>名稱</th> <th>年齡</th> <th>出生時間</th> <th>管理</th> </tr> </thead> <tbody> <tr th:each= "user : ${userList}" > <th scope= "row" th:text= "${user.id}" ></th> <td><a th:href= "@{/users/update/{userId}(userId=${user.id})}" rel= "external nofollow" th:text= "${user.name}" ></a></td> <td th:text= "${user.age}" ></td> <td th:text= "${user.birthday}" ></td> <td><a class = "btn btn-danger" th:href= "@{/users/delete/{userId}(userId=${user.id})}" rel= "external nofollow" >刪除</a></td> </tr> </tbody> </table> <div><a class = "btn btn-primary" href= "/users/create" rel= "external nofollow" role= "button" >創建用戶</a></div> </div> </body> </html> |
一個 table 展示用戶列表,引入了 jquery.min.js 和 bootstrap.min.css ,更好的展示頁面效果。具體 ThymeLeaf 語法下面會講到。
代碼共享在:https://github.com/JeffLi1993/spring-boot-core-book-demo
2.3.1 控制器
什么是控制器?控制器就是控制請求接收和負責響應到視圖的角色。
@Controller 注解標識一個類作為控制器。DispatcherServlet 會掃描所有控制器類,并檢測 @RequestMapping 注解配置的方法。Web 自動化配置已經處理完這一步驟。
@RequestMapping 注解標識請求 URL 信息,可以映射到整個類或某個特定的方法上。該注解可以表明請求需要的。
使用 value 指定特定的 URL ,比如 @RequestMapping(value = “/users”) 和 @RequestMapping(value = “/users/create”) 等
使用 method 指定 HTTP 請求方法,比如 RequestMethod.GET 等
還有使用其他特定的參數條件,可以設置 consumes 指定請求時的請求頭需要包含的 Content-Type 值、設置 produces 可確保響應的內容類型
MVC on REST ful 場景
在 HTTP over JSON (自然 JSON、XML或其他自定義的媒體類型內容等均可)場景,配合上前后端分離的開發模式,我們經常會用 @ResponseBody 或 @RestController 兩種方式實現 RESTful HTTP API 。
老方式:
@ResponseBody 注解標識該方法的返回值。這樣被標注的方法返回值,會直接寫入 HTTP 響應體(而不會被視圖解析器認為是一個視圖對象)。
新方式:
@RestController 注解,和 @Controller 用法一致,整合了 @Controller 和 @ResponseBody 功能。這樣不需要每個 @RequestMapping 方法上都加上 @ResponseBody 注解,這樣代碼更簡明。
使代碼更簡明,還有常用便捷注解 @GetMapping、@PostMapping 和 @PutMapping 等
HTTP 協議相關知識回顧,可以看看我以前的博文《圖解 HTTP 協議》http://www.bysocket.com/?p=282
2.3.2 數據綁定
數據綁定,簡單的說就是 Spring MVC 從請求中獲取請求入參,賦予給處理方法相應的入參。主要流程如下:
1. DataBinder 接受帶有請求入參的 ServletRequest 對象
2. 調用 ConversionService 組件,進行數據類型轉換、數據格式化等工作
3. 然后調用 Validator 組件,進行數據校驗等工作
4. 綁定結果到 BindingResult 對象
5. 最后賦予給處理方法相應的入參
@ModelAttribute 注解添加一個或多個屬性(類對象)到 model 上。例如
1
2
|
@RequestMapping (value = "/create" , method = RequestMethod.POST) public String postUser( @ModelAttribute User user) |
@PathVariable 注解通過變量名匹配到 URI 模板中相對應的變量。例如
1
2
|
@RequestMapping (value = "/update/{id}" , method = RequestMethod.GET) public String getUser( @PathVariable ( "id" ) Long id, ModelMap map) |
@RequestParam 注解將請求參數綁定到方法參數。
@RequestHeader 注解將請求頭屬性綁定到方法參數。
2.3.3 視圖和視圖解析
視圖的職責就是渲染模型數據,將模型里面的數據展示給用戶。
請求到經過處理方法處理后,最終返回的是 ModeAndView 。可以從 Spring MVC 框架模型 看出,最終經過 ViewResolver 視頻解析器得到視圖對象 View。可能是我們常見的 JSP ,也可能是基于 ThymLeaf 、FreeMarker 或 Velocity 模板引擎視圖,當然還有可能是 JSON 、XML 或者 PDF 等各種形式。
業界流行的模板引擎有如下的 Starters 支持:
spring-boot-starter-thymeleaf Thymeleaf 模板視圖依賴,官方推薦
spring-boot-starter-freemarker Freemarker 模板視圖依賴
spring-boot-starter-groovy-templates Groovy 模板視圖依賴
spring-boot-starter-mustache Mustache 模板視圖依賴
具體,spring-boot-starter-thymeleaf 使用案例在 GitHub :https://github.com/JeffLi1993/spring-boot-core-book-demo 的 chapter-2-spring-boot-quick-start 工程。
三、小結
本文主要介紹了 Spring Boot 在 Web 開發中涉及到的 HTTP 協議,還有一些 Spring MVC 相關的知識。
推薦:
開源項目 springboot-learning-example https://github.com/JeffLi1993/springboot-learning-example
開源項目 spring-boot-core-book-demo https://github.com/JeffLi1993/spring-boot-core-book-demo
總結
以上所述是小編給大家介紹的Spring Boot Web 開發注解篇,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.bysocket.com/?p=1929