SpringBoot國際化(jsp)

原來的項(xiàng)目用的是jsp,改成html太麻煩,這里介紹一下jsp國際化的(如果是html使用thymeleaf,它自帶了的):

#國際化標(biāo)簽
<spring:message code='xxx'/>

1.項(xiàng)目路徑如圖:


image.png

2.相關(guān)依賴:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- tomcat的支持-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- servlet依賴 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>

3.新增I18nConfig(設(shè)置默認(rèn)語言)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Locale;

/**
 * 設(shè)置默認(rèn)語言
 *
 * @author xxx
 * @date 2019/12/30
 * @since 1.0.0
 */
@Configuration
public class I18nConfig {

    private static Logger logger = LoggerFactory.getLogger(I18nConfig.class);

    @Bean(name = "localeResolver")
    public LocaleResolver localeResolver() {
        logger.info("創(chuàng)建cookieLocaleResolver");

        LocaleResolver localeResolver = new LocaleResolver();
        localeResolver.setDefaultLocale(Locale.CHINA);
        logger.info("cookieLocaleResolver:");
        return localeResolver;
    }

}

4.新增LocaleResolver(修改local的值)文件

import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 每次加載頁面時都會被調(diào)用,加載頁面時都會設(shè)置并修改語言
 *
 * @author xxx
 * @date 2019/12/30
 * @since 1.0.0
 */
public class LocaleResolver extends AcceptHeaderLocaleResolver {

    private Locale myLocal;

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //獲取cookie數(shù)組
        Cookie[] cookies = request.getCookies();
        String lang = "";
        if (cookies != null) {
            //遍歷cookie數(shù)組
            for (Cookie cookie : cookies) {
                if ("ClientLanguage".equals(cookie.getName())) {
                    lang = cookie.getValue();
                    break;
                }
            }
        }
        LocaleResolver localeResolver = (LocaleResolver) RequestContextUtils.getLocaleResolver(request);
        if (lang == null || "".equals(lang)) {
            myLocal = Locale.CHINA;
        } else {
            if (lang.equals("zh")) {
                myLocal = Locale.CHINA;
            } else if (lang.equals("en")) {
                myLocal = Locale.ENGLISH;
            }
        }
        return myLocal;
    }

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

5.application.yml文件

spring:
  http:
    encoding:
      charset: UTF-8
  mvc:
    view:
      prefix: /WEB-INF/view/
      suffix: .jsp
  messages:
    basename: i18n.messages
    cache-duration: 3600
    encoding: UTF-8
server:
  port: 80
  tomcat:
    uri-encoding: UTF-8
    max-threads: 100
    min-spare-threads: 30
  servlet:
    context-path: /ChineseDemo

6.新建messages.properties,messages_zh.properties,messages_en.properties個文件:

  • messages為默認(rèn)語言,zh中文,en英文
  • messages和zh文件內(nèi)容:
commom.xxx.logout=登出
commom.xxx.login=登錄
  • en文件內(nèi)容:
commom.xxx.logout=logout
commom.xxx.login=login

7.index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<spring:message code='commom.xxx.logout'/>
<spring:message code='commom.xxx.login'/>

<a href="javascript:;" onclick="changeLang('zh')"> 中文 </a>
<a href="javascript:;" onclick="changeLang('en')"> english </a>
</body>
<script>
    function changeLang(lang) {
        //cookie持久化
        $.cookie = "ClientLanguage=" + lang;
        location.reload();
    }
</script>
</html>

效果:


中文

英文
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容