4

我想显示在动作类中检测到的错误,我使用:

errors.add(ActionErrors.GLOBAL_MESSAGE,
  new ActionMessage("some_string_in_properties_file"));`

它工作正常。但是,我写了一些通用的错误消息,我想重用它们,所以我正在尝试这样做:

errors.add(ActionErrors.GLOBAL_MESSAGE,
  new ActionMessage("string1_in_properties_file", "string2_in_properties_file"));

其中字符串 1 = <li>{0} is required.</li>

然后它正在显示string2 is required。它没有用它的值替换 string2 。

我什至试过

errors.add(ActionErrors.GLOBAL_MESSAGE,
  new ActionMessage("string1_in_properties_file",
  new ActionMessage("string2_in_properties_file")));

然后它正在显示string2[] is required。它没有替换 string2。

我知道可以通过对值进行硬编码来完成,但是还有其他方法吗?

4

4 回答 4

2

由于您想从属性文件中获取两个键的值,并将其放入全局错误键中,我想说,使用分别检索每个值

String sValue1 = getResources(request).getMessage(locale, "key1");
String sValue2 = getResources(request).getMessage(locale, "key2");

然后把它放在你的全局错误中

errors.add(ActionErrors.GLOBAL_MESSAGE,sValue1+"<br/>"+sValue2);

希望它有帮助....

于 2012-01-19T05:21:05.013 回答
0

很难确切地告诉你该怎么做,因为 O 不知道 and 背后的errors代码ActionMessage。但是,您可以使用String.format. 你的代码看起来像这样

public class ActionErrors {
    public static final String INVALID_INPUT "'%s' is not valid input.";
    ...
}

String input = "Cats";
String message = String.format(ActionErrors.INVALID_INPUT, input);
System.out.println(message);

以上将打印

“猫”不是有效的输入。

于 2012-01-18T14:37:51.193 回答
0

在 Struts ActionMessage中,您可以为属性文件中指定的参数 、 、 指定值,{0}如下{1}所示:{2}{3}

errors.add(ActionErrors.GLOBAL_MESSAGE,
  new ActionMessage("some_string_in_properties_file", "value1"));

交替:

errors.add(ActionErrors.GLOBAL_MESSAGE,
  new ActionMessage("some_string_in_properties_file", "value1", "value2", "value3"));

value1..value3可以是任何类型(如 Struts 所期望的Object)。

所以你的财产:

string1 = <li>{0} is required.</li>

将被替换为:

<li>value1 is required.</li>

(如果您将密钥指定为string1)。

于 2012-01-18T14:52:20.143 回答
0

假设您有一个属性文件,它为消息定义了一些键,如下所示:

string1: <li>{0} is required.</li>
string2: Username

ActionMessage 类有许多构造函数,它们接受不同数量的参数。第一个是表示引用消息的键的字符串 - 在您的情况下,键string1对应于消息<li>{0} is required.</li>;作为一些动态内容的{0}占位符。

其余可能的参数是表示要替换这些占位符的实际值的对象。如果你这样做new ActionMessage("string1", "string2")了,你会传入文字值string2,你最终会得到<li>string2 is required.</li>.

您需要做的是替换"string2"为将获取与 key 对应的值的方法调用string2。不过,这就是我对问题的了解用尽的地方,因此您需要自己对此部分进行一些研究。

于 2012-01-18T15:42:19.263 回答