search
HomeJavajavaTutorialSpringMVC Learning Series (8) Detailed introduction to international code

In series (7) we talked about the formatted display of data. Spring has already done internationalization processing when formatting the display. So how to internationalize other content of our website (such as menus, titles, etc.) What about chemical treatment? This is the content of this article -> internationalization.

SpringMVC Learning Series (8) Detailed introduction to international code. International implementation based on browser request:

First configure the springservlet-config.xml file of our project and add the following content:

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


Add GlobalController.java in the com.demo.web.controllers package as follows:

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 Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international code.SpringMVC Learning Series (8) Detailed introduction to international code78);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }        return "globaltest";
    }
    
}


The model shown here also uses the functions in series (7) Demo.

Add three files: messages.properties, messages_zh_CN.properties, and messages_en_US.properties to the source folder resources in the project. Among them, "money" and "date" in messages.properties and messages_zh_CN.properties are Chinese, messages_en_US.properties are in English.

Add the globaltest.jsp view in the views folder with the following content:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (8) Detailed introduction to international codeC//DTD HTML SpringMVC Learning Series (8) Detailed introduction to international code.0SpringMVC Learning Series (8) Detailed introduction to international code Transitional//EN" "http://www.wSpringMVC Learning Series (8) Detailed introduction to international code.org/TR/htmlSpringMVC Learning Series (8) Detailed introduction to international code/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>
    


Run the test:

SpringMVC Learning Series (8) Detailed introduction to international code

Change the browser language order and refresh the page:

SpringMVC Learning Series (8) Detailed introduction to international code

SpringMVC Learning Series (8) Detailed introduction to international code. Session-based internationalization implementation:

In The content added to the project's springservlet-config.xml file is as follows (the content added in the first method should be retained):

<interceptors>  
    <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> 
    <bean learning series detailed introduction to international code8n.localechangeinterceptor></bean>  </interceptors>  <bean learning series detailed introduction to international code8n.sessionlocaleresolver></bean>


Change the globaltest.jsp view to the following content:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (8) Detailed introduction to international codeC//DTD HTML SpringMVC Learning Series (8) Detailed introduction to international code.0SpringMVC Learning Series (8) Detailed introduction to international code Transitional//EN" "http://www.wSpringMVC Learning Series (8) Detailed introduction to international code.org/TR/htmlSpringMVC Learning Series (8) Detailed introduction to international code/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>
    


Change GlobalController.java to the following content:

package com.demo.web.controllers;import java.util.Date;import java.util.Locale;import javax.servlet.http.HttpServletRequest;import org.springframework.context.iSpringMVC Learning Series (8) Detailed introduction to international code8n.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 Learning Series (8) Detailed introduction to international code8n.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 Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international code.SpringMVC Learning Series (8) Detailed introduction to international code78);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }        return "globaltest";
    }
    
}


Run the test:

SpringMVC Learning Series (8) Detailed introduction to international code

SpringMVC Learning Series (8) Detailed introduction to international code

SpringMVC Learning Series (8) Detailed introduction to international code. Cookie-based internationalization implementation:

Implement the second method in the project's springservlet-config Comment out the

<bean learning series detailed introduction to international code8n.sessionlocaleresolver></bean>


added in the .xml file and add the following:

<bean learning series detailed introduction to international code8n.cookielocaleresolver></bean>

##Change GlobalController.java For the following content:

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 Learning Series (8) Detailed introduction to international code8n.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 Learning Series (8) Detailed introduction to international code8n.CookieLocaleResolver;//import org.springframework.web.servlet.iSpringMVC Learning Series (8) Detailed introduction to international code8n.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 Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international codeSpringMVC Learning Series (8) Detailed introduction to international code.SpringMVC Learning Series (8) Detailed introduction to international code78);
            formatModel.setDate(new Date());
            
            model.addAttribute("contentModel", formatModel);
        }        return "globaltest";
    }
    
}

运行测试:

SpringMVC Learning Series (8) Detailed introduction to international code

SpringMVC Learning Series (8) Detailed introduction to international code

关于bean id="localeResolver" class="org.springframework.web.servlet.iSpringMVC Learning Series (8) Detailed introduction to international code8n.CookieLocaleResolver" />SpringMVC Learning Series (8) Detailed introduction to international code个属性的说明(可以都不设置而用其默认值):

<bean learning series detailed introduction to international code8n.cookielocaleresolver>
    <!-- 设置cookieName名称,可以根据名称通过js来修改设置,也可以像上面演示的那样修改设置,默认的名称为 类名+LOCALE(即:org.springframework.web.servlet.iSpringMVC Learning Series (8) Detailed introduction to international code8n.CookieLocaleResolver.LOCALE-->
    <property></property>
    <!-- 设置最大有效时间,如果是-SpringMVC Learning Series (8) Detailed introduction to international code,则不存储,浏览器关闭后即失效,默认为Integer.MAX_INT-->
    <property learning series detailed introduction to international code00000>
    <!-- 设置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 learning series detailed introduction to international code8n.sessionlocaleresolver></bean>


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

<bean></bean>


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

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


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

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


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Are there any areas where Java requires platform-specific configuration or tuning?Are there any areas where Java requires platform-specific configuration or tuning?Apr 29, 2025 am 12:11 AM

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

What are some tools or libraries that can help you address platform-specific challenges in Java development?What are some tools or libraries that can help you address platform-specific challenges in Java development?Apr 29, 2025 am 12:01 AM

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

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

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment