我们可以将Springboot结合thymeleaf进行国际化。
首先,我们新建项目,项目结构如下:
第一步,我们在pom.xml文件中引入thymeleaf jar包
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zk.myspringboot_012</groupId> <artifactId>myspringboot_012</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>myspringboot_012 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- 继承父包 --> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1-1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <build> <finalName>myspringboot_012</finalName> </build> </project>
第二步,我们配置属性文件application.properties、message_en_US.properties、message_zh_CN.properties、message.properties
application.properties
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/ spring.messages.basename=message
message_en_US.properties
username=username password=123456
message_zh_CN.properties
username=用户名 password=123456
message.properties
username=用户名 password=123456
第三步,我们创建index.html文件,主界面文件
index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"></meta> <title>Index首页</title> </head> <body> 点击切换语言: <a href="?lang=zh_CN">简体中文</a> <a href="?lang=en_US">English(US)</a><br/> <p> <h2 th:text="#{username}"></h2> <h2 th:text="#{password}"></h2> </p> </body> </html>
第四步,我们编写控制器IndexController.java
IndexController.java
package com.zk.myspringboot; import java.util.Locale; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @Controller public class IndexController { @Autowired private MessageSource messageSource; @RequestMapping("/demo") public String index(Model model) { Locale locale1 = LocaleContextHolder.getLocale(); model.addAttribute("username", messageSource.getMessage("username", null, locale1)); model.addAttribute("password", messageSource.getMessage("password", null, locale1)); return "index"; } }
第五步,配置使其可以当请求参数中携带语言参数时自动切换语言,编写自定义的MyLocaleResolver.java
MyLocaleResolver.java
package com.zk.myspringboot; 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; /** * SpringBoot默认的Locale解析器是根据请求头的区域信息进行解析的(浏览器语言) * 使用自定义的Locale解析器对url的区域信息进行解析达到点击切换区域效果 * 一旦我们自定义的区域解析器注册到Spring容器中,则SpringBoot提供的将不自动注册 */ public class MyLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest httpServletRequest) { String l = httpServletRequest.getParameter("l"); if(!StringUtils.isEmpty((l))){ String [] s = l.split("_"); return new Locale(s[0],s[1]); } return Locale.getDefault(); } @Override public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } }
第六步,把配置加入SpringBoot容器中,新建WebConfiguration.java
WebConfiguration.java
package com.zk.myspringboot; import java.util.List; import java.util.Locale; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; @Configuration public class WebConfiguration implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { //设置对“/”的请求映射到index //如果没有数据返回到页面,没有必要用控制器方法对请求进行映射 registry.addViewController("/").setViewName("index"); } //注册我们自定义的区域解析器,一旦将我们的区域解析器注册到Spring容器中则SpingBoot //默认提供的区域解析器将不会自动注册 @Bean public LocaleResolver localeResolver(){ CookieLocaleResolver localeResolver = new CookieLocaleResolver(); localeResolver.setCookieName("localeCookie"); //设置默认区域 localeResolver.setDefaultLocale(Locale.ENGLISH); localeResolver.setCookieMaxAge(3600);//设置cookie有效期. return localeResolver; } @Override public void configurePathMatch(PathMatchConfigurer configurer) { // TODO Auto-generated method stub } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { // TODO Auto-generated method stub } @Override public void configureAsyncSupport(AsyncSupportConfigurer configurer) { // TODO Auto-generated method stub } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { // TODO Auto-generated method stub } @Override public void addFormatters(FormatterRegistry registry) { // TODO Auto-generated method stub } @Override public void addInterceptors(InterceptorRegistry registry) { // TODO Auto-generated method stub registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // TODO Auto-generated method stub } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); // 参数名 lci.setParamName("lang"); return lci; } @Override public void addCorsMappings(CorsRegistry registry) { // TODO Auto-generated method stub } @Override public void configureViewResolvers(ViewResolverRegistry registry) { // TODO Auto-generated method stub } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // TODO Auto-generated method stub } @Override public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { // TODO Auto-generated method stub } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // TODO Auto-generated method stub } @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // TODO Auto-generated method stub } @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { // TODO Auto-generated method stub } @Override public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { // TODO Auto-generated method stub } @Override public Validator getValidator() { // TODO Auto-generated method stub return null; } @Override public MessageCodesResolver getMessageCodesResolver() { // TODO Auto-generated method stub return null; } }
最后设置启动类,DemoApplication.java
DemoApplication.java
package com.zk.myspringboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
测试结果如下:
原文:https://www.cnblogs.com/longlyseul/p/12747474.html