JSF Tutorial - JSF Resource Bundles Example








The following code shows how to load pre-defined message from resource files.

Example

The following code is from messages.properties.

message = This is "message"
message.test1 = This is "message.test1"
message.test2 = This is "<h2>message.test3</h2>"
message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;"
message.param1 = This is "message.param1" - {0}
message.param2 = This is "message.param2" - {0} and {1}

The following code is from UserBean.java.

package com.java2s.common;


import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{
  
  private static final long serialVersionUID = 1L;
  
}

The following code is from demo.xhtml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">
  
  <!-- load resource bundle for this page only 
  <f:loadBundle basename="com.java2s.messages" var="msg"/>
  -->
    <h:body>
      <h:outputText value="#{msg.message}" />
      <br/>
      <h:outputText value="#{msg['message.test1']}" />
      <br/>
      <h:outputText value="#{msg['message.test2']}" />
      <br/>
      <h:outputText value="#{msg['message.test2']}" escape="false" />
      <br/>
      <h:outputText value="#{msg['message.test3']}" />
      <br/>
      <h:outputText value="#{msg['message.test3']}" escape="false" />
      <br/>
      <h:outputFormat value="#{msg['message.param1']}">
            <f:param value="param0" />
       </h:outputFormat>
        <br/>
       <h:outputFormat value="#{msg['message.param2']}">
         <f:param value="param0" />
         <f:param value="param1" />
       </h:outputFormat>
  </h:body>
</html>


Download Resource-Bundles.zip





To RUN

Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.

After Tomcat finish starting, type the following URL in the browser address bar.

http://localhost:8080/simple-webapp/demo.xhtml