SpringMVC简单实现国际化/多语言


开发工具:intellij idea2018.2;环境:springMVC

1、jar包

pom.xml部分代码

<!-- jstl相关jar包-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
 
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

2、spring-mvc.xml部分代码

 <!-- 注解扫描 -->
    <context:component-scan base-package="com.hys.**.action"/>
    <!-- 使用mvc注解声明 -->
    <mvc:annotation-driven/>
    <!-- 处理静态资源(js,css,html) -->
    <mvc:default-servlet-handler/>
 
    <!-- 国际化配置start -->
    <!-- 主要用于获取请求中的locale信息,将其转为Locale对像,获取LocaleResolver对象-->
    <mvc:interceptors>
        <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
    </mvc:interceptors>
 
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <!-- 表示语言配置文件是以language开头的文件(language_zh_CN.properties)-->
        <property name="basename" value="language"/>
        <!-- 语言区域里没有找到对应的国际化文件时,默认使用language.properties文件-->
        <property name="useCodeAsDefaultMessage" value="true" />
    </bean>
 
    <!-- 配置SessionLocaleResolver用于将Locale对象存储于Session中供后续使用 -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>

3、创建国际化文件

 

 

 右击resources资源文件new》Resource Bundle

 

 

 

 

 

 

4、测试页面

java代码:

package com.hys.userlogin.action;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class UserLoginAction {
 
    @RequestMapping(value = "/submitLogin")
    public String submitLogin() {
 
        return "index";
    }
}

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--<fmt:message key="messages.username"/>--%>
<fmt:message key="language.username"/>:<input type="text" name="username"/><br/>
<fmt:message key="language.password"/>:<input type="text" name="password"/><br/>
 
Language:
<a href="?locale=zh_CN">中文</a>&nbsp;&nbsp;
<a href="?locale=en_US">英文</a><br/>
当前语言: ${pageContext.response.locale}
</body>
</html>

测试结果:

中文:http://localhost:8080/submitLogi

 

 

 

 
英文:http://localhost:8080/submitLogin?locale=en_US

转载于:https://blog.csdn.net/xqhys/article/details/81413053


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM