Thursday, January 17, 2013

What is resource bundle in struts and using multiple resource bundle files.

      Resource bundles allow Java applications to be easily internationalized by having application content placed into bundles. This content can then be read by the application at run time. Therefore, instead of having content hardcoded in the application, the application reads its content from the bundle. Struts has built-in support for working with Java's resource bundle mechanism. 

      Resource bundle resources can be accessed from JSPs to populate them with content. Resource bundle properties files simply contain key/value pairs. The resources are accessed by their key. The standard name for the resources bundle properties file in struts is MessageResources.properties. 
   Thes files may contain key/values like this login.empty=Empty username and passwordtitle=Struts Relearn
   
      These files are configured in struts-config.xml :

1
2
<message-resources parameter="com.nils.resources.MessageResources">
</message-resources>

keep in mind that the parameter attribute is a file name without .properties extension.You can access these values in JPSs like this 


1
<bean:message key="title" />

given that bean taglib is configured in the JSP.



     If you want to use multiple properties files with different values for the keys. Then  you just need to specify "key" attribute of message-resources in struts-config.xml entries.

1
2
3
4
5
6
<message-resources parameter="com.nilesh.resources.MessageResources" 
                   key="NormalCase">
</message-resources>
<message-resources parameter="com.nilesh.resources.AnotherMessageResources" 
                   key="UpperCase">
</message-resources>

        And while using them in JSP use "bundle" attribute of bean:message.


1
2
<bean:message key="title" bundle="NormalCase"/>
<bean:message key="title" bundle="UpperCase"/>

bundle attribute is mapped to key attribute of message-resources which specifies the properties file. 

        If you configure multiple message-resources and don't specify the keys for them both of them will have default key 

"org.apache.struts.action.MESSAGE"

so when they are used in JSP it will see two files configured with same key and will throw excpetion, this is the same exception you may see when message-resources is misconfigured:


SRVE0068E: Uncaught exception created in one of the service 
methods of the servlet /index.jsp in application StrutsEar. 
Exception created :
com.ibm.websphere.servlet.error.ServletErrorReport:
javax.servlet.jsp.JspException: Cannot find message resources under key 
org.apache.struts.action.MESSAGE.

No comments:

Post a Comment