RequestContextHolder中的寶藏工具方法
RequestAttributes requestAttributes=RequestContextHolder.getRequestAttributes();
ServletRequestAttributes servletRequestAttributes=ServletRequestAttributes.class.cast(requestAttributes);
//獲取request
HttpServletRequest request =servletRequestAttributes.getRequest();
//獲取response
HttpServletResponse response = servletRequestAttributes.getResponse();
//設置屬性
servletRequestAttributes.setAttribute("name","value","SCOPE_REQUEST|SCOPE_SESSION|");
//獲取屬性
servletRequestAttributes.getAttribute(String name, int "SCOPE_REQUEST|SCOPE_SESSION|")
去除url中的參數
public static String removeParameter(String url, String param) {
return url.replaceAll("[?&]"+param+"=[^&]*&?$", "");
}
一、Spring MVC國際化簡介
程序國際化是商業系統的一個基本要求,因爲今天的軟件系統不再是簡單的單機程序,往往都是一個開放的系統,需要面對來自全世界各個地方的訪問者,因此,國際化成爲商業系統必不可少的一部分。
Spring MVC的國際化是建立在Java國際化的基礎之上的,其一樣也是通過提供不同國家/語言環境的消息資源,然後通過 Resource Bundle加載指定 Locale對應的資源文件,再取得該資源文件中指定key對應的消息。這整個過程與Java程序的國際化完全相同,只是 Spring MVC框架對Java程序國際化進行了進一步的封裝,從而簡化了應用程序的國際化。
二、Spring MVC國際化的知識:
1、messageSource接口:告訴系統國際資源文件的存儲位置。
org.springframework.context.support.ResourceBundleMessageSource類
2、LocaleResolver接口:確定語言區域
(1)accept-langage:基於瀏覽器的語言區域選擇 --- 默認方式,不需要配置
(2)SessionLocaleResolver:基於會話的語言區域選擇,需要配置(常用)
(3)CookieLocaleResolver:基於Cookie的語言區域選擇,需要配置
3、LocaleChangeInterceptor攔截器:國際化的攔截器,當語言區域發生改變時,該攔截器將進行攔截,根據傳遞的參數來改變應用的語言環境。需要在SpringMVC的配置文件中進行註冊
4、message標籤:是Spring MVC的標籤,在視圖頁面中輸出國際化的消息
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<spring:message code="username"/>
velocigy標籤:
#springMessage("username")
三、Spring MVC國際化步驟:
(1)給系統加載國際化資源文件。
(2)輸出國際化。 Spring MVC輸出國際化消息有兩種方式:
A、在視圖頁面上輸出國際化消息,需要使用 Spring MVC的標籤庫。
B、在 Controller的處理方法中輸出國際化消息,
需要使用 org.springframework.web.servlet.support Requestcontext的getMessage()方法來完成。
四、基於SessionLocaleResolver的國際化:
1、創建資源文件
messages_zh_CN.properties
messages_en_US.properties