spring boot 国际化

  作者:记性不好的阁主

1、准备三个配置文件


在i资源目录下的18n目录下创建三个配置文件分别为默认、英文、中文




2、点击Bundle进行统一编写





点击'+'号添加key




编写完毕


3、指定资源文件路径


若不配置,默认会去找classpath:messages.properties

这里指定配置i18n路径下的login.properties


spring.messages.basename=i18n.login


4、在html页面中引入需要国际化的字段




5、浏览器切换语言即可看到对应的语言显示


5、实现点击对应的链接显示对应的语言


页面:




链接:




6、编写国际化组件


国际化组件目录结构





编写自定义国际化解析器 MyLocaleResolver


package com.laoxu.springboot.component;

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

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

public class MyLocaleResolver implements LocaleResolver {

//检查 参数l 是否为空
//为空
//则使用系统默认
//不为空
//则分割字符串
// 1.zh_CN ---> zh CN
// 2.en_US ---> en US
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}

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

}
}


将解析器配置加入到容器中使之生效


package com.laoxu.springboot.controller;

import com.laoxu.springboot.component.LoginHandlerInterceptor;
import com.laoxu.springboot.component.MyLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
* 配置静态资源映射
*
* @author sunziwen
* @version 1.0
* @date 2018-11-16 14:57
**/
@Component
public class WebConfig implements WebMvcConfigurer {
/**
* 添加静态资源文件,外部可以直接访问地址
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {

}

@Override
public void addInterceptors(InterceptorRegistry registry) {

}
    //配置国际化解析器加入到容器中
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}


}


运行时url加上参数 ?l=zh_CN 表示中文

运行时url加上参数 ?l=en_US 表示英文


相关推荐

评论 抢沙发

表情

分类选择