Sunday, 22 April 2012

Using Properties files in JSF


1-message.properties
Create "messages.properties" and save it in "WEB-INF\src\java\net\app" directory. 
Add the following content to the file:
title          = Username
welcome        = Welcome
header         = MY APP
your_name      = User Name:
button_text_ok = OK
Welcome        = Welcome
jsf_world      = to JSF 1.2 World!

Above file defines the various properties to be used in the forms.

2-index.jsp
Modify the code of "index.jsp" file to use the message resource bundle. 

Here is code of final  index.jsp:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="net.app.messages" var="msg"/>

<html>
<head>
<title>Input Form</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value="#{msg.header}"/>
</h1>
<h:form id="UserEntryForm">
<h:outputText value="#{msg.your_name}"/>
<h:inputText value="#{UserBean.userName}" />
<h:commandButton action="welcome" value="#{msg.button_text_ok}" />
</h:form>
</f:view>
</body>
</html> 


The code <f:loadBundle basename="net.app.messages" var="msg"/> loads the messages from messages.properties. 
The <f:loadBundle /> tag is used to load the recourse bundle and store it as a map in the request scope. This allows you to access the message in your JSF. 
There are two attributes for this tag "basename" and "var". "basename" is the base name where the bundle is present and "var" represents the name by which the we will refer this bundle in our jsf page.

3-welcome.jsp


<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="net.app.messages" var="msg"/>
<html>
<head>
<title>Welcome</title>
</head> 
<body>
<f:view>
<h3>
<h:outputText value="#{msg.welcome}"/>,
<h:outputText value="#{UserBean.userName}" />&nbsp;<h:outputText value="#{msg.jsf_world}"/>
</h3>
</f:view>
</body> 
</html>

No comments:

Post a Comment