Internationalization-related

Time:2019-8-11

Internationalization-related

Notes to the next paragraph:

/***
 * ┌───┐   ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┐
 * │Esc│   │ F1│ F2│ F3│ F4│ │ F5│ F6│ F7│ F8│ │ F9│F10│F11│F12│ │P/S│S L│P/B│  ┌┐    ┌┐    ┌┐
 * └───┘   └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┘  └┘    └┘    └┘
 * ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐ ┌───┬───┬───┐ ┌───┬───┬───┬───┐
 * │~ `│! 1│@ 2│# 3│$ 4│% 5│^ 6│& 7│* 8│( 9│) 0│_ -│+ =│ BacSp │ │Ins│Hom│PUp│ │N L│ / │ * │ - │
 * ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤ ├───┼───┼───┤ ├───┼───┼───┼───┤
 * │ Tab │ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │{ [│} ]│ | \ │ │Del│End│PDn│ │ 7 │ 8 │ 9 │   │
 * ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴─────┤ └───┴───┴───┘ ├───┼───┼───┤ + │
 * │ Caps │ A │ S │ D │ F │ G │ H │ J │ K │ L │: ;│" '│ Enter  │               │ 4 │ 5 │ 6 │   │
 * ├──────┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴────────┤     ┌───┐     ├───┼───┼───┼───┤
 * │ Shift  │ Z │ X │ C │ V │ B │ N │ M │< ,│> .│? /│  Shift   │     │ ↑ │     │ 1 │ 2 │ 3 │   │
 * ├─────┬──┴─┬─┴──┬┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤ ┌───┼───┼───┐ ├───┴───┼───┤ E││
 * │ Ctrl│    │Alt │         Space         │ Alt│    │    │Ctrl│ │ ← │ ↓ │ → │ │   0   │ . │<─┘│
 * └─────┴────┴────┴───────────────────────┴────┴────┴────┴────┘ └───┴───┴───┘ └───────┴───┴───┘
 */
  1. Default Access to Home Page
// Spring MVC can be extended with WebMvc Configurer Adapter@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {  
@Override
public voidAddViewControllers (ViewController Registry Registry){);
} 

//All WebMvc Configurer Adapter components work together WebMvcConfigurerAdapter webMvcConfigurerAdapter(){ WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login");
// The index. HTML request goes to login, which locates the home page login); } }; return adapter; } }

2. Internationalization

  • Writing international configuration files
  • UseResource Bundle Message Source manages international resource files
  • Use on the pageFmt: Message takes out international content.

Steps:

  • Write an internationalization profile to extract the internationalization messages that the page needs to display

 

  • Springboot automatically configures components for managing international resource files
@ Configuration Properties (prefix = spring. messages)
if (this.encoding != null) { messageSource.setDefaultEncoding(this.encoding.name());     }
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale); messageSource.setCacheSeconds(this.cacheSeconds); messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat); return messageSource; }
  • Go to the page to get internationalized values

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http‐equiv="Content‐Type" content="text/html; charset=UTF‐8">
<meta name="viewport" content="width=device‐width, initial‐scale=1, shrink‐to‐
fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template for Bootstrap</title>
<!‐‐ Bootstrap core CSS ‐‐>
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<!‐‐ Custom styles for this template ‐‐>
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}"rel="stylesheet">
</head> <body class="text‐center"> <form class="form‐signin" action="dashboard.html"> <img class="mb‐4" th:src="@{/asserts/img/bootstrap‐solid.svg}" src="asserts/img/bootstrap‐solid.svg" alt="" width="72" height="72"> <h1 class="h3 mb‐3 font‐weight‐normal" th:text="#{login.tip}">Please signin</h1> <label class="sr‐only" th:text="#{login.username}">Username</label> <input type="text" class="form‐control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""> <label class="sr‐only" th:text="#{login.password}">Password</label> <input type="password" class="form‐control" placeholder="Password" th:placeholder="#{login.password}" required="">
<div class= "checkbox MB 3">

Effect:

According to the information set by browser language, it is internationalized.

Principle:

InternationalizationLocale(Regional information object);LocaleResolver(Obtaining regional information objects);

@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 ();
  • Click on Link to Switch Internationalization
* *
@Bean public LocaleResolver localeResolver(){     return new MyLocaleResolver();   } }

3. Landing

After the template engine page is modified, some operations are needed to take effect in real time.

1. Disable template caching

spring.thymeleaf.cache=false

2. After page modification, Ctrl + F9 is recompiled

Message display of login error

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

4. Use interceptors for landing checks

/**
* Landing inspection,
*/
public class LoginHandlerInterceptor implements HandlerInterceptor {
// Before the target method is executed
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if(user == null){
// No login, return to the login page
Request. setAttribute ("msg", "login first if you have no permission");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
// Landed, released request
return true;
    }
}
 @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
    handler, ModelAndView modelAndView) throws Exception {
}
 @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
    }
}

Registered Interceptor

// All WebMvc Configurer Adapter components work together
// Registered Interceptor

 

Refer to other people’s details

Detailed internationalization configuration

Sounds tall and internationalized, starting with the use of browser language, or Chinese-English switching in the page, the text of the page will be switched in other languages and Chinese, such as:

We want to make this function come true. Click on Chinese, the page is Chinese, and click on English is English.

Internationalization Configuration

So let’s see, SpringBoot defaults to switch between Chinese and English according to the language of your browser. Configuration files, we can write in resources as follows:

 

1. Create a new package called “i18n”, which we use to store international configuration. Then under this package, we create several properties configuration files to configure the language:

As shown in the figure, we create three files, which are login. properties in effect when there is no language configuration, login_zh_CN. properties in Chinese, and login_en_US. properties in English.

That is, the combination of underlining: filename region language. properties; when we name the generated file like this, IDEA will also help us identify it as an international configuration package and automatically convert it into the following pattern:

Of course, when it becomes the above mode, we need to add the configuration file, just right-click new in the package.

It’s much more convenient.~

 

2. We need to make some changes in these configuration files. First, click the login_en_US configuration file, and then click the Resource Bundle button shown below to switch the editing mode:

According to the method shown in the figure, click on the plus sign and add a key. Our name is login. tip, which means the prompt used in the page.

Next, according to the amount of conversion we need on our page, we configure it as follows (I have configured all the login pages I need to use later):

It’s not over yet. Don’t worry. It looks complicated. It’s easy to learn. Later we need to refer to these values on the page and look at them.

Remember to add configuration parameters to our application. properties to make our configuration work:

spring.messages.basename=i18n.login

HTML Pages – Configuration

Based on previous articles, we learned about the role of @ and # in Thymeleaf’s grammar. Let’s see how to use them.

In the front form, we set all the required parameters in the form of {xx.yy} according to the internationalized parameters of the configuration. In order to use the template, we need to replace the original parameters with parameters such as th: text. (Note that the original page has the same text, placeholder, etc.)

For the Thymeleaf template to take effect, don’t forget to add this xmlns to the HTML parameters:

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

In this way, we can switch between Chinese and English in the case of switching the browser language. We can use chrome as an example to set up the method.

 

 

Custom Configuration to Make Chinese-English Switching in Our Page Effective

 

Patient students, let’s take a look at the main topic, how to make their configuration effective:

1. The screenshot at the top of the article, we see the HTML of Chinese and English buttons. Let’s see how to configure it:

Note that the page I’m going to visit here is actually: localhost: 8080 / index. html? L = zh_CN, which is also the link we generated when we clicked the Chinese button. In Thymeleaf’s template grammar, parameters are not used “?” Instead, parentheses are used, and then the parameters are set in the form of key = value, paying attention to single quotation marks.

2. In order to make the customized configuration work, what we need to do is to override or change the default configuration. Then we create a new file named MyLocaleResolver to implement the function of the LocaleResolver interface.

Specific method: (because our region is configured with an underscore “”, so here we use a separator to get the region and language, and put it in the request)

package com.iceodin.common.component;

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;

/**
 * Carry area information on links
 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.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) {

    }
}

3. Let our configuration take effect, of course, by adding the configuration to the SpringBook container, so in the previous configuration file, add Bean:

4. We’d better look at the results.

The default language display, because the browser defaults to Chinese, so:

 

Then click on the English below to see the URL and page changes:

Let’s click on Chinese again:

 

 

,

Sounds tall and internationalized, starting with the use of browser language, or Chinese-English switching in the page, the text of the page will be switched in other languages and Chinese, such as:

We want to make this function come true. Click on Chinese, the page is Chinese, and click on English is English.

Internationalization Configuration

So let’s see, SpringBoot defaults to switch between Chinese and English according to the language of your browser. Configuration files, we can write in resources as follows:

 

1. Create a new package called “i18n”, which we use to store international configuration. Then under this package, we create several properties configuration files to configure the language:

As shown in the figure, we create three files, which are login. properties in effect when there is no language configuration, login_zh_CN. properties in Chinese, and login_en_US. properties in English.

That is, the combination of underlining: filename region language. properties; when we name the generated file like this, IDEA will also help us identify it as an international configuration package and automatically convert it into the following pattern:

Of course, when it becomes the above mode, we need to add the configuration file, just right-click new in the package.

It’s much more convenient.~

 

2. We need to make some changes in these configuration files. First, click the login_en_US configuration file, and then click the Resource Bundle button shown below to switch the editing mode:

According to the method shown in the figure, click on the plus sign and add a key. Our name is login. tip, which means the prompt used in the page.

Next, according to the amount of conversion we need on our page, we configure it as follows (I have configured all the login pages I need to use later):

It’s not over yet. Don’t worry. It looks complicated. It’s easy to learn. Later we need to refer to these values on the page and look at them.

Remember to add configuration parameters to our application. properties to make our configuration work:

spring.messages.basename=i18n.login

HTML Pages – Configuration

Based on previous articles, we learned about the role of @ and # in Thymeleaf’s grammar. Let’s see how to use them.

In the front form, we set all the required parameters in the form of {xx.yy} according to the internationalized parameters of the configuration. In order to use the template, we need to replace the original parameters with parameters such as th: text. (Note that the original page has the same text, placeholder, etc.)

For the Thymeleaf template to take effect, don’t forget to add this xmlns to the HTML parameters:

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

In this way, we can switch between Chinese and English in the case of switching the browser language. We can use chrome as an example to set up the method.

 

 

Custom Configuration to Make Chinese-English Switching in Our Page Effective

 

Patient students, let’s take a look at the main topic, how to make their configuration effective:

1. The screenshot at the top of the article, we see the HTML of Chinese and English buttons. Let’s see how to configure it:

Note that the page I’m going to visit here is actually: localhost: 8080 / index. html? L = zh_CN, which is also the link we generated when we clicked the Chinese button. In Thymeleaf’s template grammar, parameters are not used “?” Instead, parentheses are used, and then the parameters are set in the form of key = value, paying attention to single quotation marks.

2. In order to make the customized configuration work, what we need to do is to override or change the default configuration. Then we create a new file named MyLocaleResolver to implement the function of the LocaleResolver interface.

Specific method: (because our region is configured with an underscore “”, so here we use a separator to get the region and language, and put it in the request)

package com.iceodin.common.component;

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;

/**
 * Carry area information on links
 */
public class MyLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String l = httpServletRequest.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) {

    }
}

3. Let our configuration take effect, of course, by adding the configuration to the SpringBook container, so in the previous configuration file, add Bean:

4. We’d better look at the results.

The default language display, because the browser defaults to Chinese, so:

 

Then click on the English below to see the URL and page changes:

Let’s click on Chinese again:

Recommended Today

Manjaro uses SS method (requires nodejs environment)

Just installed manjaro, need to installshadowsocks-qt5+Proxy SwitchyOmega, but the latest Chrome has long blocked the installation of non Google store CRX channels. Here is my solution, which is troublesome but usable. If you are familiar with NPM commands in nodejs, you won’t find it troublesome, because nodejs is used for compilation. Preparation environment: A VPS […]