<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 27\. 開發Web應用程序 Spring Boot非常適合Web應用程序開發。 您可以使用嵌入式Tomcat,Jetty或Undertow輕松創建自包含的HTTP服務器。 大多數Web應用程序將使用spring-boot-starter-web模塊快速啟動和運行。 如果您尚未開發Spring Boot Web應用程序,則可以按照“Hello World!”示例進行操作。 在“[入門](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#getting-started-first-application)”部分中的示例。 ### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#271-spring-web-mvc框架)27.1 “Spring Web MVC框架” Spring Web MVC框架(通常簡稱為“Spring MVC”)是一個豐富的“模型視圖控制器”Web框架。 Spring MVC允許您創建特殊的@Controller或@RestController bean來處理傳入的HTTP請求。 您的控制器中的方法將使用@RequestMapping注釋映射到HTTP。 以下是@RestController用于提供JSON數據的典型示例: ``` @RestController @RequestMapping(value="/users") public class MyRestController { @RequestMapping(value="/{user}", method=RequestMethod.GET) public User getUser(@PathVariable Long user) { // ... } @RequestMapping(value="/{user}/customers", method=RequestMethod.GET) List<Customer> getUserCustomers(@PathVariable Long user) { // ... } @RequestMapping(value="/{user}", method=RequestMethod.DELETE) public User deleteUser(@PathVariable Long user) { // ... } } ``` Spring MVC是Spring Framework的一部分,詳細信息可在[參考文檔](http://docs.spring.io/spring/docs/4.3.7.RELEASE/spring-framework-reference/htmlsingle#mvc)中找到。?[Spring.io/guide](https://spring.io/guides)中還有幾個指南可供Spring MVC使用。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2711-spring-mvc自動配置)27.1.1 Spring MVC自動配置 Spring Boot提供了適用于大多數應用程序的Spring MVC的自動配置。 自動配置在Spring的默認值之上添加以下功能: * 包含ContentNegotiatingViewResolver和BeanNameViewResolver bean。 * 支持提供靜態資源,包括對WebJars的支持(見下文)。 * Converter,GenericConverter,Formatter beans的自動注冊。 * 支持HttpMessageConverters(見下文)。 * 自動注冊MessageCodesResolver(見下文)。 * 靜態index.html支持。 * 自定義Favicon支持(見下文)。 * 自動使用ConfigurableWebBindingInitializer bean(見下文)。 如果要保留Spring Boot MVC功能,并且您只需要添加其他[MVC配置](http://docs.spring.io/spring/docs/4.3.7.RELEASE/spring-framework-reference/htmlsingle#mvc)(interceptors, formatters, view, controllers等),你可以添加自己的WebConfigurerAdapter類型的@Configuration類,但不能使用@EnableWebMvc。 如果要提供自定義的RequestMappingHandlerMapping,RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver實例,您可以聲明一個提供此類組件的WebMvcRegistrationsAdapter實例。 如果要完全控制Spring MVC,可以使用@EnableWebMvc添加您自己的@Configuration注釋。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2712-httpmessageconverters)27.1.2 HttpMessageConverters Spring MVC使用HttpMessageConverter接口轉換HTTP請求和響應。 包括一些開箱即用的合理配置,例如對象可以自動轉換為JSON(使用Jackson庫)或XML(使用Jackson XML擴展,如果可用,否則使用JAXB)。 字符串默認使用UTF-8進行編碼。 如果需要添加或自定義轉換器,可以使用Spring Boot HttpMessageConverter類: ``` import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.*; import org.springframework.http.converter.*; @Configuration public class MyConfiguration { @Bean public HttpMessageConverters customConverters() { HttpMessageConverter<?> additional = ... HttpMessageConverter<?> another = ... return new HttpMessageConverters(additional, another); } } ``` 上下文中存在的任何HttpMessageConverter bean將被添加到轉換器列表中。 您也可以以這種方式覆蓋默認轉換器。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2713-自定義json序列化器和反序列化器)27.1.3 自定義JSON序列化器和反序列化器 如果您使用Jackson序列化和反序列化JSON數據,則可能需要編寫自己的JsonSerializer和JsonDeserializer類。 自定義序列化程序通常[通過一個模塊注冊到Jackson](http://wiki.fasterxml.com/JacksonHowToCustomDeserializers),但是Spring Boot提供了一個備用的@JsonComponent注釋,可以更容易地直接注冊Spring Bean。 您可以直接在JsonSerializer或JsonDeserializer實現中使用@JsonComponent。 您也可以將它用于包含序列化器/解串器的類作為內部類。 例如: ``` import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import org.springframework.boot.jackson.*; @JsonComponent public class Example { public static class Serializer extends JsonSerializer<SomeObject> { // ... } public static class Deserializer extends JsonDeserializer<SomeObject> { // ... } } ``` ApplicationContext中的所有@JsonComponent bean將自動注冊到Jackson,并且由于@JsonComponent是使用@Component進行元注解的,所以常規的組件掃描規則適用。 Spring Boot還提供了[JsonObjectSerializer](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java)和[JsonObjectDeserializer](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java)基類,它們在序列化對象時為標準的Jackson版本提供了有用的替代方法。 有關詳細信息,請參閱Javadoc。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2714-messagecodesresolver)27.1.4 MessageCodesResolver Spring MVC有一個生成錯誤代碼的策略,用于從綁定錯誤中提取錯誤消息:MessageCodesResolver。 Spring Boot將為您創建一個錯誤代碼,如果您設置spring.mvc.message-codes-resolver.format屬性PREFIX_ERROR_CODE或POSTFIX_ERROR_CODE(請參閱DefaultMessageCodesResolver.Format中的枚舉)。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2715-靜態內容)27.1.5 靜態內容 默認情況下,Spring Boot將從類路徑或ServletContext的根目錄中的名為/static(或/ public或/resources或/META-INF/resources)的目錄提供靜態內容。 它使用Spring MVC中的ResourceHttpRequestHandler,因此您可以通過添加自己的WebMvcConfigurerAdapter并覆蓋addResourceHandlers方法來修改該行為。 在獨立的Web應用程序中,來自容器的默認servlet也被啟用,并且作為后備,如果Spring決定不處理它,則從ServletContext的根目錄提供內容。 大多數情況下,這不會發生(除非您修改默認的MVC配置),因為Spring將始終能夠通過DispatcherServlet處理請求。 默認情況下,資源映射到/** ,但可以通過spring.mvc.static-path-pattern調整。 例如,將所有資源重定位到 /resources/**可以配置如下: ``` spring.mvc.static-path-pattern=/resources/** ``` 您還可以使用spring.resources.static-locations(使用目錄位置列表替換默認值)來自定義靜態資源位置。 如果這樣做,默認歡迎頁面檢測將切換到您的自定義位置,因此,如果在啟動時任何位置都有一個index.html,它將是應用程序的主頁。 除了上述“標準”靜態資源位置之外,還提供了一個特殊情況,用于[Webjars內容](http://www.webjars.org/)。 任何具有/ webjars / **中路徑的資源都將從jar文件中提供,如果它們以Webjars格式打包。 如果您的應用程序將被打包為jar,請不要使用 src/main/webapp 目錄。 雖然這個目錄是一個通用的標準,但它只適用于war包,如果生成一個jar,它將被大多數構建工具忽略。 Spring Boot還支持Spring MVC提供的高級資源處理功能,允許使用例如緩存靜態資源或使用Webjars的版本無關的URL。 要為Webjars使用版本無關的URL,只需添加webjars-locator依賴關系即可。然后聲明您的Webjar,以jQuery為例,如“/webjars/jquery/dist/jquery.min.js”,這將產生“/webjars/jquery/xyz/dist/jquery.min.js”,其中xyz是Webjar版本 。 > 如果您使用JBoss,則需要聲明webjars-locator-jboss-vfs依賴關系而不是webjars-locator; 否則所有Webjars都將解析為404。 要使用緩存清除功能,以下配置將為所有靜態資源配置緩存清除解決方案,從而有效地在URL中添加內容哈希值,例如&lt;link href=“/css/spring-2a2d595e6ed9a0b24f027f2b63b134d6.css”/&gt;: ``` spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/** ``` > 鏈接資源在運行時在模板中被重寫,這歸功于自動配置為Thymeleaf和FreeMarker的ResourceUrlEncodingFilter。 使用JSP時,應手動聲明此過濾器。 其他模板引擎現在不會自動支持,但可以使用自定義模板宏/幫助程序和使用[ResourceUrlProvider](http://docs.spring.io/spring/docs/4.3.7.RELEASE/javadoc-api/org/springframework/web/servlet/resource/ResourceUrlProvider.html)。 當使用例如JavaScript模塊加載器動態加載資源時,重命名文件不是一個選項。這就是為什么其他策略也得到支持并可以合并的原因。 “固定(fixed)”策略將在URL中添加靜態版本字符串,而不更改文件名: ``` spring.resources.chain.strategy.content.enabled=true spring.resources.chain.strategy.content.paths=/** spring.resources.chain.strategy.fixed.enabled=true spring.resources.chain.strategy.fixed.paths=/js/lib/ spring.resources.chain.strategy.fixed.version=v12 ``` 使用此配置,位于“/js/lib/”下的JavaScript模塊將使用固定版本策略“/v12/js/lib/mymodule.js”,而其他資源仍將使用內容&lt;link href =“/css/“spring-2a2d595e6ed9a0b24f027f2b63b134d6.css”/&gt;。 有關更多支持的選項,請參閱[ResourceProperties](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java)。 > 此功能已在專門的[博客文章](https://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources)和Spring Framework[參考文檔](http://docs.spring.io/spring/docs/4.3.7.RELEASE/spring-framework-reference/htmlsingle/#mvc-config-static-resources)中進行了詳細描述。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2716-自定義圖標)27.1.6 自定義圖標 Spring Boot在配置的靜態內容位置和類路徑的根目錄(按順序)中查找favicon.ico。 如果文件存在,它將被自動用作應用程序的圖標。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2717-configurablewebbindinginitializer)27.1.7 ConfigurableWebBindingInitializer Spring MVC使用WebBindingInitializer為特定請求初始化WebDataBinder。 如果您用@Bean創建自己的ConfigurableWebBindingInitializer @Bean,Spring Boot將自動配置Spring MVC以使用它。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2718-模板引擎)27.1.8 模板引擎 除了REST Web服務,您還可以使用Spring MVC來提供動態HTML內容。 Spring MVC支持各種模板技術,包括Thymeleaf,FreeMarker和JSP。 許多其他模板引擎也運行自己的Spring MVC集成。 Spring Boot包括對以下模板引擎的自動配置支持: * [FreeMarker](http://freemarker.org/docs/) * [Groovy](http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_the_markuptemplateengine) * [Thymeleaf](http://www.thymeleaf.org/) * [Mustache](https://mustache.github.io/) > 如果可能,應避免使用JSP,當使用嵌入式servlet容器時,JSP有幾個[已知的限制](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-jsp-limitations)。 當您使用默認配置的模板引擎之一時,您的模板將從 src/main/resources/templates 自動獲取。 > IntelliJ IDEA根據運行應用程序的方式對類路徑進行不同的排序。 通過main方法在IDE中運行應用程序將導致使用Maven或Gradle打包的jar運行應用程序時的不同順序。這可能會導致Spring Boot找不到類路徑上的模板。 如果您受此問題的影響,您可以重新排序IDE中的類路徑,以放置模塊的類和資源。 或者,您可以配置模板前綴以搜索類路徑上的每個模板目錄:`classpath*:/templates/`。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2719-錯誤處理)27.1.9 錯誤處理 默認情況下,Spring Boot提供 /error 映射,以合理的方式處理所有錯誤,并在servlet容器中注冊為“global”錯誤頁面。 對于機器客戶端,它將產生JSON響應,其中包含錯誤,HTTP狀態和異常消息的詳細信息。 對于瀏覽器客戶端,有一個'whitelabel'錯誤視圖,以HTML格式呈現相同的數據(定制它只需添加一個解析“error”的視圖)。 要完全替換默認行為,您可以實現ErrorController并注冊該類型的bean定義,或者簡單地添加一個類型為ErrorAttributes的bean來使用現有機制,但只是替換內容。 > BasicErrorController可以用作自定義ErrorController的基類。 如果要添加新內容類型的處理程序(默認情況下是專門處理text/html并為其他內容提供備選),這一點尤其有用。 要做到這一點,只需擴展BasicErrorController并添加一個帶有@RequestMapping的公共方法,并創建一個新類型的bean。 您還可以定義一個@ControllerAdvice來自定義為特定控制器 and/or 異常類型返回的JSON文檔。 ``` @ControllerAdvice(basePackageClasses = FooController.class) public class FooControllerAdvice extends ResponseEntityExceptionHandler { @ExceptionHandler(YourException.class) @ResponseBody ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { HttpStatus status = getStatus(request); return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } } ``` 在上面的示例中,如果由FooController在同一個包中定義的控件拋出了YourException,則將使用CustomerErrorType POJO的json表示法而不是ErrorAttributes表示形式。 ##### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#自定義錯誤頁面)自定義錯誤頁面 如果要顯示給定狀態代碼的自定義HTML錯誤頁面,請將文件添加到/error文件夾。 錯誤頁面可以是靜態HTML(即添加在任何靜態資源文件夾下)或使用模板構建。 該文件的名稱應該是確切的狀態代碼或一個序列掩碼。 例如,要將404映射到靜態HTML文件,您的文件夾結構將如下所示: ``` src/ +- main/ +- java/ | + <source code> +- resources/ +- public/ +- error/ | +- 404.html +- <other public assets> ``` 要使用FreeMarker模板映射所有5xx錯誤,使用如下結構: ``` src/ +- main/ +- java/ | + <source code> +- resources/ +- templates/ +- error/ | +- 5xx.ftl +- <other templates> ``` 對于更復雜的映射,您還可以添加實現ErrorViewResolver接口的bean。 ``` public class MyErrorViewResolver implements ErrorViewResolver { @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { // Use the request or status to optionally return a ModelAndView return ... } } ``` 您還可以使用常規的Spring MVC功能,如[@ExceptionHandler方法](http://docs.spring.io/spring/docs/4.3.7.RELEASE/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers)和[@ControllerAdvice](http://docs.spring.io/spring/docs/4.3.7.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-controller-advice)。 然后,ErrorController將接收任何未處理的異常。 ##### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#映射spring-mvc之外的錯誤頁面)映射Spring MVC之外的錯誤頁面 對于不使用Spring MVC的應用程序,可以使用ErrorPageRegistrar接口來直接注冊ErrorPages。這個抽象直接與底層的嵌入式servlet容器一起工作,即使沒有Spring MVC DispatcherServlet也可以工作。 ``` @Bean public ErrorPageRegistrar errorPageRegistrar(){ return new MyErrorPageRegistrar(); } // ... private static class MyErrorPageRegistrar implements ErrorPageRegistrar { @Override public void registerErrorPages(ErrorPageRegistry registry) { registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); } } ``` N.B. 如果您注冊一個最終由Filter過濾的路徑的ErrorPage(例如,像一些非Spring Web框架,例如Jersey和Wicket一樣),則必須將Filter顯式注冊為ERROR dispatcher,例如。 ``` @Bean public FilterRegistrationBean myFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new MyFilter()); ... registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class)); return registration; } ``` (默認的FilterRegistrationBean不包括ERROR dispatcher 類型)。 ##### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#websphere-application-server上的錯誤處理)WebSphere Application Server上的錯誤處理 當部署到servlet容器時,Spring Boot會使用其錯誤頁面過濾器將具有錯誤狀態的請求轉發到相應的錯誤頁面。 如果響應尚未提交,則該請求只能轉發到正確的錯誤頁面。 默認情況下,WebSphere Application Server 8.0及更高版本在成功完成servlet的服務方法后提交響應。 您應該通過將[com.ibm.ws](http://com.ibm.ws).webcontainer.invokeFlushAfterService設置為false來禁用此行為 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#27110-spring-hateoas)27.1.10 Spring HATEOAS 如果您正在開發一種利用超媒體的RESTful API,Spring Boot可以為Spring HATEOAS提供自動配置,適用于大多數應用程序。 自動配置取代了使用@EnableHypermediaSupport的需求,并注冊了一些Bean,以便輕松構建基于超媒體的應用程序,包括LinkDiscoverers(用于客戶端支持)和配置為將響應正確地組織到所需表示中的ObjectMapper。 ObjectMapper將根據spring.jackson。*屬性或Jackson2ObjectMapperBuilder bean(如果存在)進行自定義。 您可以使用@EnableHypermediaSupport控制Spring HATEOAS配置。 請注意,這將禁用上述ObjectMapper定制。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#27111-cors-支持)27.1.11 CORS 支持 [跨原始資源共享](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing/)(CORS)是[大多數瀏覽器](http://note.youdao.com/)實現的[W3C規范](http://caniuse.com/#feat=cors),允許您以靈活的方式指定什么樣的跨域請求被授權,而不是使用一些不太安全和不太強大的方法,如IFRAME或JSONP。 從版本4.2起,Spring MVC支持CORS開箱即用。 在Spring Boot應用程序中的controller方法使用@CrossOrigin注解的CORS配置不需要任何特定的配置。 可以通過使用自定義的addCorsMappings(CorsRegistry)方法注冊WebMvcConfigurer bean來定義全局CORS配置: ``` @Configuration public class MyConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**"); } }; } } ``` ### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#272-jax-rs-和-jersey)27.2 JAX-RS 和 Jersey 如果您喜歡JAX-RS編程模型的REST endpoints ,您可以使用一個可用的實現而不是Spring MVC。 如果您剛剛在應用程序上下文中注冊了一個@Bean的Servlet或Filter,那么Jersey 1.x和Apache CXF的功能非常出色。 Jersey2.x有一些本地Spring支持,所以我們也提供自動配置支持它在Spring Boot與啟動器。 要開始使用Jersey 2.x,只需將spring-boot-starter-jersey作為依賴項,然后您需要一個@Bean類型ResourceConfig,您可以在其中注冊所有端點(endpoints): ``` @Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(Endpoint.class); } } ``` > Jersey對掃描可執行檔案的包是相當有限的。 例如,當運行可執行的war文件時,它無法掃描在WEB-INF/classes中找到的包中的端點(endpoints)。 為了避免這種限制,不應使`packages`方法,并且應使用上述寄存器方法單獨注冊(register)端點。 您還可以注冊任意數量的ResourceConfigCustomizer的實現bean,以實現更高級的自定義。 所有注冊的端點都應為具有HTTP資源注解(@GET等)的@Components,例如。 ``` @Component @Path("/hello") public class Endpoint { @GET public String message() { return "Hello"; } } ``` 由于Endpoint是一個Spring @Component,所以Spring的生命周期由Spring管理,您可以使用@Autowired依賴關系并使用@Value注入外部配置。 默認情況下,Jersey servlet將被注冊并映射到/ *。 您可以通過將@ApplicationPath添加到ResourceConfig來更改映射。 默認情況下,Jersey將通過@Bean以名為jerseyServletRegistration的ServletRegistrationBean類型在Servlet進行設置。 默認情況下,servlet將被初始化,但是您可以使用spring.jersey.servlet.load-on-startup進行自定義。您可以通過創建一個自己的同名文件來禁用或覆蓋該bean。 您也可以通過設置spring.jersey.type = filter(在這種情況下,@Bean來替換或替換為jerseyFilterRegistration),使用Filter而不是Servlet。 servlet有一個@Order,您可以使用spring.jersey.filter.order設置。 可以使用spring.jersey.init.* 給出Servlet和過濾器注冊的init參數,以指定屬性的映射。 有一個[Jersey示例](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot-samples/spring-boot-sample-jersey),所以你可以看到如何設置。 還有一個[Jersey1.x示例](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot-samples/spring-boot-sample-jersey1)。 請注意,在Jersey1.x示例中,spring-boot maven插件已經被配置為打開一些Jersey jar,以便它們可以被JAX-RS實現掃描(因為示例要求它們在Filter注冊中進行掃描) 。 如果您的任何JAX-RS資源作為嵌套的jar打包,您可能需要執行相同操作。 ### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#273-嵌入式servlet容器支持)27.3 嵌入式servlet容器支持 Spring Boot包括對嵌入式Tomcat,Jetty和Undertow服務器的支持。 大多數開發人員將簡單地使用適當的“Starter”來獲取完全配置的實例。 默認情況下,嵌入式服務器將監聽端口8080上的HTTP請求。 > 如果您選擇在CentOS上使用Tomcat,請注意,默認情況下,臨時目錄用于存儲已編譯的JSP,文件上傳等。當您的應用程序正在運行導致故障時,該目錄可能會被tmpwatch刪除。 為了避免這種情況,您可能需要自定義tmpwatch配置,以便tomcat.*目錄不被刪除,或配置server.tomcat.basedir,以便嵌入式Tomcat使用不同的位置 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2731-servlets-filters-和-listeners)27.3.1 Servlets, Filters 和 listeners 當使用嵌入式servlet容器時,可以使用Spring bean或通過掃描Servlet組件(例如HttpSessionListener)注冊Servlet規范中的Servlet,過濾器和所有監聽器。 將Servlets,過濾器和監聽器注冊為Spring bean 任何Servlet,Filter或Servlet Listener 實例都會作為Spring bean注冊到嵌入式容器中。 可以非常方便地在配置過程中引用您的application.properties中的值。 默認情況下,如果容器中只包含一個Servlet,它將映射到/。 在多個Servlet bean的情況下,bean名稱將作為路徑前綴。 過濾器(Filters)將映射到/*,默認過濾所有請求。 如果基于慣例的映射不夠靈活,可以使用ServletRegistrationBean,FilterRegistrationBean和ServletListenerRegistrationBean類來完成控制。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2732-servlet-context-初始化)27.3.2 Servlet Context 初始化 嵌入式servlet容器不會直接執行Servlet 3.0+ javax.servlet.ServletContainerInitializer接口或Spring的org.springframework.web.WebApplicationInitializer接口。 這樣設計的目的旨在降低在war中運行的第三方庫破壞Spring Boot應用程序的風險。 如果您需要在Spring Boot應用程序中執行servlet context 初始化,則應注冊一個實現org.springframework.boot.context.embedded.ServletContextInitializer接口的bean。 單個onStartup方法提供對ServletContext的訪問,并且如果需要,可以輕松地用作現有WebApplicationInitializer的適配器。 掃描Servlet,過濾器和監聽器 使用嵌入式容器時,可以使用@ServletComponentScan啟用@WebServlet,@WebFilter和@WebListener注解類的自動注冊。 > @ServletComponentScan在獨立容器中不起作用,在該容器中將使用容器的內置發現機制。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2733-embeddedwebapplicationcontext)27.3.3 EmbeddedWebApplicationContext 在Spring Boot引導下,將會使用一種新類型的ApplicationContext來支持嵌入式的servlet容器。 EmbeddedWebApplicationContext是一種特殊類型的WebApplicationContext,它通過搜索單個EmbeddedServletContainerFactory bean來引導自身。 通常,TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory將被自動配置。 > 您通常不需要知道這些實現類。 大多數應用程序將被自動配置,并將代表您創建適當的ApplicationContext和EmbeddedServletContainerFactory。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2734-定制嵌入式servlet容器)27.3.4 定制嵌入式servlet容器 可以使用Spring Environment屬性配置常見的servlet容器設置。 通常您可以在application.properties文件中定義屬性。 常用服務器設置包括: * 網絡設置:偵聽端口的HTTP請求(server.port),接口地址綁定到server.address等。 * 會話設置:會話是否持久化(server.session.persistence),會話超時(server.session.timeout),會話數據的位置(server.session.store-dir)和session-cookie配置(server.session.cookie.*)。 * 錯誤管理:錯誤頁面的位置(server.error.path)等 * [SSL](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#howto-configure-ssl) * [HTTP壓縮](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#how-to-enable-http-response-compression) Spring Boot盡可能地嘗試公開常見設置,但并不總是可能的。 對于這些情況,專用命名空間提供服務器特定的定制(請參閱server.tomcat和server.undertow)。 例如,可以使用嵌入式servlet容器的特定功能來配置[訪問日志](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#howto-configure-accesslogs)。 > 有關完整列表,請參閱?[ServerProperties](https://github.com/spring-projects/spring-boot/tree/v1.5.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java)?類。 用程序定制 如果需要以編程方式配置嵌入式servlet容器,您可以注冊一個實現EmbeddedServletContainerCustomizer接口的Spring bean。 EmbeddedServletContainerCustomizer提供對ConfigurableEmbeddedServletContainer的訪問,其中包含許多自定義設置方法。 ``` import org.springframework.boot.context.embedded.*; import org.springframework.stereotype.Component; @Component public class CustomizationBean implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(9000); } } ``` 直接自定義ConfigurableEmbeddedServletContainer 如果上述定制技術有太多限制,您可以自己注冊TomcatEmbeddedServletContainerFactory,JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory bean。 ``` @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); factory.setPort(9000); factory.setSessionTimeout(10, TimeUnit.MINUTES); factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html")); return factory; } ``` setter方法提供了許多配置選項。 如果您需要做更多的自定義,還會提供幾種保護方法“鉤子”。 有關詳細信息,請參閱源代碼文檔。 #### [](file:///C:/Users/geekidentity/AppData/Local/Youdao/YNote/markdown/index.html#2735-jsp限制)27.3.5 JSP限制 當運行使用嵌入式servlet容器(并打包為可執行文檔)的Spring Boot應用程序時,對JSP支持有一些限制。 * 可以使用Tomcat和war包,即可執行的war將會起作用,并且也可以部署到標準容器(不限于但包括Tomcat)中。 由于Tomcat中的硬編碼文件模式,可執行的jar將無法正常工作。 * 可以使用Jetty和war包,即可執行的war將會起作用,并且也可以部署到任何標準的容器,它應該可以工作。 * Undertow不支持JSP。 * 創建自定義的error.jsp頁面將不會覆蓋默認視圖以進行[錯誤處理](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-error-handling),而應使用[自定義錯誤頁面](http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-error-handling-custom-error-pages)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看