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