【发布时间】:2012-05-09 08:43:04
【问题描述】:
我正在使用 java.util.resourcebundle 来格式化我的 JSTL 消息,这很好用:
我使用您可以在此处看到的 MessageFormat 类。现在我想将它封装到一个只是 getParametrizedMessage(String key, String[]parameters) 的方法中,但我不知道该怎么做。现在有相当多的工作要显示一两条带参数的消息:
UserMessage um = null;
ResourceBundle messages = ResourceBundle.getBundle("messages");
String str = messages.getString("PF1");
Object[] messageArguments = new String[]{nyreg.getNummer()};
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString("PI14"));
String outputPI14 = formatter.format(messageArguments);
formatter.applyPattern(messages.getString("PI15"));
String outputPI15 = formatter.format(messageArguments)
if(ipeaSisFlag)
if(checkIfPCTExistInDB && nyreg.isExistInDB()) {
//um = new ExtendedUserMessage(MessageHandler.getParameterizedMessage("PI15", new String[]{nyreg.getNummer()}) , UserMessage.TYPE_INFORMATION, "Info");
um = new ExtendedUserMessage(outputPI15 , UserMessage.TYPE_INFORMATION, "Info");
……等等。现在我可以将此逻辑移动到一个静态类 MessageHandler.getParameterizedMessage 中,该类现在不起作用并且看起来像这样:
private final static String dictionaryFileName="messages.properties";
public static String getParameterizedMessage(String key, String [] params){
if (dictionary==null){
loadDictionary();
}
return getParameterizedMessage(dictionary,key,params);
}
private static void loadDictionary(){
String fileName = dictionaryFileName;
try {
dictionary=new Properties();
InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName);
dictionary.load(fileInput);
fileInput.close();
}
catch(Exception e) {
System.err.println("Exception reading propertiesfile in init "+e);
e.printStackTrace();
dictionary=null;
}
}
我怎样才能让使用我的参数化消息像调用带有键和参数的方法一样简单?
感谢您的帮助
更新
逻辑来自 this 扩展的抽象类中的继承方法。方法如下:
protected static String getParameterizedMessage(Properties dictionary,String key,String []params){
if (dictionary==null){
return "ERROR";
}
String msg = dictionary.getProperty(key);
if (msg==null){
return "?!Meddelande " +key + " saknas!?";
}
if (params==null){
return msg;
}
StringBuffer buff = new StringBuffer(msg);
for (int i=0;i<params.length;i++){
String placeHolder = "<<"+(i+1)+">>";
if (buff.indexOf(placeHolder)!=-1){
replace(buff,placeHolder,params[i]);
}
else {
remove(buff,placeHolder);
}
}
return buff.toString();
}
我认为我必须重写上述方法,以使其像资源包一样工作,而不仅仅是字典。
更新 2
似乎有效的代码在这里
public static String getParameterizedMessage(String key, Object [] params){
ResourceBundle messages = ResourceBundle.getBundle("messages");
MessageFormat formatter = new MessageFormat("");
formatter.applyPattern(messages.getString(key));
return formatter.format(params);
}
【问题讨论】:
-
我们能看到getParameterizedMessage(Properties dictionary, String key, String [] params)的代码吗?该方法如何不起作用?例外?出乎意料的结果?那么,错误的结果是什么,预期的结果是什么?
-
@Pablo 我已经用您要求的代码更新了问题。我在基类中找到了它。看起来我需要更改这种方法,因为它以前使用
<< >>标签而不是大括号[0}作为参数用于稍微不同的目的。它现在的工作方式是参数没有出现,即当我从自定义 JSTL 格式升级文件格式时参数化机制中断,参数带有大括号 {} 而不是标签 >
标签: java jakarta-ee properties jstl message