i8n,点击进行语言的切换

1.点击链接切换国际化(给它一个参数)

<div style="margin-left: 100px;">
         <a href="#" th:href="@{index.html(l='zh_CN')}">中文</a>
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         <a href="" th:href="@{index.html(l='en_US')}" >English</a>
 </div>

2. 自定义区域解析器设置区域信息

代码:

package com.cc.springboot.component;

import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

//自定义区域解析器
public class MyLocaleResolver implements LocaleResolver {
    public MyLocaleResolver() {
        super();
    }
//   解析区域信息
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
      //获取自定义请求头信息
        String l = request.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 request, HttpServletResponse response, Locale locale) {

    }
}

Ctrl+O实现接口的一些方法     Ctrl+Alt+v生成返回值 

 3.替换mvc自动配置类区域信息解析器(返回值和方法名是固定的,不能自定义)

package com.cc.springboot.config;

import com.cc.springboot.component.MyLocaleResolver;
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 MySpringMvcConfigurer {
    @Bean
//    跳转首页
    public WebMvcConfigurer webMvcConfigurer() {
      return   new WebMvcConfigurer() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("main/login");
                registry.addViewController("/index.html").setViewName("main/login");
            }
        };
    }
    @Bean
//    切换语言  自己定义的区域解析器
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值