SpringBoot+Thymeleaf realizes internationalization

Preface

SpringBoot automatically configures the components that manage internationalized resource files

@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
    
    
/**
Comma-separated list of basenames, each following the ResourceBundle convention. 
Essentially a fully-qualified classpath location. 
If it doesn't contain a package qualifier (such as "org.mypackage"),
 it will be resolved from the classpath root.
*/
//我们的配置文件可以直接放在类路径下叫message.properties
private String basename = "messages";
@Bean
	public MessageSource messageSource() {
    
    
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		if (StringUtils.hasText(this.basename)) {
    
    
		    //设置国际化资源文件的基础名
			messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
					StringUtils.trimAllWhitespace(this.basename)));
		}
		if (this.encoding != null) {
    
    
			messageSource.setDefaultEncoding(this.encoding.name());
		}
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
		messageSource.setCacheSeconds(this.cacheSeconds);
		messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
		return messageSource;
	}
}
	

Specific operation

1. Create an international configuration file and place it in a folder under resources (only Chinese and English are configured here)
Insert picture description here
2. Open the configuration file login.properties configuration file, select Resource Bundle in the lower left corner of the middle part, and then select the middle Part of the upper left corner of the "+" sign, create a reference parameter, and then click into the parameter to configure the content displayed by the browser

Insert picture description here
3. In the application.properties configuration file, import the login.properties configuration file

spring.messages.basename=login/login

4. Writing html pages
First introduce the thymeleaf template engine in the html tags in the html page

<html lang="en" xmlns:th="http://www.thymeleaf.org">

Then write the parameters of login.properties in the body

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<div th:text="#{login.top}">hello world</div>
<div th:text="#{login.username}">username</div>
</body>
</html>

Write a HelloController and visit the html page

@Controller
public class HelloController {
    
    

   //查询数据在html页面展示
    @RequestMapping("/login")
    public String success(){
    
    
        return "login";
    }
}

So if the language of the browser is Chinese, the configuration information in Chinese will be displayed, and the configuration information in English will be displayed in English.
Insert picture description here

If the Chinese shows garbled characters, you need to modify some of the configuration of idea

Insert picture description here

principle:

Internationalized Locale (regional information object) has a component LocaleResolve (obtaining regional object information);

		@Bean
		@ConditionalOnMissingBean
		@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
		public LocaleResolver localeResolver() {
    
    
			if (this.mvcProperties
					.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
    
    
				return new FixedLocaleResolver(this.mvcProperties.getLocale());
			}
			AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
			localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
			return localeResolver;
		}
		//默认的就是根据请求头带来的区域信息获取Locale进行国际化

Insert picture description here

Click the link to switch internationalization

1. Create a component MyLocaleResolver to let him inherit LocaleResolver and then rewrite the method inside

/**
 * 可以在连接上携带区域信息
 */
public class MyLocaleResolver implements LocaleResolver {
    
    
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
    
    
        //获取参数的值
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        //如果不为null
        if (!StringUtils.isEmpty(l)){
    
    
            String[] split = l.split("_");
            locale = new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    
    

    }
}

2. Write a configuration class MyMvcConfig to make this component effective

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

3. Improve the html page

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<div th:text="#{login.top}">hello world</div>
<div th:text="#{login.username}">username</div>
<a th:href="@{/login.html(l='zh_CN')}">中文</a>
<a th:href="@{/login.html(l='en_US')}">英文</a>
</body>
</html>

Click Chinese or English to switch the corresponding content
Insert picture description here

Guess you like

Origin blog.csdn.net/javaasd/article/details/113971016