搜尋
首頁Javajava教程SpringMVC學習系列(8) 之 國際化程式碼詳細介紹

在系列(7)中我們講了數據的格式化顯示,Spring在做格式化展示的時候已經做了國際化處理,那麼如何將我們網站的其它內容(如菜單、標題等)做國際化處理呢?這就是本篇要將的內容—>國際化。

一.基於瀏覽器請求的國際化實作:

首先配置我們專案的springservlet-config.xml檔案新增的內容如下:

<bean>
    <!-- 国际化信息所在的文件名 -->                     
    <property></property>   
    <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称  -->               
    <property></property>           </bean>


在com.demo.web.controllers套件中加入GlobalController.java內容如下:

package com.demo.web.controllers;import java.util.Date;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.support.RequestContext;import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/global")public class GlobalController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(HttpServletRequest request,Model model){        if(!model.containsAttribute("contentModel")){            
            //从后台代码获取国际化信息
            RequestContext requestContext = new RequestContext(request);
            model.addAttribute("money", requestContext.getMessage("money"));
            model.addAttribute("date", requestContext.getMessage("date"));

            
            FormatModel formatModel=new FormatModel();

            formatModel.setMoney(SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹.SpringMVC學習系列(8) 之 國際化程式碼詳細介紹78);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }        return "globaltest";
    }
    
}


這裡展示模型也用系列(7)中的作為演示。

在專案中的來源資料夾resources中新增messages.properties、messages_zh_CN.properties、messages_en_US.properties三個文件,其中messages.properties、messages_zh_CN.properties裡面的"money", "date",", "date",為中文,messages_en_US.properties裡面的為英文。

在views資料夾中新增globaltest.jsp視圖,內容如下:

nbsp;html PUBLIC "-//WSpringMVC學習系列(8) 之 國際化程式碼詳細介紹C//DTD HTML SpringMVC學習系列(8) 之 國際化程式碼詳細介紹.0SpringMVC學習系列(8) 之 國際化程式碼詳細介紹 Transitional//EN" "http://www.wSpringMVC學習系列(8) 之 國際化程式碼詳細介紹.org/TR/htmlSpringMVC學習系列(8) 之 國際化程式碼詳細介紹/loose.dtd"><meta><title>Insert title here</title>

    下面展示的是后台获取的国际化信息:<br>
    ${money}<br>
    ${date}<br>

    下面展示的是视图中直接绑定的国际化信息:<br>
    <message></message>:<br>
    <eval></eval><br>
    <message></message>:<br>
    <eval></eval><br>
    


執行測試:

SpringMVC學習系列(8) 之 國際化程式碼詳細介紹

更改瀏覽器語言順序,刷新頁面:

SpringMVC學習系列(8) 之 國際化程式碼詳細介紹

 

二.基於Session的國際化實現:

##在專案的springservlet-config.xml檔案新增的內容如下(第一種時新增的內容要保留):

<interceptors>  
    <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> 
    <bean></bean>  </interceptors>  <bean></bean>


更改globaltest.jsp視圖為如下內容:

nbsp;html PUBLIC "-//WSpringMVC學習系列(8) 之 國際化程式碼詳細介紹C//DTD HTML SpringMVC學習系列(8) 之 國際化程式碼詳細介紹.0SpringMVC學習系列(8) 之 國際化程式碼詳細介紹 Transitional//EN" "http://www.wSpringMVC學習系列(8) 之 國際化程式碼詳細介紹.org/TR/htmlSpringMVC學習系列(8) 之 國際化程式碼詳細介紹/loose.dtd"><meta><title>Insert title here</title>
    <a>中文</a> | <a>英文</a><br>

    下面展示的是后台获取的国际化信息:<br>
    ${money}<br>
    ${date}<br>

    下面展示的是视图中直接绑定的国际化信息:<br>
    <message></message>:<br>
    <eval></eval><br>
    <message></message>:<br>
    <eval></eval><br>
    


更改GlobalController.java為下列內容:

package com.demo.web.controllers;import java.util.Date;import java.util.Locale;import javax.servlet.http.HttpServletRequest;import org.springframework.context.iSpringMVC學習系列(8) 之 國際化程式碼詳細介紹8n.LocaleContextHolder;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.iSpringMVC學習系列(8) 之 國際化程式碼詳細介紹8n.SessionLocaleResolver;import org.springframework.web.servlet.support.RequestContext;import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/global")public class GlobalController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(HttpServletRequest request,Model model, @RequestParam(value="langType", defaultValue="zh") String langType){        if(!model.containsAttribute("contentModel")){            
            if(langType.equals("zh")){
                Locale locale = new Locale("zh", "CN"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
            }            else if(langType.equals("en")){
                Locale locale = new Locale("en", "US"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
            }            else 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());            
            //从后台代码获取国际化信息
            RequestContext requestContext = new RequestContext(request);
            model.addAttribute("money", requestContext.getMessage("money"));
            model.addAttribute("date", requestContext.getMessage("date"));

            
            FormatModel formatModel=new FormatModel();

            formatModel.setMoney(SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹.SpringMVC學習系列(8) 之 國際化程式碼詳細介紹78);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }        return "globaltest";
    }
    
}


執行測試:

SpringMVC學習系列(8) 之 國際化程式碼詳細介紹

SpringMVC學習系列(8) 之 國際化程式碼詳細介紹




############## #######三.基於Cookie的國際化實作:######把實作第二種方法時在專案的springservlet-config .xml檔案中新增的###
<bean></bean>
############註解掉,並新增以下內容:###
<bean></bean>
############更改GlobalController.java為如下內容:###
package com.demo.web.controllers;import java.util.Date;import java.util.Locale;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.context.iSpringMVC學習系列(8) 之 國際化程式碼詳細介紹8n.LocaleContextHolder;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.iSpringMVC學習系列(8) 之 國際化程式碼詳細介紹8n.CookieLocaleResolver;//import org.springframework.web.servlet.iSpringMVC學習系列(8) 之 國際化程式碼詳細介紹8n.SessionLocaleResolver;import org.springframework.web.servlet.support.RequestContext;import com.demo.web.models.FormatModel;

@Controller
@RequestMapping(value = "/global")public class GlobalController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam(value="langType", defaultValue="zh") String langType){        if(!model.containsAttribute("contentModel")){            
            /*if(langType.equals("zh")){
                Locale locale = new Locale("zh", "CN"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
            }
            else if(langType.equals("en")){
                Locale locale = new Locale("en", "US"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
            }
            else 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());*/
            
            if(langType.equals("zh")){
                Locale locale = new Locale("zh", "CN"); 
                //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
                (new CookieLocaleResolver()).setLocale (request, response, locale);
            }            else if(langType.equals("en")){
                Locale locale = new Locale("en", "US"); 
                //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
                (new CookieLocaleResolver()).setLocale (request, response, locale);
            }            else 
                //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());
                (new CookieLocaleResolver()).setLocale (request, response, LocaleContextHolder.getLocale());            
            //从后台代码获取国际化信息
            RequestContext requestContext = new RequestContext(request);
            model.addAttribute("money", requestContext.getMessage("money"));
            model.addAttribute("date", requestContext.getMessage("date"));

            
            FormatModel formatModel=new FormatModel();

            formatModel.setMoney(SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹SpringMVC學習系列(8) 之 國際化程式碼詳細介紹.SpringMVC學習系列(8) 之 國際化程式碼詳細介紹78);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }        return "globaltest";
    }
    
}
#########

运行测试:

SpringMVC學習系列(8) 之 國際化程式碼詳細介紹

SpringMVC學習系列(8) 之 國際化程式碼詳細介紹

关于bean id="localeResolver" class="org.springframework.web.servlet.iSpringMVC學習系列(8) 之 國際化程式碼詳細介紹8n.CookieLocaleResolver" />SpringMVC學習系列(8) 之 國際化程式碼詳細介紹个属性的说明(可以都不设置而用其默认值):

<bean>
    <!-- 设置cookieName名称,可以根据名称通过js来修改设置,也可以像上面演示的那样修改设置,默认的名称为 类名+LOCALE(即:org.springframework.web.servlet.iSpringMVC學習系列(8) 之 國際化程式碼詳細介紹8n.CookieLocaleResolver.LOCALE-->
    <property></property>
    <!-- 设置最大有效时间,如果是-SpringMVC學習系列(8) 之 國際化程式碼詳細介紹,则不存储,浏览器关闭后即失效,默认为Integer.MAX_INT-->
    <property>
    <!-- 设置cookie可见的地址,默认是“/”即对网站所有地址都是可见的,如果设为其它地址,则只有该地址或其后的地址才可见-->
    <property></property></property></bean>


四.基于URL请求的国际化的实现:

首先添加一个类,内容如下:

import java.util.Locale;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.DispatcherServlet;import org.springframework.web.servlet.LocaleResolver;public class MyAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver {    private Locale myLocal;    public Locale resolveLocale(HttpServletRequest request) {        return myLocal;
    } 

    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        myLocal = locale;
    }
  
}


然后把实现第二种方法时在项目的springservlet-config.xml文件中添加的

<bean></bean>


注释掉,并添加以下内容:

<bean></bean>


“xx.xxx.xxx”是刚才添加的MyAcceptHeaderLocaleResolver 类所在的包名。

保存之后就可以在请求的URL后附上 locale=zh_CN 或 locale=en_US 如 http://www.php.cn/ 来改变语言了,具体这里不再做演示了。


国际化部分的内容到此结束。

以上就是SpringMVC学习系列(8) 之 国际化代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
說明JVM如何充當Java代碼和基礎操作系統之間的中介。說明JVM如何充當Java代碼和基礎操作系統之間的中介。Apr 29, 2025 am 12:23 AM

JVM的工作原理是將Java代碼轉換為機器碼並管理資源。 1)類加載:加載.class文件到內存。 2)運行時數據區:管理內存區域。 3)執行引擎:解釋或編譯執行字節碼。 4)本地方法接口:通過JNI與操作系統交互。

解釋Java虛擬機(JVM)在Java平台獨立性中的作用。解釋Java虛擬機(JVM)在Java平台獨立性中的作用。Apr 29, 2025 am 12:21 AM

JVM使Java實現跨平台運行。 1)JVM加載、驗證和執行字節碼。 2)JVM的工作包括類加載、字節碼驗證、解釋執行和內存管理。 3)JVM支持高級功能如動態類加載和反射。

您將採取哪些步驟來確保Java應用程序在不同的操作系統上正確運行?您將採取哪些步驟來確保Java應用程序在不同的操作系統上正確運行?Apr 29, 2025 am 12:11 AM

Java應用可通過以下步驟在不同操作系統上運行:1)使用File或Paths類處理文件路徑;2)通過System.getenv()設置和獲取環境變量;3)利用Maven或Gradle管理依賴並測試。 Java的跨平台能力依賴於JVM的抽象層,但仍需手動處理某些操作系統特定的功能。

Java是否需要特定於平台的配置或調整區域?Java是否需要特定於平台的配置或調整區域?Apr 29, 2025 am 12:11 AM

Java在不同平台上需要進行特定配置和調優。 1)調整JVM參數,如-Xms和-Xmx設置堆大小。 2)選擇合適的垃圾回收策略,如ParallelGC或G1GC。 3)配置Native庫以適應不同平台,這些措施能讓Java應用在各種環境中發揮最佳性能。

哪些工具或庫可以幫助您解決Java開發中特定於平台的挑戰?哪些工具或庫可以幫助您解決Java開發中特定於平台的挑戰?Apr 29, 2025 am 12:01 AM

Osgi,Apachecommonslang,JNA和JvMoptionsareeForhandlingForhandlingPlatform-specificchallengesinjava.1)osgimanagesdeppedendendencenciesandisolatescomponents.2)apachecommonslangprovidesitorityfunctions.3)

JVM如何在不同平台上管理垃圾收集?JVM如何在不同平台上管理垃圾收集?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

為什麼Java代碼可以在不同的操作系統上運行,而無需修改?為什麼Java代碼可以在不同的操作系統上運行,而無需修改?Apr 28, 2025 am 12:14 AM

Java代碼可以在不同操作系統上無需修改即可運行,這是因為Java的“一次編寫,到處運行”哲學,由Java虛擬機(JVM)實現。 JVM作為編譯後的Java字節碼與操作系統之間的中介,將字節碼翻譯成特定機器指令,確保程序在任何安裝了JVM的平台上都能獨立運行。

描述編譯和執行Java程序的過程,突出平台獨立性。描述編譯和執行Java程序的過程,突出平台獨立性。Apr 28, 2025 am 12:08 AM

Java程序的編譯和執行通過字節碼和JVM實現平台獨立性。 1)編寫Java源碼並編譯成字節碼。 2)使用JVM在任何平台上執行字節碼,確保代碼的跨平台運行。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)