SpringBoot实现国际化

1.效果

点击中文/English切换中英文
在这里插入图片描述
在这里插入图片描述

2.配置文件

application.properties

#国际化配置
spring.messages.basename=i18n.login

在这里插入图片描述
login.properties

login.tip=请登录
login.email=邮箱地址
login.password=密码
login.remember=记住我
login.submit=登陆

login_en_US.properties

login.tip=Please sign in
login.email=Email address
login.password=Password
login.remember=remember-me
login.submit=Sign in

login_zh_CN.properties

login.tip=请登录
login.email=邮箱地址
login.password=密码
login.remember=记住我
login.submit=登陆

3.自定义MyLocaleResolver以及配置类

MyLocaleResolver

package cn.yf.springboot_crud.component;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

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

public class MyLocaleResolver implements LocaleResolver {
    /**
     * Resolve the current locale via the given request.
     * Can return a default locale as fallback in any case.
     *
     * @param request the request to resolve the locale for
     * @return the current locale (never {@code null})
     */
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if(!StringUtils.isEmpty(l)){
            String[] strings = l.split("_");
            locale = new Locale(strings[0],strings[1]);
        }
        return locale;
    }

    /**
     * Set the current locale to the given one.
     *
     * @param request  the request to be used for locale modification
     * @param response the response to be used for locale modification
     * @param locale   the new locale, or {@code null} to clear the locale
     * @throws UnsupportedOperationException if the LocaleResolver
     *                                       implementation does not support dynamic changing of the locale
     */
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}

MyMvcConfig

package cn.yf.springboot_crud.config;

import cn.yf.springboot_crud.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

@Configuration
public class MyMvcConfig {

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }

}

4.index.html

		<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
        <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值