Friday, June 29, 2012

JSTL : How to use fmt:message and ResourceBundle

There are two ways you can access values from a property file. Mostly a text value which can change in future are kept in property file and access it using fmt:message and ResourceBundle in JSP and JAVA respectively so that if the text values are changed in future it wont affect our code. We just need to change in property file and rest all will be taken care implicitly.

Lets see how to use fmt:message and ResourceBundle in JSP and JAVA respectively.

1. In JSP

If you need to access the property value in JSP, first lets create a property file lets say prop.properties. Add prop.properties in src folder of your application.

prop.properties

key1=This is value1
key2=This is value2

Add the mapping in web.xml or Spring's dispatcher-servlet.xml as shown below

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="prop" />
</bean>

Note the value="prop" it says to load prop.properties from the src folder. Now through JSP you can access the property by its key as shown below

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<fmt:bundle basename="prop">
<fmt:message key="key1"/>
<fmt:message key="key2"/>
</fmt:bundle>

2. In Java

Also you may need to access these properties in a JAVA program it could be either bean or any controller. You can access using java.util.ResourceBundle as shown below.

String value1 = ResourceBundle.getBundle("prop").getString("key1");
String value2 = ResourceBundle.getBundle("prop").getString("key2");

Note : You may get below error

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/fmt cannot be resolved in either web.xml or the jar files deployed with this application

To solve above error you need to include jstl-1.2.jar in your application's classpath. It could be possible that your application is not able to detect jstl-1.2.jar file.

No comments:

Post a Comment