专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

Spring MVC 教程(八)国际化

一、页面国际化

1、在pom.xml引入国际化需要的依赖

 <!--国际化相关依赖 begin  -->
     <dependency>
       <groupId>jstl</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
     </dependency>
 <!--国际化相关依赖 end  -->

2、在success.jsp里面添加jstl的fmt

 <%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

3、在springmvc.xml里面国际化资源文件

 <!-- 配置国际化资源文件 -->
     <bean id="messageSource"
         class="org.springframework.context.support.ResourceBundleMessageSource">
         <property name="basename" value="i18n"></property>    
     </bean>

4、src/main/java新建国际化资源文件

i18n.properties

 i18n.username=Username
 i18n.password=Password

i18n_zh_CN.properties

 i18n.username=\u7528\u6237\u540D
 i18n.password=\u5BC6\u7801

i18n_en_US.properties

 i18n.username=Username
 i18n.password=Password

5、在success.jsp页面通过jstl的标签获取值

 <!--国际化 begin  -->
 <p><b>国际化 begin</b></p>
 <fmt:message key="i18n.username"></fmt:message>
 <br>
 <fmt:message key="i18n.password"></fmt:message>
 <p><b>国际化 end</b></p>    
 <!--国际化 end  -->

72_1.png

二、java代码国际化(依赖于i18n_zh_CN.properties和i18n_en_US.properties)

1、注入ResourceBundleMessageSource

 @Autowired
 private ResourceBundleMessageSource messageSource;

2、 通过getMessage方法获取国际化资源

 @RequestMapping("/i18n")
     public String testI18n(Locale locale){
         String val = messageSource.getMessage("i18n.user", null, locale);
         System.out.println(val); 
         return "i18n";
     }

三、点击超链接切换语言进行页面国际化(全局国际化)

(依赖于一的fmt标签、i18n_zh_CN.properties和i18n_en_US.properties)

原理如下:

1、LocaleChanceInterceptor拦截器获取local对象

2、 SessionLocalResolver解析器把local对象放到session里面

3、应用程序从session里面获取local对象进行国际化

72_2.png

1、在jsp页面设置语言切换链接

 <a href="i18n?locale=zh_CH">中文</a>

 <br><br>
 <a href="i18n?locale=en_US">英文</a>

2、在springmvc.xml文件里面配置SessionLocaleResolver和LocaleChangeInterceptor

 <!-- 配置 SessionLocalResolver -->
     <bean id="localeResolver"
         class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>

     <mvc:interceptors>

         <!-- 配置 LocaleChanceInterceptor -->
         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
     </mvc:interceptors>

https://www.cnblogs.com/leeSmall/category/1093236.html

文章永久链接:https://tech.souyunku.com/13913

未经允许不得转载:搜云库技术团队 » Spring MVC 教程(八)国际化

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们