springboot进行页面国际化

本文详细介绍了如何在SpringBoot项目中实现国际化配置,包括创建i18n目录、配置properties文件、自定义LocaleResolver以及在Thymeleaf模板引擎中使用国际化。通过自定义的MyLocalResolver组件,实现了页面按钮的语言自动切换。同时,文章也展示了在前端页面如何进行相应的设置以支持国际化显示。
摘要由CSDN通过智能技术生成

1.需要自己创建i18n目录,然后创建相应的properties文件,然后在添加页面中需要国际化的数据

2.添加需要的国际化配置

3.在项目中需要自动按钮切换时,需要在springboot中自定义一个组件LocaleResolver

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 MyLocalResolver implements LocaleResolver {

    // 解析请求
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 获取请求中的语言参数链接
        String langues = request.getParameter("l");

        Locale locale = Locale.getDefault();

        // 如果请求的链接携带了国际化的参数
        if(!StringUtils.isEmpty(langues)){
            String[] split = langues.split("_");
            locale = new Locale(split[0], split[1]);
        }

        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

 

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 MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }


    // 自定义的国际化放到Bean中就生效了
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalResolver();
    }
}
4.在前端页面需要配置的地方进行设置,我的前端页面使用的是thymeleaf模板引擎

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值