I am using Struts 2 and I created a simple application following a tutorial I found.
I've created a <MyActionClass>-validation.xml
file and I wonder how can I display the validation messages based on multiple languages?
<field name="password">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>You have to enter a password.</message>
</field-validator>
</field>
Can I get the messages from a localized .properties
file or do I have to use some other kind of validation?
Should there be validation XML files for every locale?
The messages are retrieved by key
from you localized properties. You don't have to write duplicate code for validation. For example
<validators>
<validator type="requiredstring">
<param name="fieldname">field.name</param>
<message key="field.key"/>
</validator>
</validators>
or using annotations
private String name;
@RequiredStringValidator(key = "field.key")
public void setName(String name) {
this.name = name;
}
field.name
is a resource key for a field label while field.key
is a key to an error message.
in the properties you write
field.name=MyName
field.key=MyName required
that is localized.
Messages automatically retrieved depending on the locale settings of the user browser or via request_locale
parameter that is setting locale by theI18N interceptor independent of the browser settings. So, make sure you have it on the stack.
Use getText
method to get message from properties file.
<message>${getText("enter.password")}</message>
Yes you can get localized messages from a properties file and no there is no need of any validation.xml for any locale specific messages.
You need to specify the ResourceBundle which will be nothing but different locales files of extension .properties
Just use <message key="key_name"/>
inside your ActionClass-validation.xml
Then you define key_name
in
global.properties
global_vn.properties
Make sure you have request_locale
in your stack.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.