场景:拓展海外业务,要求程序支持国际化
首先根据需要建立配置文件内容(messages_en_US.properties):
200=SUCCESS
not.null = Required field
user.jcaptcha.error = Incorrect captcha
user.jcaptcha.expire = Expired captcha
user.not.exists = User does not exist / incorrect password
user.password.not.match = User does not exist / incorrect password
user.password.retry.limit.count = Password entered incorrectly {0} times
user.password.retry.limit.exceed = Password entered incorrectly {0} times, account locked for {1} minutes
user.password.delete = Sorry, your account has been deleted
user.blocked = User is blocked, please contact the administrator
role.blocked = Role is blocked, please contact the administrator
login.blocked = Unfortunately, the access IP has been added to the system blacklist
user.logout.success = Logout successful
length.not.valid = Length must be between {min} and {max} characters
user.username.not.valid = * Must be 2 to 20 Chinese characters, letters, numbers, or underscores, and cannot start with a number
user.password.not.valid = * Must be 5-50 characters
user.email.not.valid = Invalid email format
user.mobile.phone.number.not.valid = Invalid phone number format
user.login.success = Login successful
user.register.success = Registration successful
user.notfound = Please log in again
user.forcelogout = You have been forcibly logged out by an administrator. Please log in again.
user.unknown.error = Unknown error, please log in again
File Upload Messages
upload.exceed.maxSize = The uploaded file size exceeds the maximum allowed file size! <br/> The maximum file size allowed is: {0}MB!
upload.filename.exceed.length = The uploaded filename must be no longer than {0} characters
Permissions
no.permission = You do not have permission for this data, please contact the administrator to add permissions [{0}]
no.create.permission = You do not have permission to create this data, please contact the administrator to add permissions [{0}]
no.update.permission = You do not have permission to modify this data, please contact the administrator to add permissions [{0}]
no.delete.permission = You do not have permission to delete this data, please contact the administrator to add permissions [{0}]
no.export.permission = You do not have permission to export this data, please contact the administrator to add permissions [{0}]
no.view.permission = You do not have permission to view this data, please contact the administrator to add permissions [{0}]
messages.properties:
#错误消息
200=成功
not.null=* 必须填写
user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效
user.not.exists=用户不存在/密码错误
user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定10分钟
user.password.delete=对不起,您的账号已被删除
user.blocked=用户已封禁,请联系管理员
role.blocked=角色已封禁,请联系管理员
user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成,且必须以非数字开头
user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误
user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功
user.register.success=注册成功
user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录
##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB!
upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0},{1}]
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]
上面文件是一些提示语,和返回信息,根据自己项目配置;
配置文件里,需要根据自己路径文件写:
# 资源信息
messages:
# 国际化资源文件路径
basename: i18n/messages
WebConfig.java
package com.pmtest.web.core.config;
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.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;
/**
* @Author: pangyq
* @CreateTime: 2024-08-26 17:12
* @Description: TODO
* @Version: 1.0
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 注册拦截器
*
*/
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(getLocaleChangeInterceptor());
}
/**
* Locale拦截器
*/
public LocaleChangeInterceptor getLocaleChangeInterceptor(){
LocaleChangeInterceptor interceptor =new LocaleChangeInterceptor();
interceptor.setParamName("language");
return interceptor;
}
/**
* 默认解析器,其中locale为默认语言
*
locale
*/
@Bean
LocaleResolver localeResolver(){
// 替换掉默认的 AcceptHeaderLocaleResolver
SessionLocaleResolver localeResolver =new SessionLocaleResolver();
// 设置默认语言为简体中文
localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
return localeResolver;
}
}
CustomLocaleChangeInterceptor.java
package com.pmtest.Interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* @Author: pangyq
* @CreateTime: 2024-08-26 17:13
* @Description: TODO
* @Version: 1.0
*/
@Component()
public class CustomLocaleChangeInterceptor extends HandlerInterceptorAdapter {
private LocaleResolver localeResolver;
public CustomLocaleChangeInterceptor(LocaleResolver localeResolver) {
this.localeResolver = localeResolver;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String lang = request.getParameter("language");
if (lang != null) {
Locale locale = new Locale(lang);
localeResolver.setLocale(request, response, locale);
}
return true;
}
}
MessageUtils.java
package com.pmtest.util;
import com.pmtest.common.utils.spring.SpringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
/**
* @Author: pangyq
* @CreateTime: 2024-08-26 18:08
* @Description: TODO
* @Version: 1.0
*/
public class MessageUtils
{
/**
* 根据消息键和参数 获取消息
*
* @param messageKey 消息键
* @param args 参数
* @return 获取国际化翻译值
*/
public static String getMessage(String messageKey, Object... args) {
try {
MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
return messageSource.getMessage(messageKey, args, LocaleContextHolder.getLocale());
} catch (NoSuchMessageException e) {
return "Message not found: " + messageKey;
}
}
}
TransController
package com.pmtest.controller;
import com.pmtest.util.LocalizationUtils;
import com.pmtest.util.MessageUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: pangyq
* @CreateTime: 2024-08-26 15:26
* @Description: TODO
* @Version: 1.0
*/
@RestController
@RequestMapping("test")
public class TransController {
// private final MsgUtil msgUtil;
// @Autowired
// public TransController(MsgUtil msgUtil) {
// this.msgUtil = msgUtil;
// }
@GetMapping("/greet")
public String greet() {
Object [] args=new Object[] {"你好","你干嘛"};
return MessageUtils.getMessage("no.update.permission", args);
}
}