在Struts2 web应用程序的特定Java类中,我有以下代码:
try {
user = findByUsername(username);
} catch (NoResultException e) {
throw new UsernameNotFoundException("Username '" + username + "' not found!");
}我的老师想让我把“扔”语句改成这样的东西:
static final String ex = "Username '{0}' not found!" ;
// ...
throw new UsernameNotFoundException(MessageFormat.format(ex, new Object[] {username}));但我不认为在这种情况下使用MessageFormat有什么意义。是什么使这比简单的字符串连接更好呢?正如用于MessageFormat的JDK所述:
MessageFormat提供了一种以语言中立的方式生成连接消息的方法.使用此方法可构造为最终用户显示的消息。
我怀疑最终用户是否会看到这个异常,因为它只会由应用程序日志显示,而且我有一个web应用程序的自定义错误页面。
我应该更改代码行还是坚持当前的代码行?
发布于 2009-10-14 15:43:45
我应该更改代码行还是坚持当前的代码行?
根据你的老师,你应该。
也许他想让你为同一件事学习不同的方法。
虽然在您提供的示例中,它没有多大意义,但当使用其他类型的消息或用于i18n时,它将是有用的
想想看:
String message = ResourceBundle.getBundle("messages").getString("user.notfound");
throw new UsernameNotFoundException(MessageFormat.format( message , new Object[] {username}));您可以有一个messages_en.properties文件和一个messages_es.properties
第一个字符串:
user.notfound=Username '{0}' not found!第二项包括:
user.notfound=¡Usuario '{0}' no encontrado!那就有道理了。
MessageFormat的另一种用法在文档中描述。
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
double[] filelimits = {0,1,2};
String[] filepart = {"no files","one file","{0,number} files"};
ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
form.setFormatByArgumentIndex(0, fileform);
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
System.out.println(form.format(testArgs));对于fileCount具有不同值的输出:
The disk "MyDisk" contains no files.
The disk "MyDisk" contains one file.
The disk "MyDisk" contains 1,273 files.所以也许你的老师是让你知道你所拥有的可能性。
发布于 2009-10-14 15:40:47
教师的方式允许更容易的本地化,因为您可以提取单个字符串,而不是几个小比特。
发布于 2009-10-14 15:43:28
但我不认为在这种情况下使用MessageFormat有什么意义
在那种特殊的情况下,它不会给你买多少钱。通常,使用MessageFormat可以将这些消息外部化到文件中。这使你能够:
https://stackoverflow.com/questions/1567146
复制相似问题