在最近的工作中,现在遇到的一种情况是,客户上传Excel 之后,比如excel 中的第N行数据校验不通过,这时候后端应该给用户友好的提示,告诉用户的excel 中是第几行的数据有错误,之前仅仅是告诉了客户exce 校验不通过。
所以当时考虑的方法是自己手拼,但是这要在java 代码中插入,很不美观,所以后来想到了在国际化文件中也许可以使用占位符,果然,还是google 好用,搜到了,所以现在也发现,关键时刻,尤其是程序猿,还是要学会使用google
在这里直接贴代码
google 中是这样说的:
@Controller
public class HelloController {
@Autowired
private MessageSource messageSource;
@RequestMapping("/")
public String home(HttpServletRequest request, Model model) {
String name = messageSource.getMessage("world", new Object[]{}, Locale.getDefault());
Account account = AccountResolver.INSTANCE.getAccount(request);
if (account != null) {
name = account.getGivenName();
model.addAttribute(account);
}
model.addAttribute("name", name);
return "hello";
}
}
这里首先我要说一下国际化文件资源的位置
translationUtil.translate(ErrorCode.SUPPORT_ALREADY_EXIST.toString(), new Object[]{support.getId()});
资源文件里可以这样写
SUPPORT_ALREADY_EXIST = {0}对应的问题件已经存在
上面的代码可以看到调用了
MessageSource
这个类,通过这个类的方法
.getMessage()
而第一个参数就是源,第二个参数就是传值进去的占位符的内容,第三个参数就是指定的国际化的资源文件。
所以在这里我自己封装了一个方法:
public String translate(String source, Object[] args) {
return messageSource.getMessage(source, args, "", Locale.SIMPLIFIED_CHINESE);
}
调用的时候直接使用类似于下面的这种就可以了:
translationUtil.translate(ErrorCode.SUPPORT_ALREADY_EXIST.toString(), new Object[]{support.getId()});