springboot頁面國際化

阿落小世界發表於2022-03-03
  1. 引入依賴pom.xml
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

  1. 匯入網頁資源,這裡給大家推薦一個我自己在使用的頁面資源,SB ADMIN-2

    html頁面放在templates目錄下,這是thymeleaf預設的解析目錄,其他的樣式檔案放在static目錄下
    image

  2. 接管spring Mvc,自定義url訪問路徑,可做可不做

    建一個config目錄,在這裡建一個myWebMvcConfig

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.LocaleResolver;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class myWebMvcConfig implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
    
            registry.addViewController("/wq").setViewName("register");//localhost:8080/wq
            registry.addViewController("/").setViewName("register");//localhpst:8080/
            registry.addViewController("/register.html").setViewName("register");
            //localhost:8080/register.html
        }
    }
    

    路徑可以設定多個,這樣只要是這三個url,spring 都會訪問register.html
    還有一種方式也能實現

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class demoController {
        @RequestMapping({"/","/wq"})
        public String test(){
            return "register";
        }
    }
    
    1. 國際化配置檔案:en_US英文,zh_CN中文
      image
      點選左上角加號,便可以新增配置的屬性,只要在右邊填寫相應的中英文即可

image
5. 配置檔案已經寫好,如何在我們的頁面中使用呢?thyme leaf的作用又來了

  首先在你的網頁新增這樣的頭部

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

  在所有的html屬性前加**th:**就被thymeleaf接管了,根據thymeleaf 語法,獲取國際化值使用**#{}**,本地值用**${}**,url用**@{}**

  ![image-20220228101634725](C:\Users\32944\AppData\Roaming\Typora\typora-user-images\image-20220228101634725.png)

  ![image-20220228101806743](C:\Users\32944\AppData\Roaming\Typora\typora-user-images\image-20220228101806743.png)

  ```html
   <a  th:href="@{/register.html(l='zh_CN')}" >中文 </a>
  <a  th:href="@{/register.html(l='en_US')}">English </a>
  ```

  6. 頁面和配置檔案都準備好了,怎樣實現跳轉呢?

     在WebMvcAutoConfiguration.class中

     ```java
      		@Bean
             @ConditionalOnMissingBean(
                 name = {"localeResolver"}
             )
             public LocaleResolver localeResolver() {
                 if (this.webProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.WebProperties.LocaleResolver.FIXED) {
                     return new FixedLocaleResolver(this.webProperties.getLocale());
                 } else {
                     AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
                     localeResolver.setDefaultLocale(this.webProperties.getLocale());
                     return localeResolver;
                 }
             }
     ```

     我們再找到AcceptHeaderLocaleResolver.class,發現它實現了LocaleResolver 

     ```java
     public class AcceptHeaderLocaleResolver implements LocaleResolver {
         private final List<Locale> supportedLocales = new ArrayList(4);
         @Nullable
         private Locale defaultLocale;
     ```

     那我們就編寫自己的LocaleResolver 

     ```java
     public class myLocaleResolver implements LocaleResolver {
         @Override
         public Locale resolveLocale(HttpServletRequest request) {
     
             String mylocale=request.getParameter("l");
             Locale locale=Locale.getDefault();
             if(!StringUtils.isEmpty(mylocale)){
                 String[] split=mylocale.split("_");
                 locale=new Locale(split[0],split[1]);
             }
              System.out.println("debug====>"+mylocale);
             return locale;
         }
     
         @Override
         public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
     
         }
     }
     
     ```

     然後在spring配置中注入myLocaleResolver

     ```java
     @Bean
     public LocaleResolver localeResolver(){
         return new myLocaleResolver();
     
     }
     ```

     **注意:方法名必須是localeResolver**,**因為原始碼中名字為localeResolver的bean**

image
7. 最後我們來測試一下
image
image
image
而且控制檯輸出也沒問題

相關文章