This part of the reference documentation covers Spring Framework’s support for the presentation tier (and specifically web-based presentation tiers) including support for WebSocket-style messaging in web applications.
這部分文檔包含spring框架對於展示層的支持(並且特別指的是基於web的展示層)包括對於WebSocket風格的消息在一個web應用中。
Spring Framework’s own web framework, Spring Web MVC, is covered in the first couple of chapters. Subsequent chapters are concerned with Spring Framework’s integration with other web technologies, such as JSF.
spring框架自身的web框架,spring的web的mvc,是包含在章節的第一部分中。後續的章節包含了spring集成其他的web技術,例如JSF。
Following that is coverage of Spring Framework’s MVC portlet framework.
下面覆蓋了spring框架mvc的指導框架。
The section then concludes with comprehensive coverage of the Spring Framework Chapter 26, WebSocket Support (including Section 26.4, 「STOMP Over WebSocket Messaging Architecture」).
章節包含複雜的有關spring框架的26章節(包括章節26.4,「STOMP關於WebSocket消息的架構」)
Chapter 22, Web MVC framework
Chapter 23, View technologies
Chapter 24, Integrating with other web frameworks
Chapter 25, Portlet MVC Framework
Chapter 26, WebSocket Support
web mvc框架
22.1 Introduction to Spring Web MVC framework
介紹spring的web mvc框架
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale, time zone and theme resolution as well as support for uploading files. The default handler is based on the @Controller and @RequestMapping annotations, offering a wide range of flexible handling methods. With the introduction of Spring 3.0, the @Controller mechanism also allows you to create RESTful Web sites and applications, through the @PathVariable annotation and other features.
spring的web 模型-視圖-控制(MVC)框架設計圍繞着DispatcherServlet來分發請求給處理器,配置處理器映射、視圖處理、位置、失去和主題解決方案以及對於上傳文件的支持。默認的處理器基於@Controller和@RequestMapping註解,提供了廣泛的方便的處理方式。在spring的3.0中被引入,@Controller策略允許你創建RESTful風格的web站點和應用通過@PathVariable註解和其他特性。
"Open for extension…" A key design principle in Spring Web MVC and in Spring in general is the "Open for extension, closed for modification" principle.
「對擴展開發。。。」一個關鍵的設計理念在spring的web的mvc中並且通常在spring中是說「對於擴展開發,對於修改關閉」原則。
Some methods in the core classes of Spring Web MVC are marked final. As a developer you cannot override these methods to supply your own behavior. This has not been done arbitrarily, but specifically with this principle in mind.
一些在spring的web的mvc中的核心類是final的。作爲開發者你不應該重寫這些方法來支持你自己的行爲。這不是一種武斷,但是請記住這些原則。
For an explanation of this principle, refer to Expert Spring Web MVC and Web Flow by Seth Ladd and others; specifically see the section "A Look At Design," on page 117 of the first edition. Alternatively, see
對於這個原則的解釋,請參考Expert Spring Web MVC and Web Flow,作者Seth Ladd等,尤其是章節「A Look At Design」在第一版的117頁。也可以看
Bob Martin, The Open-Closed Principle (PDF)
You cannot add advice to final methods when you use Spring MVC. For example, you cannot add advice to the AbstractController.setSynchronizeOnSession() method. Refer to Section 11.6.1, 「Understanding AOP proxies」 for more information on AOP proxies and why you cannot add advice to final methods.
你不能添加advice對於final方法當你使用spring的mvc時。例如,你不能添加advice對於AbstractController.setSynchronizeOnSession()方法。參考11.6.1節,「理解AOP代理」來了解更多AOP代理及爲什麼你不能添加advice對於final方法。
In Spring Web MVC you can use any object as a command or form-backing object; you do not need to implement a framework-specific interface or base class. Spring’s data binding is highly flexible: for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. Thus you do not need to duplicate your business objects' properties as simple, untyped strings in your form objects simply to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects.
在spring的web的mvc中你可以使用任何object作爲命令或支持的object,你不需要實現指定框架接口或基類。spring的數據綁定是高度自由的,例如,他處理類型匹配錯誤做爲驗證錯誤可以被應用處理,不是作爲系統錯誤。你不需要重複定義你的業務object屬性作爲簡單無類型的字符串在你的object來處理不合法的分配或適當的轉換String。作爲替代,可以直接綁定你的業務object。
Spring’s view resolution is extremely flexible. A Controller is typically responsible for preparing a model Map with data and selecting a view name but it can also write directly to the response stream and complete the request. View name resolution is highly configurable through file extension or Accept header content type negotiation, through bean names, a properties file, or even a custom ViewResolver implementation. The model (the M in MVC) is a Map interface, which allows for the complete abstraction of the view technology. You can integrate directly with template based rendering technologies such as JSP, Velocity and Freemarker, or directly generate XML, JSON, Atom, and many other types of content. The model Map is simply transformed into an appropriate format, such as JSP request attributes, a Velocity template model.
spring的視圖處理是很方便的。一個控制器通常準備一個model的Map包含數據和視圖名但是也可以直接是返回流和完整的請求。視圖名可以配置通過文件擴展名或接受投上下文類型通過bean的名字、一個屬性文件或自定義的ViewResolver實現。模型(MVC中的M)是一個Map接口,允許完整的視圖技術抽象。你可以直接集成基於模板的技術如JSP、Velocity和Freemarker或直接生成XML、JSON、Atom和許多內容。model的映射可以簡單轉換爲適當的形式,例如JSP請求屬性,一個Velocity的模板模型。
22.1.1 Features of Spring Web MVC
spring的web的mvc的特性
Spring Web Flow
spring的web流
Spring Web Flow (SWF) aims to be the best solution for the management of web application page flow.
swf目的是對於web應用頁面流實現最好的解決方案。
SWF integrates with existing frameworks like Spring MVC and JSF, in both Servlet and Portlet environments. If you have a business process (or processes) that would benefit from a conversational model as opposed to a purely request model, then SWF may be the solution.
swf集成已有的框架例如spring的mvc和JSF,包括在Servlet和可變的環境中。如果你有一個業務處理(或多個處理)將從轉換模型中獲益作爲純淨的請求模型,swf可以是一種方案。
SWF allows you to capture logical page flows as self-contained modules that are reusable in different situations, and as such is ideal for building web application modules that guide the user through controlled navigations that drive business processes.
swf允許你來抓取邏輯頁面根據自包含的模塊可以在不同的情況下重用,例如構建理想的web應用模塊指導用戶通過控制導航對於業務的流程。
For more information about SWF, consult the Spring Web Flow website.
關於更多有關swf的信息,參考spring的web流站點。
Spring’s web module includes many unique web support features:
spring的web模塊包括許多獨立的web支持特性:
Clear separation of roles. Each role?—?controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, and so on?—?can be fulfilled by a specialized object.
清晰的角色劃分。每個角色————控制器、驗證器、命令object、form的object、模型object、DispatcherServlet、處理匹配、視圖解析等等————可以實現通過指定的object。
Powerful and straightforward configuration of both framework and application classes as JavaBeans. This configuration capability includes easy referencing across contexts, such as from web controllers to business objects and validators.
有力和直接的配置框架和應用類作爲JavaBean。這個配置能力包括簡單的引用跨越上下文,例如從web控制器到業務邏輯和驗證。
Adaptability, non-intrusiveness, and flexibility. Define any controller method signature you need, possibly using one of the parameter annotations (such as @RequestParam, @RequestHeader, @PathVariable, and more) for a given scenario.
適應力、沒有侵入性、方便的。定義任何控制器方法根據你的需要,使用參數註解中的一個(例如@RequestParam、@RequestHeader、@PathVariable等等)對於給定的場景。
Reusable business code, no need for duplication. Use existing business objects as command or form objects instead of mirroring them to extend a particular framework base class.
重用業務代碼,不需要重複。使用已有的業務object作爲命令或form的object鏡像他們來執行特定框架基類。
Customizable binding and validation. Type mismatches as application-level validation errors that keep the offending value, localized date and number binding, and so on instead of String-only form objects with manual parsing and conversion to business objects.
自定義綁定和驗證。類型不匹配例如應用層驗證錯誤可以保持錯誤的值、日期和數值綁定等等來代替字符串————只有form的object使用手動解析和轉換對於業務object。
Customizable handler mapping and view resolution. Handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. Spring is more flexible than web MVC frameworks that mandate a particular technique.
自定義處理器匹配和視圖處理。處理器匹配和視圖解析策略來自簡單的基於URL的配置,對於複雜的、構建目標的解決策略。spring是很方便的比web的mvc框架授權一個特定的技術。
Flexible model transfer. Model transfer with a name/value Map supports easy integration with any view technology.
方便的模型轉換。模型轉換使用name/value的Map支持簡單的集成視圖技術。
Customizable locale, time zone and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, and so on.
自定義位置、時區和主題,支持JSP或不使用spring的標籤庫,支持JSTL,支持Velocity不需要額外的支持等等。
A simple yet powerful JSP tag library known as the Spring tag library that provides support for features such as data binding and themes. The custom tags allow for maximum flexibility in terms of markup code. For information on the tag library descriptor, see the appendix entitled Chapter 43, spring JSP Tag Library
一個簡單有用的JSP標籤庫被知道是spring的標籤庫提供支持對於特性例如數據綁定和主題。自定義標籤允許最大限度的自由在標記代碼方面。關於標籤描述的更多內容,見43章節,spring的標籤庫。
A JSP form tag library, introduced in Spring 2.0, that makes writing forms in JSP pages much easier. For information on the tag library descriptor, see the appendix entitled Chapter 44, spring-form JSP Tag Library
一個來自標籤庫的JSP,在spring2.0中被引入,使得更加簡單的書寫JSP頁面。對於標籤庫描述符的更多信息,見章節44,spring風格的JSP標籤庫。
Beans whose lifecycle is scoped to the current HTTP request or HTTP Session. This is not a specific feature of Spring MVC itself, but rather of the WebApplicationContext container(s) that Spring MVC uses. These bean scopes are described in Section 7.5.4, 「Request, session, global session, application, and WebSocket scopes」
bean的生命週期如果是當前HTTP請求或HTTP會話。不是spring的mvc本身的特定特性,但不是springmvc使用的WebApplicationContext容器。bean的範圍描述在7.5.4章節,「請求、會話、全局會話、application和WebSocket範圍」。
22.1.2 Pluggability of other MVC implementations
其他mvc實現的可插拔性
Non-Spring MVC implementations are preferable for some projects. Many teams expect to leverage their existing investment in skills and tools, for example with JSF.
非springmvc實現對於一些項目會更好。許多小組期望利用他們已經存在的技能和工具,例如JSF。
If you do not want to use Spring’s Web MVC, but intend to leverage other solutions that Spring offers, you can integrate the web MVC framework of your choice with Spring easily. Simply start up a Spring root application context through its ContextLoaderListener, and access it through its ServletContext attribute (or Spring’s respective helper method) from within any action object. No "plug-ins" are involved, so no dedicated integration is necessary. From the web layer’s point of view, you simply use Spring as a library, with the root application context instance as the entry point.
如果你不希望使用spring的web的mvc,但是試圖利用其他spring提供的解決方案,你可以集成web mvc框架通過使用你的選擇配合spring。簡單的設置spring的根應用上下文通過他的ContextLoaderListener並且訪問他通過ServletContext屬性(或spring的各自助手方法)在任何action object中。沒有插件被引入因此不需要專有的集成。根據web層的觀點,你可以將spring當作一個庫來使用,配合根應用上下文實例作爲整個點。
Your registered beans and Spring’s services can be at your fingertips even without Spring’s Web MVC. Spring does not compete with other web frameworks in this scenario. It simply addresses the many areas that the pure web MVC frameworks do not, from bean configuration to data access and transaction handling. So you can enrich your application with a Spring middle tier and/or data access tier, even if you just want to use, for example, the transaction abstraction with JDBC or Hibernate.
你註冊bean並且spring的服務可以在你的附近甚至不需要spring的web的mvc。spring在這種情況不會與其他web框架競爭。他簡單的指示許多位置有些純淨的web的mvc框架不會有,來自bean的配置用於數據訪問和事務處理。因此你可以豐富你的應用使用spring的中間層或數據訪問層,即使你只是使用他們,例如,JDBC或Hibernate的事務翻譯。
22.2 The DispatcherServlet
Spring’s web MVC framework is, like many other web MVC frameworks, request-driven, designed around a central Servlet that dispatches requests to controllers and offers other functionality that facilitates the development of web applications. Spring’s DispatcherServlet however, does more than just that. It is completely integrated with the Spring IoC container and as such allows you to use every other feature that Spring has.
spring的web的mvc框架是,像許多其他的web的mvc框架,基於請求,設計一箇中間的servlet用於分發請求到控制器並且提供其他功能促進web應用的開發。spring的DispatcherServlet做的更多。他完全集成了IOC容器並且允許使用任何spring的特性。
The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram. The pattern-savvy reader will recognize that the DispatcherServlet is an expression of the "Front Controller" design pattern (this is a pattern that Spring Web MVC shares with many other leading web frameworks).
spring的web mvc的DispatcherServlet的請求處理工作流是展示在下面的圖片中的。對於模式理解的讀者將意識到DispatcherServlet是一個「前端控制器」設計模式的表達(這是一個設計模式,spring web mvc框架想起和其他許多web框架共享使用)
Figure 22.1. The request processing workflow in Spring Web MVC (high level)
圖22.1。在spring web mvc中請求處理工作流(高級)
The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is declared in your web application. You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping. Here is a standard Java EE Servlet configuration in a Servlet 3.0+ environment:
DispatcherServlet是一個實際的servlet(他繼承自HttpServlet基類),並且定義在你的web應用中。你需要映射你希望DispatcherServlet來處理的請求,通過使用URL匹配。這裏給出一個標準JavaEE的Servlet配置在Servlet3.0以上的環境中:
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
ServletRegistration.Dynamic registration = container.addServlet("example", new DispatcherServlet());
registration.setLoadOnStartup(1);
registration.addMapping("/example/*");
}
}
In the preceding example, all requests starting with /example will be handled by the DispatcherServlet instance named example.
在之前的例子中,所有的請求以/example開始的都會被DispatcherServlet實例來處理。
WebApplicationInitializer is an interface provided by Spring MVC that ensures your code-based configuration is detected and automatically used to initialize any Servlet 3 container. An abstract base class implementation of this interface named AbstractAnnotationConfigDispatcherServletInitializer makes it even easier to register the DispatcherServlet by simply specifying its servlet mapping and listing configuration classes - it’s even the recommended way to set up your Spring MVC application. See Code-based Servlet container initialization for more details.
WebApplicationInitializer是一個接口由spring mvc提供保證你的基於代碼的配置被自動探測並且被使用來初始化任何Servlet3容器。一個抽象基類實現這個接口是AbstractAnnotationConfigDispatcherServletInitializer使得他可以更加簡單被註冊DispatcherServlet通過簡單指定他的servlet映射和監聽器配置類————他甚至推薦設置你的spring mvc應用。見基於代碼的Servlet容器初始化的更多內容。
The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is declared in the web.xml of your web application. You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the same web.xml file. This is standard Java EE Servlet configuration; the following example shows such a DispatcherServlet declaration and mapping:
DispatcherServlet是一個實際的Servlet(他繼承自HttpServlet基類),並且指定在你的web應用的web.xml文件中。你需要匹配你的請求當你希望DispatcherServlet來處理的時候,通過使用URL匹配在相同的web.xml文件中。這是標準的JavaEE的Servlet配置,後面的例子展示了這樣一個DispatcherServlet聲明和匹配。
Below is the web.xml equivalent of the above code based example:
下面的web.xml相當於上面的基於代碼的例子:
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/example/*</url-pattern>
</servlet-mapping>
</web-app>
As detailed in Section 7.15, 「Additional Capabilities of the ApplicationContext」, ApplicationContext instances in Spring can be scoped. In the Web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. The root WebApplicationContext should contain all the infrastructure beans that should be shared between your other contexts and Servlet instances. These inherited beans can be overridden in the servlet-specific scope, and you can define new scope-specific beans local to a given Servlet instance.
詳細細節在7.15章節,「ApplicationContext」的額外功能」,ApplicationContext實例在spring中是可以指定範文的。在web mvc框架中,每個DispatcherServlet有其自己的WebApplicationContext,繼承所有的已經定義的bean在根WebApplicationContext中。根WebApplicationContext應當包含所有的基礎bean應當被共享在你的其他上下文和Servlet實例之間。這些集成bean可以被覆蓋在特定的servlet範圍中,並且你可以定義新的指定範圍的bean根據給定的Servlet實例。
Figure 22.2. Typical context hierarchy in Spring Web MVC
圖22.2,典型的上下文結構咋spring的web mvc中
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.
上面DispatcherServlet的初始化,spring mvc查找一個文件名字爲[servlet-name]-servlet.xml在你web應用的WEB-INF文件並且創建定義在那裏的bean,覆蓋任何bean定義在全局的範圍的同名bean定義。
Consider the following DispatcherServlet Servlet configuration (in the web.xml file):
考慮下面的DispatcherServlet的Servlet配置(在web.xml文件中)
<web-app>
<servlet>
<servlet-name>golfing</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>golfing</servlet-name>
<url-pattern>/golfing/*</url-pattern>
</servlet-mapping>
</web-app>
With the above Servlet configuration in place, you will need to have a file called /WEB-INF/golfing-servlet.xml in your application; this file will contain all of your Spring Web MVC-specific components (beans). You can change the exact location of this configuration file through a Servlet initialization parameter (see below for details).
使用上面的Servlet配置,你將需要有一個文件名字爲/WEB-INF/golfing-servlet.xml在你的應用中;這個文件包含了你的spring的web指定mvc組件(bean)。你可以改變這個配置文件的實際位置通過Servlet初始化參數(見如下)
It is also possible to have just one root context for single DispatcherServlet scenarios.
他也可以有一個根上下文對於單個DispatcherServlet場景。
Figure 22.3. Single root context in Spring Web MVC
圖22.3,單根上下文在spring的web mvc中
This can be configured by setting an empty contextConfigLocation servlet init parameter, as shown below:
這個可以被配置通過設置一個空的contextConfigLocation的Servlet初始化參數,展示如下:
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Section 22.9, 「Using themes」), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.
WebApplicationContext是一個普通ApplicationContext的擴展有一些額外的特性對於web應用是必須的。他和普通的ApplicationContext不同,他可以處理主題(見章節22.9,「使用主題」),並且他可以被servlet知道並連接(通過有一個到ServletContext的連接)。WebApplicationContext被綁定到ServletContext中,通過使用靜態方法在RequestContextUtils類你可以查找WebApplicationContext如果你需要訪問他的話。
Note that we can achieve the same with java-based configurations:
注意我們可以使用相同的基於java的配置。
public class GolfingWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
// GolfingAppConfig defines beans that would be in root-context.xml
return new Class[] { GolfingAppConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
// GolfingWebConfig defines beans that would be in golfing-servlet.xml
return new Class[] { GolfingWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/golfing/*" };
}
}
22.2.1 Special Bean Types In the WebApplicationContext
在WebApplicationContext中指定bean的類型
The Spring DispatcherServlet uses special beans to process requests and render the appropriate views. These beans are part of Spring MVC. You can choose which special beans to use by simply configuring one or more of them in the WebApplicationContext. However, you don’t need to do that initially since Spring MVC maintains a list of default beans to use if you don’t configure any. More on that in the next section. First see the table below listing the special bean types the DispatcherServlet relies on.
spring的DispatcherServlet使用指定的bean來處理請求和解析適當的視圖。這些bean作爲spring mvc的一部分。你可以選擇指定bean來使用通過簡單的配置一個或多個在WebApplicationContext中。然而,你不需要最初這麼做自從spring mvc包含了一個列表關於使用的默認bean如果你沒有配置的話。在下一章節中會有介紹。首先讓我們看一下下面的表格列出了DispatcherServlet依賴的指定bean的類型。
Table 22.1. Special bean types in the WebApplicationContext
表格22.1,在WebApplicationContext中指定的bean類型
Bean type bean類型 |
Explanation 解釋 |
Maps incoming requests to handlers and a list of pre- and post-processors (handler interceptors) based on some criteria the details of which vary by HandlerMapping implementation. The most popular implementation supports annotated controllers but other implementations exists as well. 映射捕獲請求給處理器並且前或後的攔截器基於一些標準的處理根據不同的HandlerMapping的實現。最流行的實現支持註解控制但是其他實現也是存在的。 |
|
HandlerAdapter |
Helps the DispatcherServlet to invoke a handler mapped to a request regardless of the handler is actually invoked. For example, invoking an annotated controller requires resolving various annotations. Thus the main purpose of a HandlerAdapter is to shield the DispatcherServlet from such details. 幫助DispatcherServlet來調用一個處理對於一個請求的映射而不是實際的處理器的調用。例如,調用一個註解控制器要求解析不同的註解。HandlerAdapter的主要目的是屏蔽一些DispatcherServlet的細節。 |
Maps exceptions to views also allowing for more complex exception handling code. 映射對於視圖的異常運行較複雜的異常處理代碼。 |
|
Resolves logical String-based view names to actual View types. 處理邏輯字符串基於視圖名對於實際的視圖類型 |
|
LocaleResolver & LocaleContextResolver |
Resolves the locale a client is using and possibly their time zone, in order to be able to offer internationalized views 處理客戶端的位置被用於和可能的時區,用於提供國際化的視圖 |
Resolves themes your web application can use, for example, to offer personalized layouts 處理你web應用可以使用的主題,例如,提供獨立的表示 |
|
Parses multi-part requests for example to support processing file uploads from HTML forms. 解析多部分請求例如來支持處理文件上傳來自HTML的表單。 |
|
Stores and retrieves the "input" and the "output" FlashMap that can be used to pass attributes from one request to another, usually across a redirect. 存儲和獲得輸入和輸出的FlashMap可以用於傳遞屬性從一個請求到另一個請求,通常是跨越轉發的。 |
22.2.2 Default DispatcherServlet Configuration
默認的DispatcherServlet配置
As mentioned in the previous section for each special bean the DispatcherServlet maintains a list of implementations to use by default. This information is kept in the file DispatcherServlet.properties in the package org.springframework.web.servlet.
就像之前每個特定bean提到的DispatcherServlet維持默認的實現列表。這個信息保存在文件DispatcherServlet.properties中在org.springframework.web.servlet包中。
All special beans have some reasonable defaults of their own. Sooner or later though you’ll need to customize one or more of the properties these beans provide. For example it’s quite common to configure an InternalResourceViewResolver settings its prefix property to the parent location of view files.
所有的特殊的bean有一些原因默認。遲早你會需要自定義一個或多個這些bean提供的屬性。例如,通常配置一個InternalResourceViewResolver設置它的前綴對於視圖文件的父位置。
Regardless of the details, the important concept to understand here is that once you configure a special bean such as an InternalResourceViewResolver in your WebApplicationContext, you effectively override the list of default implementations that would have been used otherwise for that special bean type. For example if you configure an InternalResourceViewResolver, the default list of ViewResolver implementations is ignored.
儘管細節,重要的概念在這裏需要理解是一旦你配置了指定bean的屬性例如在你的web應用中的InternalResourceViewResolver,你影響的是默認實現列表將使用指定的bean類型。例如,如果你配置了一個InternalResourceViewResolver,默認的ViewResolver的列表會被忽略。
In Section 22.16, 「Configuring Spring MVC」 you’ll learn about other options for configuring Spring MVC including MVC Java config and the MVC XML namespace both of which provide a simple starting point and assume little knowledge of how Spring MVC works. Regardless of how you choose to configure your application, the concepts explained in this section are fundamental should be of help to you.
在章節22.16中,「配置spring的mvc」你將瞭解其他選項有關配置spring mvc包括mvc java配置和mvc xml命名空間提供簡單的開始點和假設一點spring mvc的知識就可以工作。儘管你選擇配置你的應用,在這節中解釋的觀點基本會幫助到你。
22.2.3 DispatcherServlet Processing Sequence
DispatcherServlet處理順序
After you set up a DispatcherServlet, and a request comes in for that specific DispatcherServlet, the DispatcherServlet starts processing the request as follows:
在你設置一個DispatcherServlet之後,並且一個請求到來對於指定的DispatcherServlet,DispatcherServlet開始處理一個請求如下:
The WebApplicationContext is searched for and bound in the request as an attribute that the controller and other elements in the process can use. It is bound by default under the key DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE.
WebApplicationContext被查找和綁定在請求中作爲一個屬性使得控制器和其他處理中的元素可以使用。他綁定默認在關鍵的DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE中。
The locale resolver is bound to the request to enable elements in the process to resolve the locale to use when processing the request (rendering the view, preparing data, and so on). If you do not need locale resolving, you do not need it.
位置處理器綁定到請求中允許元素在處理中處理使用的位置當處理請求時(解析視圖、處理數據等等)。如果你不需要位置解析,你可以不需要他。
The theme resolver is bound to the request to let elements such as views determine which theme to use. If you do not use themes, you can ignore it.
主題接替綁定到請求中使得元素例如視圖決定應該使用的主題。如果你不需要使用主題,你可以忽略他。
If you specify a multipart file resolver, the request is inspected for multiparts; if multiparts are found, the request is wrapped in a MultipartHttpServletRequest for further processing by other elements in the process. See Section 22.10, 「Spring’s multipart (file upload) support」 for further information about multipart handling.
如果你指定多個文件解析器,請求是檢查多個部分,如果多個部分被檢查到,請求被包裹在一個MultipartHttpServletRequest對於更進一步的處理通過其他的元素在過程中。見22.10章節,「spring的多部分(文件上傳)支持」來了解更多信息有關多部分處理。
An appropriate handler is searched for. If a handler is found, the execution chain associated with the handler (preprocessors, postprocessors, and controllers) is executed in order to prepare a model or rendering.
查找適當的處理器。如果一個處理器被找到,執行鏈連接處理器(處理器、後處理器和控制器)被按順序執行來準備一個模型或解析。
If a model is returned, the view is rendered. If no model is returned, (may be due to a preprocessor or postprocessor intercepting the request, perhaps for security reasons), no view is rendered, because the request could already have been fulfilled.
如果一個模型被返回,視圖被解析。如果沒有模型被返回,(或許由於前處理器或後處理器攔截了請求,或者安全原因),沒有試圖被解析,應爲請求已經被處理了。
Handler exception resolvers that are declared in the WebApplicationContext pick up exceptions that are thrown during processing of the request. Using these exception resolvers allows you to define custom behaviors to address exceptions.
處理異常解析定義在WebApplicationContext獲得異常在處理請求時被拋出。使用這些異常解析允許你來定義自定義行爲來處理異常。
The Spring DispatcherServlet also supports the return of the last-modification-date, as specified by the Servlet API. The process of determining the last modification date for a specific request is straightforward: the DispatcherServlet looks up an appropriate handler mapping and tests whether the handler that is found implements the LastModified interface. If so, the value of the long getLastModified(request) method of the LastModified interface is returned to the client.
spring的DispatcherServlet也支持返回最後修改日期,通過Servlet的API來定義。決定最後修改日期的處理對於特定的請求是直接的,DispatcherServlet查找一個適當的處理映射和測試當處理查找實現LastModified接口。如果這麼做,getLastModified(request)方法的返回值被返回給客戶端。
You can customize individual DispatcherServlet instances by adding Servlet initialization parameters ( init-param elements) to the Servlet declaration in the web.xml file. See the following table for the list of supported parameters.
你可以自定義獨立的DispatcherServlet實例通過添加Servlet的初始化參數(init-param元素)對於servlet定義在web.xml文件中。見下面支持參數的表格。
Table 22.2. DispatcherServlet initialization parameters
表格22.2,DispatcherServlet初始化參數
Parameter 參數 |
Explanation 解釋 |
contextClass |
Class that implements WebApplicationContext, which instantiates the context used by this Servlet. By default, the XmlWebApplicationContext is used. 類實現了WebApplicationContext,指定了被這個servlet使用的上下文。默認情況下,使用XmlWebApplicationContext。 |
contextConfigLocation |
String that is passed to the context instance (specified by contextClass) to indicate where context(s) can be found. The string consists potentially of multiple strings (using a comma as a delimiter) to support multiple contexts. In case of multiple context locations with beans that are defined twice, the latest location takes precedence. 傳遞給上下文實例的字符串(通過contextClass來指定)來指示可以被找到的上下文。字符串包括潛在的多字符串(使用逗號分隔)來支持多個上下文。由於多個上下文路徑bean被定義兩次,最後定義的優先級最高。 |
namespace |
Namespace of the WebApplicationContext. Defaults to [servlet-name]-servlet. WebApplicationContext的命名空間,默認是[servlet-name]-servlet |
22.3 Implementing Controllers
實現控制器
Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.
控制器提供訪問對於應用的行爲你通常定義通過一個服務接口。控制器攔截用戶的輸入並轉換爲一個模型被視圖來使用。spring實現一個控制器以非常抽象的形式,允許你來創建一個不同的控制器。
Spring 2.5 introduced an annotation-based programming model for MVC controllers that uses annotations such as @RequestMapping, @RequestParam, @ModelAttribute, and so on. This annotation support is available for both Servlet MVC and Portlet MVC. Controllers implemented in this style do not have to extend specific base classes or implement specific interfaces. Furthermore, they do not usually have direct dependencies on Servlet or Portlet APIs, although you can easily configure access to Servlet or Portlet facilities.
spring2.5引入了一個基於註解的編程模型對於mvc的控制器使用註解例如@RequestMapping、@RequestParam、@ModelAttribute等等。註解執行對於Servlet mvc和porlet mvc。控制器實現以這樣的風格不需要繼承特定的基類或引入特定的接口。此外,他們不需要直接依賴於servlet或移動API,使得你可以簡單的配置Servlet和Portlet設施。
[Tip]
提示
Available in the spring-projects Org on Github, a number of web applications leverage the annotation support described in this section including MvcShowcase, MvcAjax, MvcBasic, PetClinic, PetCare, and others.
在spring項目org的github主頁,很多web應用利用的註解支持描述這個章節的內容包括MvcShowcase、MvcAjax、MvcBasic、PetClinic、PetCare等等。
@Controller
public class HelloWorldController {
@RequestMapping("/helloWorld")
public String helloWorld(Model model) {
model.addAttribute("message", "Hello World!");
return "helloWorld";
}
}
As you can see, the @Controller and @RequestMapping annotations allow flexible method names and signatures. In this particular example the method accepts a Model and returns a view name as a String, but various other method parameters and return values can be used as explained later in this section. @Controller and @RequestMapping and a number of other annotations form the basis for the Spring MVC implementation. This section documents these annotations and how they are most commonly used in a Servlet environment.
就像你看到的,@Controller和@RequestMapping註解允許方便的方法名和簽名。在這特殊的例子中,方法接收一個Model並返回一個視圖名字的字符串,但是多個其他方法參數和返回值可以被使用會在後面的章節中說明。@Controller和@RequestMapping和一些其他的註解來自基本spring的mvc的實現。這節說明了註解和他們是如何使用在servlet環境中的。
22.3.1 Defining a controller with @Controller
使用@Controller來定義一個控制器
The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API. However, you can still reference Servlet-specific features if you need to.
@Controller註解指示了一個特定的類作爲一個控制器來工作。spring沒有要求你來擴展任何控制器基類或引用Servlet的API。然而,你依然可以引用指定Servlet的特性如果你需要的話。
The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations (see the next section).
@Controller註解扮演一個模板的角色對於註解類。dispatcher掃描這樣的註解類對於匹配方法和探測@RequestMapping註解(見下一節)。
You can define annotated controller beans explicitly, using a standard Spring bean definition in the dispatcher’s context. However, the @Controller stereotype also allows for autodetection, aligned with Spring general support for detecting component classes in the classpath and auto-registering bean definitions for them.
你可以直接定義註解控制器bean,使用一個標準的spring的bean定義在dispatcher的上下文中。然而,@Controller依然允許自動探測,可以和spring的通用支持對於探測組件類在類路徑和爲他們自動註冊bean定義。
To enable autodetection of such annotated controllers, you add component scanning to your configuration. Use the spring-context schema as shown in the following XML snippet:
爲了允許自動探測這樣的註解控制器,你添加組件掃描對於你的配置。使用spring-context的schema展示在下面的xml片段中:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>
<!-- ... -->
</beans>
22.3.2 Mapping Requests With @RequestMapping
使用@RequestMapping來匹配請求
You use the @RequestMapping annotation to map URLs such as /appointments onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping for a specific HTTP method request method ("GET", "POST", etc.) or an HTTP request parameter condition.
你使用@RequestMapping註解來匹配URL類似於/appointments和整個類或特殊的處理方法。通常類級別的註解匹配一個請求路徑(或路徑模式)對於一個控制器,此外方法級別的註解縮小了主匹配對於特定的HTTP方法請求方法(GET、POST等等)或一個HTTP請求參數條件。
The following example from the Petcare sample shows a controller in a Spring MVC application that uses this annotation:
下面的例子來自Petcare例子展示了一個控制器在spring的mvc應用中使用這個註解:
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
@Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
@RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
@RequestMapping(path = "/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}
@RequestMapping(path = "/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
}
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}
In the above example, @RequestMapping is used in a number of places. The first usage is on the type (class) level, which indicates that all handler methods in this controller are relative to the /appointments path. The get() method has a further @RequestMapping refinement: it only accepts GET requests, meaning that an HTTP GET for /appointments invokes this method. The add() has a similar refinement, and the getNewForm() combines the definition of HTTP method and path into one, so that GET requests for appointments/new are handled by that method.
在上面的例子中,@RequestMapping被用於很多位置。第一種用法是在類級別,指示所有的請求方法在這個控制器中都是相對於/appointments路徑的。get方法返回一個@RequestMapping:他只接受get請求,意味着HTTP的get請求對於/appointments會調用這個方法。add有相同的簽名,並且getNewForm組合定義了HTTP方法和李靜,因此get請求對於appointments/new會被這個方法來處理。
The getForDay() method shows another usage of @RequestMapping: URI templates. (See the section called 「URI Template Patterns」).
getForDay方法展示了另一種@RequestMapping的用法:URI模板。(見章節「URI模板形式」)
A @RequestMapping on the class level is not required. Without it, all paths are simply absolute, and not relative. The following example from the PetClinic sample application shows a multi-action controller using @RequestMapping:
@RequestMapping在類的級別是不必須的。不使用的話,所有的路徑是簡單的絕對路徑而不是相對的。下面的例子來自PetClinic樣例應用展示了多行爲的控制器使用@RequestMapping:
@Controller
public class ClinicController {
private final Clinic clinic;
@Autowired
public ClinicController(Clinic clinic) {
this.clinic = clinic;
}
@RequestMapping("/")
public void welcomeHandler() {
}
@RequestMapping("/vets")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
}
The above example does not specify GET vs. PUT, POST, and so forth, because @RequestMapping maps all HTTP methods by default. Use @RequestMapping(method=GET) or @GetMapping to narrow the mapping.
上面的例子沒有指定GET、PUT、POST等等,因爲@RequestMapping默認匹配所有的http方法。使用@RequestMapping(method=GET)或@GetMapping來縮小匹配。
Composed @RequestMapping Variants
組合@RequestMapping變量
Spring Framework 4.3 introduces the following method-level composed variants of the @RequestMapping annotation that help to simplify mappings for common HTTP methods and better express the semantics of the annotated handler method. For example, a @GetMapping can be read as a GET @RequestMapping.
spring框架4.3引入了下面的方法級別的組合變量對於@RequestMapping註解來幫助簡單的匹配通用的http方法和較好的展示註解處理方法的語義。例如,@GetMapping可以處理get方式的@RequestMapping。
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
The following example shows a modified version of the AppointmentsController from the previous section that has been simplified with composed @RequestMapping annotations.
下面的例子展示了一個修改版本的AppointmentsController來自前面的章節使用了簡單組合@RequestMapping註解。
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private final AppointmentBook appointmentBook;
@Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}
@GetMapping
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}
@GetMapping("/{day}")
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}
@GetMapping("/new")
public AppointmentForm getNewForm() {
return new AppointmentForm();
}
@PostMapping
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}
@Controller and AOP Proxying
@Controller和AOP代理
In some cases a controller may need to be decorated with an AOP proxy at runtime. One example is if you choose to have @Transactional annotations directly on the controller. When this is the case, for controllers specifically, we recommend using class-based proxying. This is typically the default choice with controllers. However if a controller must implement an interface that is not a Spring Context callback (e.g. InitializingBean, *Aware, etc), you may need to explicitly configure class-based proxying. For example with <tx:annotation-driven/>, change to <tx:annotation-driven proxy-target-class="true"/>.
在一些情況一個控制器需要被修飾爲aop代理在運行時。一個例子是如果你選擇@Transactional註解直接來修飾控制器。當是這種情況,對於指定的控制器,我們建議使用基於類的代理。通常默認是控制器默認的選項。然而如果一個控制器必須實現接口而不是spring上下文的回調(例如,InitializingBean、*Aware等等),你可能需要直接配置基於類的代理。例如,使用<tx:annotation-driven/>,換爲<tx:annotation-driven proxy-target-class="true"/>。
New Support Classes for @RequestMapping methods in Spring MVC 3.1
在spring的mvc3.1中對於@RequestMapping方法新的支持類
Spring 3.1 introduced a new set of support classes for @RequestMapping methods called RequestMappingHandlerMapping and RequestMappingHandlerAdapter respectively. They are recommended for use and even required to take advantage of new features in Spring MVC 3.1 and going forward. The new support classes are enabled by default by the MVC namespace and the MVC Java config but must be configured explicitly if using neither. This section describes a few important differences between the old and the new support classes.
spring3.1引入了一系列支持類對於@RequestMapping方法名字分別爲RequestMappingHandlerMapping和RequestMappingHandlerAdapter。他們被建議使用甚至在spring3.1中有許多新的特性並且會延續下去。新的支持類由默認的mvc命名空間來允許並且mvc的java配置但是必須在使用的時候明確配置。這一節描述一個新的重要的不同關於以前和新的支持類。
Prior to Spring 3.1, type and method-level request mappings were examined in two separate stages — a controller was selected first by the DefaultAnnotationHandlerMapping and the actual method to invoke was narrowed down second by the AnnotationMethodHandlerAdapter.
在spring3.1之前,類型和方法級別的請求映射是解釋在兩個不同的情況————一個控制首先被DefaultAnnotationHandlerMapping來選擇並且實際調用的縮小範圍是通過AnnotationMethodHandlerAdapter。
With the new support classes in Spring 3.1, the RequestMappingHandlerMapping is the only place where a decision is made about which method should process the request. Think of controller methods as a collection of unique endpoints with mappings for each method derived from type and method-level @RequestMapping information.
在spring3.1新的支持類下,RequestMappingHandlerMapping是唯一的位置來決定哪個方法來處理請求。考慮控制器方法作爲一個唯一的位置來匹配每個方法來源於類型和方法級別的@RequestMapping信息。
This enables some new possibilities. For once a HandlerInterceptor or a HandlerExceptionResolver can now expect the Object-based handler to be a HandlerMethod, which allows them to examine the exact method, its parameters and associated annotations. The processing for a URL no longer needs to be split across different controllers.
這允許一些新的可能。對於HandlerInterceptor或HandlerExceptionResolver可以期望基於object的處理器可以是一個HandlerMethod,允許他們來檢查實際的方法,他的參數和關聯的註解。處理一個URL不在需要分給不同的控制器。
There are also several things no longer possible:
下面的事情不在可能了:
Select a controller first with a SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping and then narrow the method based on @RequestMapping annotations.
選擇一個控制器使用SimpleUrlHandlerMapping或BeanNameUrlHandlerMapping並且縮小方法範圍對於@RequestMapping註解。
Rely on method names as a fall-back mechanism to disambiguate between two @RequestMapping methods that don’t have an explicit path mapping URL path but otherwise match equally, e.g. by HTTP method. In the new support classes @RequestMapping methods have to be mapped uniquely.
依賴一個方法名作爲回調策略來消除兩個@RequestMapping方法沒有指定路徑匹配URL路徑但是其他匹配是相同的,例如通過HTTP方法。在新的支持類@RequestMapping方法必須唯一匹配。
Have a single default method (without an explicit path mapping) with which requests are processed if no other controller method matches more concretely. In the new support classes if a matching method is not found a 404 error is raised.
有一個單一的默認方法(不需要指定路徑匹配)可以處理請求如果沒有具體控制器方法匹配。在新的支持類如果一個匹配方法沒有找到會返回404錯誤。
The above features are still supported with the existing support classes. However to take advantage of new Spring MVC 3.1 features you’ll need to use the new support classes.
上面的特性將一直支持因爲存在的支持類。然而爲了使用spring3.1新的特性,你將需要使用新的支持類。
URI Template Patterns
URI模板模式
URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.
URI模板可以方便的使用來訪問選擇URL在@RequestMapping方法中。
A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI. The proposed RFC for URI Templates defines how a URI is parameterized. For example, the URI Template http://www.example.com/users/{userId} contains the variable userId. Assigning the value fred to the variable yields http://www.example.com/users/fred.
一個URI模板是一個類似於URI的字符串,包含一個或多個變量名。當你替代這些變量值,模板將成爲一個URI。RFC建議對於URI模板定義了一個URI是如何參數化的。例如,URI模板http://www.example.com/users/{userId}包含變量userId。分配變量值爲fred則http://www.example.com/users/fred。
In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable:
在spring的mvc中你可以使用@PathVariable註解在方法上聲明綁定URI模板變量的值:
@GetMapping("/owners/{ownerId}")
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}
The URI Template " /owners/{ownerId}`" specifies the variable name `ownerId. When the controller handles this request, the value of ownerId is set to the value found in the appropriate part of the URI. For example, when a request comes in for /owners/fred, the value of ownerId is fred.
URI模板" /owners/{ownerId}`"指定變量名爲`ownerId。當控制器處理請求,ownerId的值被根據URI適當的部分設置。例如,當一個請求來自/owners/fred,值就是fred。
[Tip]
提示
To process the @PathVariable annotation, Spring MVC needs to find the matching URI template variable by name. You can specify it in the annotation:
爲了處理@PathVariable註解,spring的mvc需要找到URI模板中變量的名字。你可以在註解中指定:
@GetMapping("/owners/{ownerId}")
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
// implementation omitted
}
Or if the URI template variable name matches the method argument name you can omit that detail. As long as your code is compiled with debugging information or the -parameters compiler flag on Java 8, Spring MVC will match the method argument name to the URI template variable name:
或者如果URI模板變量名匹配方法參數名你可以省略細節。如果你的代碼使用調試信息來編譯通過java8,spring的mvc將匹配方法參數名對於URI模板的變量名:
@GetMapping("/owners/{ownerId}")
public String findOwner(@PathVariable String ownerId, Model model) {
// implementation omitted
}
A method can have any number of @PathVariable annotations:
一個方法可以用任意數量個@PathVariable註解:
@GetMapping("/owners/{ownerId}/pets/{petId}")
public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
Pet pet = owner.getPet(petId);
model.addAttribute("pet", pet);
return "displayPet";
}
When a @PathVariable annotation is used on a Map<String, String> argument, the map is populated with all URI template variables.
當一個@PathVariable註解被使用在一個Map<String, String>參數,map中是所有URL模板變量的組合。
A URI template can be assembled from type and method level @RequestMapping annotations. As a result the findPet() method can be invoked with a URL such as /owners/42/pets/21.
一個URI模板可以裝配類型和方法級別的@RequestMapping註解。由於findPet方法的結果可以是一個URL類似於/owners/42/pets/21。
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping("/pets/{petId}")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
A @PathVariable argument can be of any simple type such as int, long, Date, etc. Spring automatically converts to the appropriate type or throws a TypeMismatchException if it fails to do so. You can also register support for parsing additional data types. See the section called 「Method Parameters And Type Conversion」 and the section called 「Customizing WebDataBinder initialization」.
一個@PathVariable參數可以是任意簡單的類型例如int、long、Date等等。spring自動將轉換相應的類型或拋出類型匹配錯誤如果轉換失敗的話。你也可以註冊支持解析額外的數據類型。見章節「方法參數和類型轉換」和章節「自定義WebDataBinder初始化」。
URI Template Patterns with Regular Expressions
URI模板模式使用正則表達式
Sometimes you need more precision in defining URI template variables. Consider the URL "/spring-web/spring-web-3.0.5.jar". How do you break it down into multiple parts?
有時你需要更精確的定義URI模板變量。考慮URL爲"/spring-web/spring-web-3.0.5.jar"。你如何將其進行分解?
The @RequestMapping annotation supports the use of regular expressions in URI template variables. The syntax is {varName:regex} where the first part defines the variable name and the second - the regular expression. For example:
@RequestMapping註解支持使用正則表達式在URI模板變量。語法是{varName:regex}當第一部分定義變量名並且第二部分用橫槓來區分正則表達式。例如:
@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
public void handle(@PathVariable String version, @PathVariable String extension) {
// ...
}
Path Patterns
路徑模式
In addition to URI templates, the @RequestMapping annotation and all composed @RequestMapping variants also support Ant-style path patterns (for example, /myPath/*.do). A combination of URI template variables and Ant-style globs is also supported (e.g. /owners/*/pets/{petId}).
此外對於URI模板,@RequestMapping註解和所有組合@RequestMapping變量支持ant風格的路徑模式(例如/myPath/*.do)。一個URI模式的組合和ant風格也是支持的(例如/owners/*/pets/{petId})。
Path Pattern Comparison
路徑模型比較
When a URL matches multiple patterns, a sort is used to find the most specific match.
當一個URL匹配多個路徑模式時,在使用時會選擇最匹配的。
A pattern with a lower count of URI variables and wild cards is considered more specific. For example /hotels/{hotel}/* has 1 URI variable and 1 wild card and is considered more specific than /hotels/{hotel}/** which as 1 URI variable and 2 wild cards.
一個模式有最少的URI變量和最廣泛的考慮指定。例如 /hotels/{hotel}/* 中有一個URI的變量和一個通配符並且比/hotels/{hotel}/** 中的一個URI變量和兩個通配符更有指定性。
If two patterns have the same count, the one that is longer is considered more specific. For example /foo/bar* is longer and considered more specific than /foo/*.
如果兩個模式有相同的計數,其中一個比考慮更加指定。例如/foo/bar*就比/foo/*更加具體。
When two patterns have the same count and length, the pattern with fewer wild cards is considered more specific. For example /hotels/{hotel} is more specific than /hotels/*.
當兩個模式有相同的計數和長度,模式會匹配最少的通配符。例如/hotels/{hotel}就比/hotels/*更加具體。
There are also some additional special rules:
還有兩條額外指定的規則:
The default mapping pattern /** is less specific than any other pattern. For example /api/{a}/{b}/{c} is more specific.
默認的匹配模式/**是比其他模式更加沒有具體。例如/api/{a}/{b}/{c}是比較具體的。
A prefix pattern such as /public/** is less specific than any other pattern that doesn’t contain double wildcards. For example /public/path3/{a}/{b}/{c} is more specific.
一個前綴模式例如/public/**就沒有其他的模式具體並且沒有包含兩個通配符。例如/public/path3/{a}/{b}/{c}就更加具體。
For the full details see AntPatternComparator in AntPathMatcher. Note that the PathMatcher can be customized (see Section 22.16.11, 「Path Matching」 in the section on configuring Spring MVC).
參考AntPathMatcher中AntPatternComparator的更多細節。注意PathMatcher可以被自定義(見章節22.16.11,「模式匹配」在配置spring的mvc章節中)。
Path Patterns with Placeholders
帶有佔位符的路徑模式
Patterns in @RequestMapping annotations support ${…} placeholders against local properties and/or system properties and environment variables. This may be useful in cases where the path a controller is mapped to may need to be customized through configuration. For more information on placeholders, see the javadocs of the PropertyPlaceholderConfigurer class.
在@RequestMapping註解中的模式支持${…}的佔位符對於本地屬性和/或系統屬性和環境變量。這在有些情況下是有用的當一個控制器的路徑匹配可能需要通過配置來實現自定義。對於更多通配符信息,見PropertyPlaceholderConfigurer類的javadocs。
Suffix Pattern Matching
後綴模式匹配
By default Spring MVC performs ".*" suffix pattern matching so that a controller mapped to /person is also implicitly mapped to /person.*. This makes it easy to request different representations of a resource through the URL path (e.g. /person.pdf, /person.xml).
默認spring的mvc提供了".*"的模式匹配因此一個控制匹配/person也會匹配/person.*。這會導致簡單的請求不同的資源通過URL的路徑(例如, /person.pdf、/person.xml)。
Suffix pattern matching can be turned off or restricted to a set of path extensions explicitly registered for content negotiation purposes. This is generally recommended to minimize ambiguity with common request mappings such as /person/{id} where a dot might not represent a file extension, e.g. /person/[email protected] vs /person/[email protected] Furthermore as explained in the note below suffix pattern matching as well as content negotiation may be used in some circumstances to attempt malicious attacks and there are good reasons to restrict them meaningfully.
後綴模式匹配可以被關閉或明確指定限制於一些路徑的擴展爲了內容的處理。通常建議最小化衝突當使用相同的請求匹配例如/person/{id}當一個點不是代表一個文件的擴展,例如,/person/[email protected]和/person/[email protected]。更多文檔的解釋在後綴匹配和內容的處理可能被用在一些情況試圖惡意攻擊和有好的理由來進行有意義的限制。
See Section 22.16.11, 「Path Matching」 for suffix pattern matching configuration and also Section 22.16.6, 「Content Negotiation」 for content negotiation configuration.
見章節22.16.11,「路徑匹配」對於後綴模式匹配配置和章節22.16.6,「內容協商」對於內容的處理配置。
Suffix Pattern Matching and RFD
後綴模式匹配和RFD
Reflected file download (RFD) attack was first described in a paper by Trustwave in 2014. The attack is similar to XSS in that it relies on input (e.g. query parameter, URI variable) being reflected in the response. However instead of inserting JavaScript into HTML, an RFD attack relies on the browser switching to perform a download and treating the response as an executable script if double-clicked based on the file extension (e.g. .bat, .cmd).
反射文件下載(RFD)攻擊首先被Trustwave在2014年描述在論文中。這個攻擊和XSS相似並且依賴於輸入(例如,查詢參數,URI變量)被反射在響應中。然而替代插入JavaScript到HTML中,一個RFD攻擊依賴於瀏覽器打開執行一個下載並且將響應作爲一個可執行腳本來處理如果雙擊基於文件系統(例如,bat或cmd)。
In Spring MVC @ResponseBody and ResponseEntity methods are at risk because they can render different content types which clients can request including via URL path extensions. Note however that neither disabling suffix pattern matching nor disabling the use of path extensions for content negotiation purposes alone are effective at preventing RFD attacks.
在spring的mvc中的@ResponseBody和ResponseEntity方法在一定的情況因爲他可以處理不同的內容類型根據客戶端的請求包括通過一個URL路徑的擴展。注意然而關閉後綴匹配不會關閉使用路徑擴展對於內容除了的目錄並且有效的應對了RFD的攻擊。
For comprehensive protection against RFD, prior to rendering the response body Spring MVC adds a Content-Disposition:inline;filename=f.txt header to suggest a fixed and safe download file filename. This is done only if the URL path contains a file extension that is neither whitelisted nor explicitly registered for content negotiation purposes. However it may potentially have side effects when URLs are typed directly into a browser.
對於比較複雜的RFD保護,爲了返回響應體spring的mvc添加了一個Content-Disposition:inline;filename=f.txt頭來建議一個固定和安全的下載文件名。只有當URL路徑包含一個文件擴展名或指定白名單註冊對於內容的處理。然而他可能潛在有一定的影響當URL通常直接指向瀏覽器。
Many common path extensions are whitelisted by default. Furthermore REST API calls are typically not meant to be used as URLs directly in browsers. Nevertheless applications that use custom HttpMessageConverter implementations can explicitly register file extensions for content negotiation and the Content-Disposition header will not be added for such extensions. See Section 22.16.6, 「Content Negotiation」.
許多一般的路徑擴展默認是在白名單中的。更多REST的API調用通常不會因爲着被使用作爲URL在瀏覽器中。除非應用使用自定義的HttpMessageConverter實現可以明確指定註冊文件擴展對於內容除了和Content-Disposition的頭將不會被添加到這樣的擴展中。見章節22.16.6,「內容協商」。
[Note]
注意
This was originally introduced as part of work for CVE-2015-5211. Below are additional recommendations from the report:
最初引入這一部分是爲了CVE-2015-5211。下面是對於報告的額外的建議。
Encode rather than escape JSON responses. This is also an OWASP XSS recommendation. For an example of how to do that with Spring see spring-jackson-owasp.
編碼而不是逃開JSON返回。這也是一種OWASP XSS的建議。對於一個如何使用的例子對於spring見spring-jackson-owasp。
Configure suffix pattern matching to be turned off or restricted to explicitly registered suffixes only.
配置後綴模式匹配被關閉或只嚴格指定後綴註冊。
Configure content negotiation with the properties "useJaf" and "ignoreUnknownPathExtensions" set to false which would result in a 406 response for URLs with unknown extensions. Note however that this may not be an option if URLs are naturally expected to have a dot towards the end.
配置內容協商使用屬性"useJaf"和"ignoreUnknownPathExtensions"設置爲false將導致406返回對於URL由於未知的擴展。注意然而這不會是一種選項如果URL是被指定有一個點在最後。
Add X-Content-Type-Options: nosniff header to responses. Spring Security 4 does this by default.
添加X-Content-Type-Options:響應中的nosniff頭。spring security 4默認是這麼做的。
Matrix Variables
矩陣變量
The URI specification RFC 3986 defines the possibility of including name-value pairs within path segments. There is no specific term used in the spec. The general "URI path parameters" could be applied although the more unique "Matrix URIs", originating from an old post by Tim Berners-Lee, is also frequently used and fairly well known. Within Spring MVC these are referred to as matrix variables.
URI指定RFC3986定義了包含name-value對和路徑片段的可能。沒有指定成對使用在特定的情況。通常「URL路徑參數」可以應用盡管有更加唯一的「矩陣URI」,來自Tim Berners-Lee提出,也很方便使用爲人所知。在spring的mvc中他們引用了矩陣變量。
Matrix variables can appear in any path segment, each matrix variable separated with a ";" (semicolon). For example: "/cars;color=red;year=2012". Multiple values may be either "," (comma) separated "color=red,green,blue" or the variable name may be repeated "color=red;color=green;color=blue".
矩陣變量可以出現在任何路徑段中,每個矩陣變量使用一個分號分隔。例如:"/cars;color=red;year=2012"。多個值使用逗號分隔"color=red,green,blue"或變量名可以重複"color=red;color=green;color=blue"。
If a URL is expected to contain matrix variables, the request mapping pattern must represent them with a URI template. This ensures the request can be matched correctly regardless of whether matrix variables are present or not and in what order they are provided.
如果一個URL被期望包含矩陣變量,請求匹配模式可以代表使用一個URI模板。這保證了請求可以被正確匹配不管矩陣變量是否代表他們被提供的順序。
Below is an example of extracting the matrix variable "q":
下面一個例如是擴展了矩陣變量「q」:
// GET /pets/42;q=11;r=22
@GetMapping("/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
// petId == 42
// q == 11
}
Since all path segments may contain matrix variables, in some cases you need to be more specific to identify where the variable is expected to be:
所有的變量段可能包含矩陣變量,在一些情況你需要明確指定當你期望如下的時候:
// GET /owners/42;q=11/pets/21;q=22
@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2) {
// q1 == 11
// q2 == 22
}
A matrix variable may be defined as optional and a default value specified:
一個矩陣變量可以被定義作爲一個選項和一個默認值:
// GET /pets/42
@GetMapping("/pets/{petId}")
public void findPet(@MatrixVariable(required=false, defaultValue="1") int q) {
// q == 1
}
All matrix variables may be obtained in a Map:
所有的矩陣變量可以從一個map中獲取:
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23
@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
@MatrixVariable MultiValueMap<String, String> matrixVars,
@MatrixVariable(pathVar="petId"") MultiValueMap<String, String> petMatrixVars) {
// matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
// petMatrixVars: ["q" : 11, "s" : 23]
}
Note that to enable the use of matrix variables, you must set the removeSemicolonContent property of RequestMappingHandlerMapping to false. By default it is set to true.
注意確保使用矩陣變量,你必須設置RequestMappingHandlerMapping中的removeSemicolonContent屬性爲false。默認他是true的。
[Tip]
提示
The MVC Java config and the MVC namespace both provide options for enabling the use of matrix variables.
mvc的java配置和mvc命名空間提供了選項來允許使用矩陣變量。
If you are using Java config, The Advanced Customizations with MVC Java Config section describes how the RequestMappingHandlerMapping can be customized.
如果你使用java配置,mvc的java配置中的高級自定義描述了RequestMappingHandlerMapping是如何被自定義的。
In the MVC namespace, the <mvc:annotation-driven> element has an enable-matrix-variables attribute that should be set to true. By default it is set to false.
在mvc的命名空間,<mvc:annotation-driven>元素有一個enable-matrix-variables屬性被設置爲true。默認他是設置爲false的。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven enable-matrix-variables="true"/>
</beans>
Consumable Media Types
處理的媒體類型
You can narrow the primary mapping by specifying a list of consumable media types. The request will be matched only if the Content-Type request header matches the specified media type. For example:
你可以縮小主要的匹配通過指定一個列表對於處理的媒體類型。請求將被匹配只有當Content-Type請求頭匹配指定的媒體類型。例如:
@PostMapping(path = "/pets", consumes = "application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
}
Consumable media type expressions can also be negated as in !text/plain to match to all requests other than those with Content-Type of text/plain. Also consider using constants provided in MediaType such as APPLICATION_JSON_VALUE and APPLICATION_JSON_UTF8_VALUE.
處理的媒體類型表達式也可以使用否定的形式例如!text/plain來匹配所有的請求中除了text/plain的Content-Type的類型。也要考慮指定的數量對於媒體類型例如APPLICATION_JSON_VALUE和APPLICATION_JSON_UTF8_VALUE。
[Tip]
提示
The consumes condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level consumable types override rather than extend type-level consumable types.
處理條件被支持對於類型並且在方法級別。不像其他的條件,當使用在類型級別、方法級別的處理類型會覆蓋類型級別的處理類型。
Producible Media Types
可擴展的媒體類型
You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the produces condition. For example:
你可以縮小主要的匹配通過指定一個可擴展的媒體類型列表。請求將被匹配只有Accept的請求頭匹配這些值。此外,使用可擴展的田間保證實際的內容類型使用通常生成相應代表媒體類型指定在生產條件。例如:
@GetMapping(path = "/pets/{petId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}
[Note]
注意
Be aware that the media type specified in the produces condition can also optionally specify a character set. For example, in the code snippet above we specify the same media type than the default one configured in MappingJackson2HttpMessageConverter, including the UTF-8 charset.
意識到媒體類型定義在生產條件也可以選擇指定一個字符集。例如,在上面的代碼片段我們指定了相同的媒體類型而不是默認配置在MappingJackson2HttpMessageConverter中的,包括UTF-8字符集。
Just like with consumes, producible media type expressions can be negated as in !text/plain to match to all requests other than those with an Accept header value of text/plain. Also consider using constants provided in MediaType such as APPLICATION_JSON_VALUE and APPLICATION_JSON_UTF8_VALUE.
就像耗盡一樣,生產媒體類型表達式可以忽略如!text/plain來匹配所有的請求除了Accept頭值是text/plain。也考慮使用常量提供在MediaType中例如APPLICATION_JSON_VALUE和APPLICATION_JSON_UTF8_VALUE。
[Tip]
提示
The produces condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level producible types override rather than extend type-level producible types.
生產條件被支持在類型和方法級別。不像其他的條件,當使用在類型級別、方法級別生產類型覆蓋而不是擴展類型級別的生產類型。
Request Parameters and Header Values
請求參數和頭信息
You can narrow request matching through request parameter conditions such as "myParam", "!myParam", or "myParam=myValue". The first two test for request parameter presence/absence and the third for a specific parameter value. Here is an example with a request parameter value condition:
你可以縮小請求的匹配通過請求參數條件例如"myParam"、"!myParam"或"myParam=myValue"。首先的兩個測試對於請求參數的有或者沒有並且第三個用於指定參數值。這是一個例子展示了使用請求參數值作爲條件:
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@GetMapping(path = "/pets/{petId}", params = "myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
The same can be done to test for request header presence/absence or to match based on a specific request header value:
相同的也可以用於請求頭有或者沒有或者匹配指定的請求頭參數值:
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@GetMapping(path = "/pets", headers = "myHeader=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
[Tip]
提示
Although you can match to Content-Type and Accept header values using media type wild cards (for example "content-type=text/*" will match to "text/plain" and "text/html"), it is recommended to use the consumes and produces conditions respectively instead. They are intended specifically for that purpose.
儘管你可以匹配Content-Type和Accept的頭信息使用媒體類型通配符(例如"content-type=text/*"將匹配"text/plain"和"text/html"),他要求使用消費和過程管理條件作爲明顯的替代。他們試圖指定爲了實現這種目的。
HTTP HEAD and HTTP OPTIONS
@RequestMapping methods mapped to "GET" are also implicitly mapped to "HEAD", i.e. there is no need to have "HEAD" explicitly declared. An HTTP HEAD request is processed as if it were an HTTP GET except instead of writing the body only the number of bytes are counted and the "Content-Length" header set.
@RequestMapping方法匹配"GET"也可以明確指定匹配"HEAD",例如不需要直接定義"HEAD"。一個http頭請求被處理如果他是一個http的get而不是隻有內容和"Content-Length"的頭信息。
@RequestMapping methods have built-in support for HTTP OPTIONS. By default an HTTP OPTIONS request is handled by setting the "Allow" response header to the HTTP methods explicitly declared on all @RequestMapping methods with matching URL patterns. When no HTTP methods are explicitly declared the "Allow" header is set to "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS". Ideally always declare the HTTP method(s) that an @RequestMapping method is intended to handle, or alternatively use one of the dedicated composed @RequestMapping variants (see the section called 「Composed @RequestMapping Variants」).
@RequestMapping方法有內置的對於http選項的支持。默認一個http選項請求被處理通過設置"Allow"響應頭對於http方法明確定義對於所有的@RequestMapping方法使用匹配URL模式。當沒有http方法被明確指定通過"Allow"頭設置爲"GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS"。理想是定義http方法使得一個@RequestMapping方法可以去處理或使用其中的一個組合@RequestMapping變量(參見章節「組合@RequestMapping變量」)
Although not necessary an @RequestMapping method can be mapped to and handle either HTTP HEAD or HTTP OPTIONS, or both.
儘管沒有必要一個@RequestMapping方法可以匹配http頭或http選項或兩者都匹配。
22.3.3 Defining @RequestMapping handler methods
定義@RequestMapping處理方法
@RequestMapping handler methods can have very flexible signatures. The supported method arguments and return values are described in the following section. Most arguments can be used in arbitrary order with the only exception being BindingResult arguments. This is described in the next section.
@RequestMapping處理方法可有多個方便的簽名。支持方法參數和返回值被描述在後面的章節。大部分參數可以被使用以任意的順序除了BindingResult參數。這會在下一章節中描述。
[Note]
注意
Spring 3.1 introduced a new set of support classes for @RequestMapping methods called RequestMappingHandlerMapping and RequestMappingHandlerAdapter respectively. They are recommended for use and even required to take advantage of new features in Spring MVC 3.1 and going forward. The new support classes are enabled by default from the MVC namespace and with use of the MVC Java config but must be configured explicitly if using neither.
spring3.1引入了一個新的集合支持類對於@RequestMapping方法名字爲RequestMappingHandlerMapping和RequestMappingHandlerAdapter。他們被推薦使用當你需要spring的mvc3.1中的新的功能時。新的支持類默認是開啓的並且作爲mvc命名空間的默認並且使用mvc的java配置但是必須明確指定是否使用。
Supported method argument types
支持方法參數類型
The following are the supported method arguments:
下面是支持的方法參數:
Request or response objects (Servlet API). Choose any specific request or response type, for example ServletRequest or HttpServletRequest.
請求或響應object(Servlet API)。選擇任何請求或響應類型,例如ServletRequest或HttpServletRequest。
Session object (Servlet API): of type HttpSession. An argument of this type enforces the presence of a corresponding session. As a consequence, such an argument is never null.
會話object(Servlet API):類型是HttpSession。一個這個類型的參數強制相應的會話出現。因此,這樣的參數不會是null。
[Note]
注意
Session access may not be thread-safe, in particular in a Servlet environment. Consider setting the RequestMappingHandlerAdapter's "synchronizeOnSession" flag to "true" if multiple requests are allowed to access a session concurrently.
會話訪問可能不是線程安全的,特別是在Servlet環境中。考慮設置RequestMappingHandlerAdapter的"synchronizeOnSession"標識爲"true"如果多個請求被允許同步訪問一個會話。
org.springframework.web.context.request.WebRequest or org.springframework.web.context.request.NativeWebRequest. Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.
允許一般的請求參數訪問包括請求/會話屬性訪問,而不需要綁定本地的Servlet/Portlet的API。
java.util.Locale for the current request locale, determined by the most specific locale resolver available, in effect, the configured LocaleResolver / LocaleContextResolver in an MVC environment.
java.util.Locale用於當前的請求,通過大部分本地解析被決定,實際上,配置LocaleResolver / LocaleContextResolver在mvc的環境。
java.util.TimeZone (Java 6+) / java.time.ZoneId (on Java 8) for the time zone associated with the current request, as determined by a LocaleContextResolver.
java.util.TimeZone (Java 6+) / java.time.ZoneId (on Java 8)對於時區和當前的請求有關,通過LocaleContextResolver來決定。
java.io.InputStream / java.io.Reader for access to the request’s content. This value is the raw InputStream/Reader as exposed by the Servlet API.
java.io.InputStream / java.io.Reader對於請求內容。這個只是InputStream/Reader通過Servlet的API暴露出來。
java.io.OutputStream / java.io.Writer for generating the response’s content. This value is the raw OutputStream/Writer as exposed by the Servlet API.
java.io.OutputStream / java.io.Writer用於生成響應的內容。這個值是OutputStream/Writer通過Servlet的API暴露出來。
org.springframework.http.HttpMethod for the HTTP request method.
org.springframework.http.HttpMethod用於http請求方法。
java.security.Principal containing the currently authenticated user.
java.security.Principal包含當前ervletRequest或HttpServletRequest。
Session object (Servlet API): of type HttpSession. An argument of this type enforces the presence of a corresponding session. As a consequence, such an argument is never null.
會話object(Servlet API):類型是HttpSession。一個這個類型的參數強制相應的會話出現。因此,這樣的參數不會是null。
[Note]
注意
Session access may not be thread-safe, in particular in a Servlet environment. Consider setting the RequestMappingHandlerAdapter's "synchronizeOnSession" flag to "true" if multiple requests are allowed to access a session concurrently.
會話訪問可能不是線程安全的,特別是在Servlet環境中。考慮設置RequestMappingHandlerAdapter的"synchronizeOnSession"標識爲"true"如果多個請求被允許同步訪問一個會話。
org.springframework.web.context.request.WebRequest or org.springframework.web.context.request.NativeWebRequest. Allows for generic request parameter access as well as request/session attribute access, without ties to the native Servlet/Portlet API.
允許一般的請求參數訪問包括請求/會話屬性訪問,而不需要綁定本地的Servlet/Portlet的API。
java.util.Locale for the current request locale, determined by the most specific locale resolver available, in effect, the configured LocaleResolver / LocaleContextResolver in an MVC environment.
java.util.Locale用於當前的請求,通過大部分本地解析被決定,實際上,配置LocaleResolver / LocaleContextResolver在mvc的環境。
java.util.TimeZone (Java 6+) / java.time.ZoneId (on Java 8) for the time zone associated with the current request, as determined by a LocaleContextResolver.
java.util.TimeZone (Java 6+) / java.time.ZoneId (on Java 8)對於時區和當前的請求有關,通過LocaleContextResolver來決定。
java.io.InputStream / java.io.Reader for access to the request’s content. This value is the raw InputStream/Reader as exposed by the Servlet API.
java.io.InputStream / java.io.Reader對於請求內容。這個只是InputStream/Reader通過Servlet的API暴露出來。
java.io.OutputStream / java.io.Writer for generating the response’s content. This value is the raw OutputStream/Writer as exposed by the Servlet API.
java.io.OutputStream / java.io.Writer用於生成響應的內容。這個值是OutputStream/Writer通過Servlet的API暴露出來。
org.springframework.http.HttpMethod for the HTTP request method.
org.springframework.http.HttpMethod用於http請求方法。
java.security.Principal containing the currently authenticated user.
java.security.Principal包含當前的已經認證的用戶。
@PathVariable annotated parameters for access to URI template variables. See the section called 「URI Template Patterns」.
@PathVariable註解的參數用於訪問uri模型變量。見章節「URI模板模式」。
@MatrixVariable annotated parameters for access to name-value pairs located in URI path segments. See the section called 「Matrix Variables」.
@MatrixVariable註解的參數用於訪問鍵值對在uri的路徑中。見章節「矩陣變量」。
@RequestParam annotated parameters for access to specific Servlet request parameters. Parameter values are converted to the declared method argument type. See the section called 「Binding request parameters to method parameters with @RequestParam」.
@RequestParam註解參數用於訪問指定的Servlet請求參數。參數值可以轉化爲指定的方法參數類型。見章節「綁定請求參數對於方法參數通過@RequestParam」。
@RequestHeader annotated parameters for access to specific Servlet request HTTP headers. Parameter values are converted to the declared method argument type. See the section called 「Mapping request header attributes with the @RequestHeader annotation」.
@RequestHeader註解參數用於訪問指定的Servlet請求的http頭。參數值轉化爲指定的方法參數類型。見章節「匹配請求頭屬性通過@RequestHeader註解」。
@RequestBody annotated parameters for access to the HTTP request body. Parameter values are converted to the declared method argument type using HttpMessageConverters. See the section called 「Mapping the request body with the @RequestBody annotation」.
@RequestBody註解參數用於訪問http請求體。