spring 页面国际化

页面国际化

1.修改编码类型

setting ---file encodings

2.确保所有编码都改为utf-8 properties处打勾

3.新建一个目录 i18n

4.在i18n下面创建 message.properties message_zh_CN.properties

5.右击快捷添加 en_US 英文

6.Resource bundle中可快速配置

7.在配置文件中yaml

spring.messages.basename=i18n.message

8.此时在前端写 th:text="#{参数}",就可以自动识别语言

9.自己重载一个解析器,这个用到http 交换中

package com.wang.config;

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 {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //获取请求中的语言参数,带来l的参数,参考别人怎么写的
        String language = request.getParameter("l");
        Locale locale= Locale.getDefault();

        if(StringUtils.isEmpty(language)){
            String[] split = language.split("_"); //分割成为数组
            //分割国家地区
            locale = new Locale(split[0], split[1]);

        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

写完后注入spring bean中,

@configuration修饰 @Bean

10.工具类

package com.wang.Service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import java.util.Locale;

@Component
public class MessageService {

    @Autowired
    MessageSource messageSource;

    Locale currentLocale = new Locale("en","US");

    @Bean
    public static MessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("i18n/message");
        messageSource.setCacheSeconds(5);
        return messageSource;
    }

    public String getMessage(String key) {
        return messageSource.getMessage(key, null, key, currentLocale);
    }
}

上一篇:c# – 隐私违规Checkmarx


下一篇:springSecurity修改默认错误提示信息