SpringBoot-7 internationalization

Posted by magaly on Mon, 21 Feb 2022 12:57:41 +0100

SpringBoot-7 internationalization

This article uses SpringBoot+Thymeleaf to explain the internationalization of springboot. If you don't know Thymeleaf well, you can check my previous articles. Code word is not easy to hope that you can pay attention to my official account. Your concern is my greatest support. Thank you. At the end of the article, my official account number 2 D code can also search for springboot sunflower treasure book for attention. Reply: springboot, you can get some SpringBoot learning materials collected by some bloggers.

SpringBoot-5 - page showing Thymeleaf

SpringBoot-6-template Thymeleaf common tags

Introduction to internationalization

The internationalization of springboot is an issue that all of us should consider when making international websites. Springboot has strong support for internationalization. Internationalization is also called i18n. Why is it called i18n? This is because the International English word is internationalization, which contains 18 words between i and n. This paper introduces the internationalization of springboot by introducing a case.

1. Three ways of springboot internationalization

There are three ways to use Springboot Internationalization:

  • AcceptHeaderLocaleResolver (the default parser determines the environment of the current request through the accept language field of the request header, and then gives an appropriate response)

  • SessionLocaleResolver

  • CookieLocaleResolver

The default AcceptHeaderLocaleResolver implements internationalization

By default, the internationalization folder is directly placed in the src\main\resources folder. We create three test files, as shown in the figure:

  • When we create the messages file, we directly create it in the src\main\resources directory. At this time, the IDEA will display an additional Resource Bundle. Don't worry about it. Don't create this directory manually.

  • messages.properties is the default configuration, while others are configured in different locales, en_US is English (USA), zh_CN is simplified Chinese.

  • Chinese cannot be displayed normally without setting.

You can enter File Encoding in the settings of idea, and then set it all to UTF-8.

Result after setting:

In the three created and files, write the following contents respectively:

messages_en_US.properties

name=Nameage=Ageemail=Emailphone=Phone

messages_zh_CN.properties

name=full name age=Age email=mailbox phone=Telephone

Note: the MessageSource that needs to be configured in spring does not need to be configured now. Spring Boot will go through org springframework. boot. autoconfigure. context. Automatically configure an instance of messagesourceautoconfiguration for us.

Create a TestController as follows:

@Controllerpublic class TestController {    @GetMapping("/")    public String index(Model model) {        Student stu1 = new Student("Zhang San", 20, "1155@qq.com", "13333835901");        Student stu2 = new Student("Li Si", 21, "1154@qq.com", "13333835902");        Student stu3 = new Student("Wang Wu", 22, "1153@qq.com", "13333835903");        Student stu4 = new Student("Xiao Fang", 23, "1156@qq.com", "13333835904");        ArrayList<Student> stus = new ArrayList<>();        stus.add(stu1);        stus.add(stu2);        stus.add(stu3);        stus.add(stu4);        model.addAttribute("stus", stus);        return "index";    }}

Create an entity class

@Data@AllArgsConstructorpublic class Student {    private String name;    private int age;    private String email;    private String phone;}

Create an index in the src\main\resources\templates directory HTML, as follows

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"      xmlns:th="http://www.thymeleaf.org"><head >    <meta charset="UTF-8">    <title>index</title>    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">    <link rel="stylesheet" th:href="@{/css/dashboard.css}">    <script th:src="@{/js/jquery-3.3.1.min.js}"></script>    <script th:src="@{/js/bootstrap.min.js}"></script></head><body><div>    <table border="1" cellspacing="0">        <tr>            <th th:text="#{name}"></th>            <th th:text="#{age}"></th>            <th th:text="#{email}"></th>            <th th:text="#{phone}"></th>        </tr>        <tr th:each="stu:${stus}">            <td th:text="${stu.name}"></td>            <td th:text="${stu.age}"></td>            <td th:text="${stu.email}"></td>            <td th:text="${stu.phone}"></td>        </tr>    </table></div></body></html>

Using POSTMAN, set the accept language to zh CN and en US in the request header respectively. The results are as follows:

Custom switch Local saving method

Sometimes we feel that it is inconvenient to put the switching parameters into the request header. At this time, we can conduct custom parsing. SessionLocaleResolver saves the client's Locale to the HttpSession object, and CookieLocaleResolver saves the LOCAL to the Cookie.

No matter what kind of customized LocalResolver, you need to define LocaleChangeInterceptor, which is used to intercept the parameter whose key is lang in the request (locale if not configured), and this parameter specifies the current environment information.

    @Override    public void addInterceptors(InterceptorRegistry registry) {        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();        interceptor.setParamName("lang");        registry.addInterceptor(interceptor);    }

If SessionLocaleResolver is used

    @Bean    LocaleResolver localeResolver() {        SessionLocaleResolver localeResolver = new SessionLocaleResolver();        localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);        return localeResolver;    }

If SessionLocaleResolver is used

    @Bean    public LocaleResolver localeResolver() {        SessionLocaleResolver slr = new SessionLocaleResolver();        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);        return slr;    }

Start separate access after configuration

http://localhost:8080/?lang=zh-CNhttp://localhost:8080/?lang=en-US

The results are as follows:

Other customization

If messages do not want to be stored in src\main\resources \ directory, you can use the following to modify and save the file in src\main\resources\i18n and messages:

spring:  thymeleaf:    cache: false  messages:    basename: i18n/messages

Other codes

spring:  messages:    cache-duration: 1800    encoding: UTF-8    fallback-to-system-locale: true
  • spring. messages. Cache duration indicates the cache expiration time of the file

  • Fallback to system locale means that if the attribute is true, the resource file corresponding to the current system will be found by default. Otherwise, null will be returned. After null is returned, the system will eventually call the default messages Properties file.

If you think this article is good, welcome Star's support. Your attention is the driving force of my persistence!

Original is not easy, reprint please indicate the source, thank you for your support! If this article is useful to you, welcome to forward and share!

Topics: Java Spring Spring Boot