zhitong.yu
7 天以前 7fc9c42987a13c1d8d2159591a5803e70518827f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.hxzk.gps.filter;
 
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
 
import java.util.Locale;
 
@Configuration
public class WebConfig implements WebMvcConfigurer {
 
    // 配置消息源,用于加载资源文件
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages"); // 指定资源文件的基本名称
        messageSource.setCacheSeconds(0);
        messageSource.setDefaultEncoding("UTF-8"); // 设置字符编码
        return messageSource;
    }
 
    // 配置 LocaleResolver,用于解析用户的 Locale
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); // 设置默认 Locale
        return slr;
    }
 
    // 配置 LocaleChangeInterceptor,用于根据请求参数切换 Locale
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang"); // 指定切换语言的请求参数名
        return lci;
    }
 
    // 将 LocaleChangeInterceptor 添加到拦截器链中
    // 注意:LocaleChangeInterceptor现在在SaTokenConfigure中注册,以避免拦截器执行顺序问题
    // @Override
    // public void addInterceptors(InterceptorRegistry registry) {
    //     registry.addInterceptor(localeChangeInterceptor());
    // }
}