• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

JSF 2 Message and Messages Example

March 27, 2014 //  by Amr Mohammed//  Leave a Comment

The <h:message/> and <h:messages/> can be used for displaying the error, fatal error, warning and information messages for single component and for the whole current view respectively. When it comes to develop a JSF page, it happens for a component/view to have a messages that tell the user about some missing or wrong data must be provided/fixed to ensure that the business logic for your managed beans can execute smoothly and without any problems.

The message/messages component provides the capability for the developer to provide the desired style for the different kind of messages, so the styles for different messages can provide a deep identification in which the user can discriminate between those that are just providing an information from those that couldn’t proceed any further if they aren’t fixed.

The severity level which passed through adding a faces message into component/view determine the type of the messages whether they are error or even just an information. Any message/messages contains either type of information; detail and summary, where the developer has controlled if it does wish to render the detail alone or the summary alone or it has the both. One remaining important issue, in that when it comes to use the message/messages, the bundled messages are brought for making a localization of component/view messages.

Also Read:

  • JSF 2 Tutorials
  • JSF Tutorials
  • Introduction to JSF

This tutorial will explain the proper way for using the message and messages for displaying the messages for a specific component or for the current view.

1. Managed Bean

IndexBean.java

package net.javabeat.jsf;

import java.util.Locale;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class IndexBean {

	private String locale = "en";
	private String message = "";
	private String email = "";

	public String getLocale() {
		return locale;
	}

	public void setLocale(String locale) {
		this.locale = locale;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String changeLocale(String locale){
		// Change the locale attribute
		this.locale = locale;
		// Change the locale of the view
		FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(this.locale));
		return "";
	}

	public String send(){
		if(this.message.equals("")){
			// Bring the error message using the Faces Context
			String errorMessage = FacesContext.getCurrentInstance().getApplication().
					getResourceBundle(FacesContext.getCurrentInstance(),"msg").
					getString("message_missing");
			// Add View Faces Message
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
			errorMessage, errorMessage);
			// Add the message into context for a specific component
			FacesContext.getCurrentInstance().addMessage("form:message", message);
		}

		if(this.email.equals("")){
			// Bring the error message using the Faces Context
			String errorMessage = FacesContext.getCurrentInstance().getApplication().
					getResourceBundle(FacesContext.getCurrentInstance(),"msg").
                                          getString("email_missing");
			// Add View Faces Message
			// Cause the application doesn't functional if you've got missing the email
			// The severity case is Error or fatal error
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,errorMessage,
                                         errorMessage);
			// Add the message into context for a specific component
			FacesContext.getCurrentInstance().addMessage("form:email", message);
			// Return empty token for navigation handler
			return "";
		}

		// Return confirmation message that the message has been sent

		// Bring the information message using the Faces Context
		String confirmMessage = FacesContext.getCurrentInstance().getApplication().
				getResourceBundle(FacesContext.getCurrentInstance(),"msg").
                                  getString("email_sent");
		// Add View Faces Message
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,confirmMessage, confirmMessage);
		// The component id is null, so this message is considered as a view message
		FacesContext.getCurrentInstance().addMessage(null, message);
		// Return empty token for navigation handler
		return "";
	}
}

2. The View

index.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
	<title><h:outputText value="#{msg.title}"/></title>
	<style>
		.err {
			color: red;
		}
		.warn {
			color: yellow;
		}
		.info {
			color: blue;
		}
	</style>
</h:head>
<h:body>
	<h:form id="form">
	<div style="border: 1">
		<span> Global Message Area:</span>
		<h:messages globalOnly="true" errorClass="err" warnClass="warn" infoClass="info"></h:messages>
		<h:messages globalOnly="false" errorClass="err" warnClass="warn" infoClass="info"></h:messages>
	</div>
	<f:loadBundle var="messages" basename="net.javabeat.jsf.messages"></f:loadBundle>
		<h1>
			<h:outputText value="#{msg.head}" />
		</h1>
		<h2>
			<h:outputText value="#{msg.example_name}" />
		</h2>
		<h:outputText value="#{msg.hello_message}"/>
		<br/>
		<br/>
		<h:outputText value="#{messages.inlineLoad}"/>
		<br/>
		<br/>
		<h:panelGrid columns="3">
			<h:outputText value="#{msg.enter_message}"/>
			<h:inputText id="message" value="#{indexBean.message}"/>
			<h:message for="message" errorClass="err" warnClass="warn" infoClass="info"></h:message>
			<h:outputText value="#{msg.enter_email}"/>
			<h:inputText id="email" value="#{indexBean.email}"/>
			<h:message for="email" errorClass="err" warnClass="warn" infoClass="info"></h:message>
		</h:panelGrid>
		<h:commandButton value="Send" action="#{indexBean.send}"/>
		<h:commandButton value="#{messages.german}"
			action="#{indexBean.changeLocale('de')}"
				rendered="#{indexBean.locale == 'en'}"/>
		<h:commandButton value="#{messages.english}"
			action="#{indexBean.changeLocale('en')}"
				rendered="#{indexBean.locale == 'de'}"/>
	</h:form>
</h:body>
</html>

3. faces-config.xml

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
	version="2.2">
<application>
	<resource-bundle>
		<base-name>net.javabeat.jsf.application</base-name>
		<var>msg</var>
	</resource-bundle>
</application>
</faces-config>

4.The Directory Structure

JSF 2 Message Example 1

5. JSF 2 Messages Demo

The below snapshots will show you a complete scenario of using the messages either message component for component-based messages or messages for view-based messages.
The developed scenario has supported the locales (English/German) in order to explain the concept of localizing the messages that consumed by. The suggested scenario contains the following points that should bring your attention:

  • The message component used for displayed the error/info/warn messages for a specific component in the view.
  • The messages component used for displayed the error/info/warn messages for the whole view.
  • The messages component provide attribute (globalOnly) that used for determine whether the messages that being added in the faces context for specific component will be displayed or not.
  • The styles err, warn and info are used by the jsf message/messages component based on the used severity.

JSF 2 Message Example 2

JSF 2 Message Example 3

JSF 2 Message Example 4

JSF 2 Message Example 5

JSF 2 Message Example 6

JSF 2 Message Example 7

[wpdm_file id=21]

Category: JSFTag: JSF 2

About Amr Mohammed

Previous Post: « JavaScript – Data Types and Variables
Next Post: JavaScript Objects »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact