首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

基於 Session 的 Spring MVC 國際化實現:攔截器 + ResourceBundle 切換語系

     編輯:Java 綜合教學

基於 Session 的 Spring MVC 國際化實現:攔截器 + ResourceBundle 切換語系

架構設計

  1. LocaleChangeInterceptor 攔截 langType 參數解析語系
  2. Controller 將 Locale 存入 Session
  3. JSP 透過 ResourceBundle 讀取對應屬性檔

配置與實現

1. Spring 配置攔截器


<mvc:interceptors>
  <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="langType"/> <!-- 預設 locale -->
  </bean>
</mvc:interceptors>

2. 訊息屬性檔


# myproperties.properties (預設)
welcome=Welcome
simplified=Simplified Chinese

# myproperties_zh.properties
welcome=歡迎
simplified=簡體中文

# myproperties_en.properties
welcome=Welcome
simplified=English

3. Controller 切換語系並存 Session


@Controller
@RequestMapping("/index")
public class IndexAction {
    @GetMapping("/findex")
    public String findex(HttpServletRequest request, 
                         @RequestParam String langType, 
                         @RequestParam String page) {
        Locale locale;
        switch (langType) {
            case "zh": locale = Locale.SIMPLIFIED_CHINESE; break;
            case "en": locale = Locale.US; break;
            default: locale = Locale.getDefault();
        }
        request.getSession().setAttribute("i18nlanguage", locale);
        return "/front/" + page + ".jsp";
    }
}

4. JSP 讀取國際化文字


<%@ page import="java.util.*" %>
<%
  Locale locale = (Locale) session.getAttribute("i18nlanguage");
  ResourceBundle bundle = ResourceBundle.getBundle("myproperties", locale);
%>
<a href="${pageContext.request.contextPath}/index/findex.do?langType=en&page=Home">ENG</a> |
<a href="${pageContext.request.contextPath}/index/findex.do?langType=zh&page=Home"><%=bundle.getString("simplified")%></a>

進階優化建議

  • 使用 SessionLocaleResolver 替代手動存 Session,配合 LocaleChangeInterceptor 完全聲明式
  • JSP 採用 <fmt:message key="welcome"/> (JSTL fmt 標籤庫) 替代 Scriptlet
  • 屬性檔命名遵循 messages_zh_CN.properties 標準格式
  • 支援參數化訊息:welcome=Welcome, {0}! → bundle.getString("welcome", new Object[]{userName})

Session vs Cookie vs Accept-Language

根據業務場景選擇最適合的語系解析策略。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
策略優點缺點
Session伺服器端可控,支援登入後綁定用戶偏好需 Session 親和性,無狀態架構不適用
Cookie客戶端持久,無 Session 依賴用戶可禁用/清除
Accept-Language零配置,自動跟隨瀏覽器用戶難以手動切換