Struts2 i18n messages

限于喜欢 提交于 2020-01-04 16:57:32

问题


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?


回答1:


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.




回答2:


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 the I18N interceptor independent of the browser settings. So, make sure you have it on the stack.




回答3:


Use getText method to get message from properties file.

<message>${getText("enter.password")}</message>

See: http://struts.apache.org/development/2.x/docs/validation.html#Validation-LocalizingandParameterizingMessages.




回答4:


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



来源:https://stackoverflow.com/questions/15495371/struts2-i18n-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!