翻譯自:https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web
Spring Boot非常適合web應用程序開發。您可以使用嵌入式Tomcat、Jetty、Undertow或Netty創建一個自包含的(self-contained)HTTP服務器。大多數web應用程序使用spring-boot-starter-web模塊快速啓動並運行。您還可以選擇使用spring-boot-starter-webflux模塊構建反應式web應用程序。
如果您還沒有開發過Spring Boot web應用程序,可以參考“Hello World!”入門部分的示例。
1. Servlet Web Applications
如果您想構建基於servlet的web應用程序,可以利用Spring Boot對Spring MVC或Jersey的自動配置。
1.1. The “Spring Web MVC Framework”
Spring Web MVC框架(通常被稱爲“SpringMVC”)是一個豐富的“模型(model)-視圖(view)-控制器(controller)”Web框架。Spring MVC允許您創建特殊的@Controller或@RestController bean來處理傳入的HTTP請求。控制器中的方法通過@RequestMapping註釋映射到HTTP。
下面的代碼顯示了提供JSON數據的典型@RestController:
import java.util.List; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class MyRestController { private final UserRepository userRepository; private final CustomerRepository customerRepository; public MyRestController(UserRepository userRepository, CustomerRepository customerRepository) { this.userRepository = userRepository; this.customerRepository = customerRepository; } @GetMapping("/{user}") public User getUser(@PathVariable Long userId) { return this.userRepository.findById(userId).get(); } @GetMapping("/{user}/customers") public List<Customer> getUserCustomers(@PathVariable Long userId) { return this.userRepository.findById(userId).map(this.customerRepository::findByUser).get(); } @DeleteMapping("/{user}") public void deleteUser(@PathVariable Long userId) { this.userRepository.deleteById(userId); } }
Spring MVC是核心Spring框架的一部分,詳細信息可在參考文檔中找到。spring.io/guides上還提供了幾個關於Spring MVC的指南。
1.1.1. Spring MVC Auto-configuration
Spring Boot爲Spring MVC提供了自動配置(auto-configuration),可用於大多數應用程序。
自動配置在Spring默認設置的基礎上增加了以下功能:
- Inclusion(包含) of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.
- Support for serving static resources, including support for WebJars (covered later in this document).
- Automatic registration of
Converter
,GenericConverter
, andFormatter
beans.
- Support for
HttpMessageConverters
(covered later in this document).
- Automatic registration of
MessageCodesResolver
(covered later in this document).
- Static
index.html
support.
- Automatic use of a
ConfigurableWebBindingInitializer
bean (covered later in this document).
如果您想保留這些Spring Boot MVC定製,並進行更多MVC定製(攔截器、格式化程序、視圖控制器和其他功能),您可以添加自己的@Configuration類,類型爲WebMvcConfigurer,但不使用@EnableWebMvc。
如果您想提供RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定義實例,並且仍然保留Spring Boot MVC自定義設置,那麼可以聲明WebMvcRegistrations類型的bean,並使用它來提供這些組件的自定義實例。
如果你想完全控制Spring MVC,你可以添加你自己的@Configuration註釋@EnableWebMvc,或者添加你自己的@Configuration註釋DelegatingWebMvcConfiguration配置,如@EnableWebMvc的Javadoc所述。
1.1.2. HttpMessageConverters
Spring MVC使用HttpMessageConverter接口轉換HTTP請求和響應。合理的默認設置是現成的。例如,對象可以自動轉換爲JSON(通過使用Jackson庫)或XML(通過使用Jackson XML擴展,如果可用,或者如果Jackson XML擴展不可用,則通過使用JAXB)。默認情況下,字符串以UTF-8編碼。
1.1.5. Static Content
默認情況下,Spring Boot從類路徑中名爲/static(或/public或/resources或/META-INF/resources)的目錄或ServletContext的根目錄提供靜態內容。它使用Spring MVC中的ResourceHttpRequestHandler,因此您可以通過添加自己的WebMvcConfigurer並重寫addResourceHandlers方法來修改該行爲。
在一個獨立的web應用程序中,容器中的默認servlet也會被啓用,並充當後備服務,如果Spring決定不處理它,則從ServletContext的根目錄提供內容。大多數情況下,這種情況不會發生(除非修改默認的MVC配置),因爲Spring總是可以通過DispatcherServlet處理請求。
默認情況下,資源映射到/**,但您可以使用spring.mvc.static-path-pattern屬性對其進行調整。例如,將所有資源重新定位到/resources/**可以通過以下方式實現:
spring.mvc.static-path-pattern=/resources/**
還可以使用spring.web.resources.static-locations屬性(用目錄位置列表替換默認值)自定義靜態資源位置。根servlet上下文路徑“/”也會自動添加爲一個位置。
1.1.6. Welcome Page
Spring Boot支持靜態和模板化的歡迎頁面。它首先在配置的靜態內容位置中查找index.html文件。如果沒有找到,它就會查找索引模板。如果找到其中任何一個,則自動將其用作應用程序的歡迎頁面。
1.1.7. Path Matching and Content Negotiation
Spring MVC可以通過查看請求路徑並將其與應用程序中定義的映射匹配(例如,控制器方法上的@GetMapping註釋),將傳入的HTTP請求映射到處理程序。
Spring Boot默認選擇禁用後綴模式匹配,這意味着像“GET /projects/spring-boot.json”這樣的請求將不會與@GetMapping(“/projects/spring-boot”)映射匹配。這被認爲是Spring MVC應用程序的最佳實踐。這個特性在過去主要用於HTTP客戶機,這些客戶機沒有發送正確的“Accept”請求頭;我們需要確保向客戶端發送正確的內容類型。如今,內容協商(Content Negotiation)更加可靠。
還有其他一些方法可以處理HTTP客戶端不一致地發送正確的“Accept”請求頭。我們可以使用查詢參數來確保像“GET /projects/spring-boot?format=json”這樣的請求將被映射到@GetMapping(“/projects/spring-boot”):
spring.mvc.contentnegotiation.favor-parameter=true
或者,如果您更喜歡使用不同的參數名稱:
spring.mvc.contentnegotiation.favor-parameter=true spring.mvc.contentnegotiation.parameter-name=myparam
大多數標準media類型都支持開箱即用(out-of-the-box),但您也可以定義新的media類型:
spring.mvc.contentnegotiation.media-types.markdown=text/markdown
後綴模式匹配已被棄用,並將在未來的版本中刪除。如果您理解這些注意事項,並且仍然希望應用程序使用後綴模式匹配,則需要以下配置:
spring.mvc.contentnegotiation.favor-path-extension=true spring.mvc.pathmatch.use-suffix-pattern=true
或者,與其打開所有後綴模式,不如只支持已註冊的後綴模式:
spring.mvc.contentnegotiation.favor-path-extension=true spring.mvc.pathmatch.use-registered-suffix-pattern=true
從Spring Framework 5.3開始,Spring MVC支持幾種實現策略,用於將請求路徑匹配到控制器處理程序。它以前只支持AntPathMatcher策略,但現在還提供PathPatternParser。Spring Boot現在提供了一個配置屬性來選擇和選擇新策略:
spring.mvc.pathmatch.matching-strategy=path-pattern-parser
或者更詳細的說明爲什麼你應該考慮這個新的實現,請看專門的博客文章。
1.1.10. Error Handling
默認情況下,Spring Boot提供了一個/error映射,以合理的方式處理所有錯誤,並在servlet容器中註冊爲“全局(global)”錯誤頁。對於機器客戶端,它會生成一個JSON響應,其中包含錯誤、HTTP狀態和異常消息的詳細信息。對於瀏覽器客戶端,有一個以HTML格式呈現相同數據的“白標籤(whitelabel)”錯誤視圖(要自定義它,請添加一個解決error的View)。
如果要自定義默認錯誤處理行爲,可以設置許多server.error屬性。請參閱附錄中的“服務器屬性”部分。
要完全替換默認行爲,可以實現ErrorController並註冊該類型的bean定義,或者添加ErrorAttributes類型的bean以使用現有機制,但替換內容。
1.3. Embedded Servlet Container Support
對於servlet應用程序,Spring Boot包括對嵌入式Tomcat、Jetty和Undertow服務器的支持。大多數開發人員使用適當的“啓動器(Starter)”來獲得完全配置的實例。默認情況下,嵌入式服務器偵聽端口8080上的HTTP請求。
1.3.4. Customizing Embedded Servlet Containers
可以使用Spring Environment屬性配置公共servlet容器設置。通常,您會在application.properties或application.yaml文件中定義屬性。
常見的服務器設置包括:
- 網絡設置:偵聽傳入HTTP請求的端口(server.port)、綁定到server.address的接口地址,等等。
- 會話設置(Session settings):session是否持久(server.servlet.session.persistent)、session超時(server.servlet.Session.timeout)、session數據位置(server.servlet.session.store-dir)和session-cookie配置(server.servlet.session.cookie.*)。
- 錯誤管理:錯誤頁面的位置(server.error.path)等等。
Spring Boot儘可能地公開公共設置,但這並不總是可能的。對於這些情況,專用名稱空間提供特定於服務器的定製(請參閱server.tomcat和server.undertow)。例如,可以使用嵌入式servlet容器的特定功能配置訪問日誌。
有關完整列表,請參見ServerProperties類。
SameSite Cookies
web瀏覽器可以使用SameSite cookie屬性來控制是否以及如何在跨站點請求中提交cookie。該屬性與現代web瀏覽器尤其相關,因爲現代web瀏覽器已開始更改缺少該屬性時使用的默認值。