今天開始第五天的spring mvc框架學習
----------------------3小時完成-----------------------------------
要做的事:學習spring mvc
1、在Spring MVC中使用 flash attributes
2、Spring MVC Building
3、Using locales
-------------------------------------------------------------------------
markpage45
1、在Spring MVC中使用 flash attributes
spring mvc Flash attributes提供了一個請求存儲屬性可供另外請求使用一種方式。在使用重定向時候非常必要。
例如,Post/Redirect/Get模式。flash attributes在重定向之前暫存以便重定向之後還能使用,並立即刪除。
Spring MVC有兩個主要的抽象來支持flash attributes。FlashMap用於保持 flash attributes而FlashMapManager用於存儲,檢索,管理FlashMap實例。
Flash attribute支持默認開啓並不需要顯式啓用,它永遠不會導致HTTP Session的創建。每一個請求都有一個"input" FlashMap具有從上一個請求傳過來的屬性和一個“output”FlashMap具有將要在後續請求中保存的屬性。這兩個FlashMap實例都可以通過靜態方法RequestContextUtils從Spring MVC的任何位置訪問。
使用註解的控制器通常不需要直接與FlashMap一起工作。相反,@RequestMapping方法可以接受一個RedirectAttributes類型的參數,用它來在重定向場景中增加flash attributes。通過RedirectAttributes加入的Flash attributes將自動傳播到“output”FlashMap。同樣的,重定向之後,從“input” FlashMap來的屬性自動添加到控制器的Model,爲目標Url服務。
Matching requests to flash attributes
閃存屬性的概念存在於許多其他的Web框架,事實證明,有時受到併發問題。這是因爲根據定義flash屬性是要被存儲直到下一個請求。但是恰好“next”請求並不是接受者,而是另外的異步請求,這種情況下,flash attributes被過早移除。
2、Spring MVC Building
Spring MVC提供用於生成和使用UriComponentsBuilder和 UriComponents對URI編碼的機制。
例如你可以展開並進行編碼的uri模板字符串:
UriComponents uriComponents =
UriComponentsBuilder.fromUriString("http://example.com/hotels/{hotel}/bookings/{booking}").build();
URI uri = uriComponents.expand("42","21").encode().toUri();
你可以使用單獨的URI組件expand和encode:
UriComponents uriComponents = UriComponentsBuilder.newInstance()
.scheme("http").host("example.com").path("/hotels/{hotel}/bookings/{booking}").build().expand("42","21")
.encode();
在Servlet環境中,ServletUriComponentsBuilder子類提供了靜態工廠方法來從Servlet請求複製可用的URL信息:
HttpServletRequest request = ...
ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromRequest(request).replaceQueryParam("accountId","{id}").build()
.expand("123").encode();
另外,你可以選擇複製包括甚至contect path的可用信息的子集:
ServletUriComponentsBuilder ucb =
ServletUriComponentsBuilder.fromContextPath(request).path("/accounts").build()
或在DispatcherServlet被以name映射情況下,你也可以講servlet mapping的文字部分包含進來:
ServletUriComponentsBuilder ucb =
ServletUriComponentsBuilder.fromServletMapping(request).path{"/accounts"}.build()
3、Using locales
Spring的體系結構中,大部分都支持國際化,就像Spring Web MVC框架一樣。DispatcherServlet使你能夠使用客戶端的locale自動解決信息。這都是由LocaleResolver對象來實現的。
請求進來的時候,DispatcherServlet查找一個locale resolver,如果它找到了一個,它就試圖用它來設置locale。使用 RequestContext.getLocale()方法,你可以始終檢索由locale resolver解決的 locale。
爲了自動處理locale resolution,你可以給handle mapping附加一個攔截器來改變指定環境下的locale,例如,基於請求中的一個參數。
下面是Spring中locale resolvers的一些選擇。
3.1 AcceptHeaderLocaleResolver
該locale resolver攔截客戶端發送請求中的 accept-language頭信息。通常該header字段包含客戶端操作系統的locale。
3.2CookieLocaleResolver
該locale resolver攔截一個可能存在於客戶端的cookie,看是否設置了locale。如果是這樣,它將使用指定的區域設置。
3.3SessionLocaleResolver
SessionLocaleResolver允許你從可能與用戶請求相關聯的session中檢索locales。
3.4LocaleChangeInterceptor
你可以通過將LocaleChangeInterceptor添加到 handlermappings來啓用locales更改。
它將檢測請求中的參數並修改locale。
mg:49