• 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.0 – Images, CSS and Java Script

July 2, 2010 //  by Krishna Srinivasan//  Leave a Comment

This book will cover all the important aspects involved in developing JSF applications. It provides clear instructions for getting the most out of JSF and offers many exercises to build impressive desktop-style interfaces for your web applications. You will learn to develop JSF applications starting with simple recipes and gradually moving on to complex recipes.
We start off with the simple concepts of converters, validators, and file management. We then work our way through various resources such as CSS, JavaScript, and images to improve your web applications. You will learn to build simple and complex custom components to suit your needs. Next, you get to exploit AJAX as well as implement internationalization and localization for your JSF applications. We then look into ensuring security for your applications and performing testing of your applications. You also get to learn all about Facelets and explore the newest JSF 2.0 features. Finally, you get to learn a few integrations such as JSTL with JSF, Spring with JSF, and Hibernate with JSF. All these concepts are presented in the form of easy-to-follow recipes.
Each chapter discusses separate types of recipes and they are presented with an increasing level of complexity from simple to advanced. All of these recipes can be used with JSF 1.2 as well as JSF 2.0.

also read:

  • JSF Articles
  • Accessing Web Services from JSF applications
  • Introduction to Java Server Faces
  • Introduction to JSF Core Tags Library
  • Introduction to Java Server Faces(JSF) HTML Tags
  • AJAX Support in Struts 2.0
  • Using Converters in JSF
  • Request Processing Lifecycle phases in JSF

What This Book Covers

Chapter 1, Using Standard and Custom Converters in JSF covers the standard and custom converters in JSF. We start with implicit and explicit conversion examples, then move on to creating and using custom converters, and we end up with client-side converters using MyFaces Trinidad.

Chapter 2, Using Standard and Custom Validators in JSF continues with standard and custom validators. We see how to use a standard validator, how to create and use custom validators, and how to use RichFaces and Apache MyFaces validators. We also present the new JSF 2.0 validators, such as f:validateRegex and f:validateRequired.

Chapter 3, File Management discusses file management issues. You will see different methods for downloading and uploading files, learn how to use JSF Core, RichFaces, PrimeFaces, and Apache Tomahawk. In addition, you will see how to export data to PDF and Excel, and how to extract data from an uploaded CSV file.

Chapter 4, Security covers some security issues. You will see how to use the JSF Security project without JAAS Roles, use secured managed beans with JSF Security, and use Acegi/Spring security in JSF applications.

Chapter 5, Custom Components discusses custom components in JSF. You will see how to build different kinds of custom components in JSF 2.0, Archetypes for Maven, JSF and Dojo and more.

Chapter 6, AJAX in JSF starts with the f:ajax tag, continues with Dynamic Faces, RichFaces, ajax4jsf, and ends up with PrimeFaces and learning to write reusable AJAX components.

Chapter 7, Internationalization and Localization covers internationalization and localization. We will see how to load message resource bundles on JSF pages and how to use locales and message resource bundles. We then move on to parameterized messages, learning how to display Arabic, Chinese, Russian, and so on and how to select time zones in JSF 2.0.

Chapter 8, JSF, Images, CSS, and JS discusses JSF with images, CSS, JS, and RSS. We will integrate JS with JSF, pass values between JS and JSF, crop images, work with dynamic images, work with pop-up windows, RSS support, and so on.

Chapter 9, JSF—Managing and Testing starts with Faces Console, and moves on to JSFUnit and JMeter.

Chapter 10, Facelets covers Facelets recipes. You will see how to work with aliasing components, templates, composition components, passing actions, and sub-elements to composition components.

Chapter 11, JSF 2.0 Features presents some of the most relevant JSF 2.0 features, such as annotations, exception handling mechanism, declarative event handling, URLs based on specified navigation outcome, JSF view parameters, JSF 2.0, and navigation cases.

Chapter 12, Mixing JSF with Other Technologies discusses mixing JSF with other important technologies, such as Spring, Seam, JSTL, Hibernate, and EJB (JPA).

Appendix, Configuring JSF-related Technologies talks about the issues when a JSF related technology gets into the equation. You need to add some specific configuration, you have to create a “bridge” between JSF and the technology used. This appendix contains the configurations for a few technologies.

  • Explore all the new features of JSF 2.0 that has numerous advantages over JSF 1.2
  • Work with standard and custom JSF converters and validators
  • Learn to upload and download with JSF, RichFaces and MyFaces
  • Work with resources such as CSS, JavaScript and images
  • Develop sophisticated applications using standard and custom components
  • Explore AJAX in JSF and related frameworks
  • Enhance your applications with internationalization and localization
  • Exploit all of the security tasks in JSF and perform thorough testing of your applications
  • Get to grips with JSFUnit, JMeter and JXIsight
  • Integrate JSF with JSTL, Spring and Hibernate

JSF, Images, CSS, and JS

In this chapter, we will cover:

  • Injecting CSS in JSF
  • JSF, CSS, and tables
  • JSF and dynamic CSS
  • Integrating JavaScript and JSF
  • Getting a JSF inputText value from JavaScript
  • Working with JSF hidden fields from JavaScript
  • Passing parameters from JS to JSF (client to server)
  • Passing parameters from JSF to JS (server to client)
  • Opening a pop-up window using JSF and JS
  • Passing parameters with HTTP GET within the URL
  • Communicating between parent pop-up windows
  • Populating a JS load function with JSF values
  • Dynamic images with PrimeFaces
  • Cropping images with PrimeFaces
  • Working with rss4jsf project
  • Using resource handlers

Injecting CSS in JSF

In this recipe, you will see how to add CSS styles to JSF tags. It is a simple solution, but it has the advantage that it can be applied to almost all JSF tags that render text, images, and so on.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

When you need a simple and classic solution to integrate CSS in JSF it is important to know that JSF components support the styleClass and style attributes. The styleClass attribute is used when you are working with CSS classes, while the style attribute allows you to place CSS code directly in place between quotes. You can see in the following code snippet how this works with the h:outputText component:

	<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:ui="http://java.sun.com/jsf/facelets"
		xmlns:h="http://java.sun.com/jsf/html"
		xmlns:f="http://java.sun.com/jsf/core">
		<h:head>
			<title>JSF and CSS example</title>
			<style type="text/css">
				.message { text-align: left;
					letter-spacing:5px;
					color:#000099
				}
				.message-overline { text-decoration:overline;
				}
				.message-font { font-family:georgia,garamond,serif;
					font-size:20px;
					font-style:italic;
				}
			</style>
		</h:head>
		<h:body>
			<h:outputText styleClass="message"
				value="This text is CSS formated by 'message' class!"/>
			<br /><br />
			<h:outputText styleClass="message message-overline"
				value="This text is CSS formated by 'message' and
				'message-overline' classes!"/>
			<br /><br />
			<h:outputText styleClass="message message-overline message-font"
				value="This text is CSS formated by 'message',
				'message-overline' and 'message-font' classes!"/>
			<br /><br />
			<h:outputText style="text-align: left;letter-spacing:5px;
				color:#000099" value="This text is CSS formated
				using the 'style' attribute instead of 'message' class!"/>
			<br /><br />
			<h:outputText style="text-align: left;letter-spacing:5px;
				color:#000099;text-decoration:overline;"
				value="This text is CSS formated using the
				'style' attribute instead of 'message'
				and 'message-overline' classes!"/>
			<br /><br />
			<h:outputText style="text-align: left;letter-spacing:5px;
				color:#000099;text-decoration:overline;
				font-family:georgia,garamond,serif;
				font-size:20px;font-style:italic;
				" value="This text is CSS formated using the
				'style' attribute instead of 'message',
				'message-overline' and 'message-font' classes!"/>
			<br /><br />
		</h:body>
	</html>

Notice that when you need to specify more CSS classes under the same styleClass you need to separate their names by space.

How it works…

As you can see the JSF – CSS construction looks similar to HTML – CSS usage. The interaction between JSF – CSS imitates HTML – CSS interaction, but, as you will see in the next recipes, JSF is more fl exible and supports more kinds of attributes for injecting CSS code in JSF pages.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Injecting_CSS_in_JSF.

JSF, CSS, and tables

There are two kinds of grids (tables) that are very often used in JSF, h:panelGrid and h:dataTable. Both of them can be styled with CSS in detail using a set of dedicated attributes. In this recipe you will see these attributes at work for h:panelGrid, but it is very simple to extrapolate this to h:dataTable .

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0
classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

Suppose that we have an h:panelGrid. We can “populate” it with CSS styles, using the following set of attributes:

Knowing these attributes, we build a JSF page to show you how to use them in practice (notice where we have placed the attributes):

	<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:ui="http://java.sun.com/jsf/facelets"
		xmlns:h="http://java.sun.com/jsf/html"
		xmlns:f="http://java.sun.com/jsf/core">
		<h:head>
			<title>JSF and CSS example</title>
			<style type="text/css">
				.message { text-align: left;
					letter-spacing:5px;
					color:#000099
				}
				.message-font { font-family:georgia,garamond,serif;
					font-size:20px;
					font-style:italic;
				}
				.odd { background-color: blue }
				.even { background-color: red }
			</style>
		</h:head>
		<h:body>
			<h:form>
				<h:panelGrid columns="3" border="1" footerClass="message"
					headerClass="message-font" rowClasses="odd, even"
					title="PanelGrid and CSS">
					<f:facet name="header">
						<h:outputText value="Fill Names Below"/>
					</f:facet>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
					<h:inputText/>
						<f:facet name="footer">
							<h:outputText value="The End"/>
						</f:facet>
				</h:panelGrid>
			</h:form>
		</h:body>
	</html>

How it works…

Since we have an attribute for each part of a grid, we can easily specify CSS styles to customize the design of each of these parts. JSF will combine the specified CSS styles to render a cool grid to the user.

There’s more…

The h:dataTable allows you to use the same CSS attributes for table header, footer, and so on.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: JSF_CSS_and_tables

Integrating JavaScript and JSF

JSF and JavaScript can combine their forces to develop powerful applications. For example, let’s see how we can use JavaScript code with h:commandLink and h:commandButton to obtain a confirmation before getting into action.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

As you know the h:commandLink takes an action after a link is clicked (on the mouse click event), while h:commandButton does the same thing, but renders a button, instead of a text link. In this case, we place a JavaScript confirmation box before the action starts its effect. This is useful in user tasks that can’t be reversed, such as deleting accounts, database records, and so on.
Therefore, the onclick event was implemented as shown next:

	<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:ui="http://java.sun.com/jsf/facelets"
		xmlns:h="http://java.sun.com/jsf/html"
		xmlns:f="http://java.sun.com/jsf/core">
		<h:head>
			<title>JSF and JavaScript example</title>
		</h:head>
		<h:body>
			<!-- using h:commandLink and JavaScript -->
			<h:form id="myCLForm">
				<h:commandLink id="cmdlinkID" value="Delete record"
					onclick="if (!confirm('Are you sure you want to delete the
					current record?')) return false"
					action="#{bean.deleteRecord}"/>
			</h:form>
			<!-- using h:commandButton and JavaScript -->
			<h:form id="myCBForm">
				<h:commandButton id="cmdbtnID" value="Delete record"
					onclick="if (!confirm('Are you sure you want to delete the
					current record?')) return false"
					action="#{bean.deleteRecord}"/>
			</h:form>
		</h:body>
	</html>

How it works…

Notice that we embed the JavaScript code inside the onclick event (you also may put it separately in a JS function, per example). When the user clicks the link or the button, a JS confirmation box appear with two buttons. If you confirm the choice the JSF action takes
place, while if you deny it then nothing happens.

There’s more…

You can use this recipe to display another JS box, such as prompt box or alert box.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Integrating_JavaScript_and_JSF.

Getting a JSF inputText value from JavaScript

In the next example we will type text in a JSF h:inputText component, and after each character is typed, a JavaScript alert box will reveal the text inserted so far.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

The secret of our recipe consists in using the onkeyup event for calling a JavaScript function.
Here it is the code:

	<h:head>
		<script type="text/javascript" language="javascript">
			function getInputText(text)
			{
				alert(text.value);
			}
		</script>
	</h:head>
	<h:body>
		<h:inputText id="inputId" value=""
			onkeyup ="getInputText(this);"/>
	</h:body>

How it works…

When a character is typed in the h:inputText , the onkeyup event is fired and the JavaScript getInputText function is called. This JS function extracts the text from the JSF h:inputText through the received argument. Notice that the this keyword is used.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Getting_a_JSF_inputText_value_
from_JavaScript.

Working with JSF hidden fields from JavaScript

The idea of putting together JSF hidden fields and JavaScript comes from a simple question—how to use JavaScript and JSF to submit a form from a control event? In other words you will see how to submit a form immediately after a checkbox is checked or unchecked (it is simple to imagine how to apply this solution for other components such as radio buttons).

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

The solution is pretty simple, but the idea it self is ingenious and involves JavaScript and JSF command links. First we write a simple JSF form (this form will be submitted when the checkbox is checked / unchecked):

	<h:form id="myForm">
		<h:selectBooleanCheckbox id="checkbox"
			value="#{participateBean.participate}" title="Click it to select or
			deselect" onclick="submitForm('myForm:hiddenCommandLink');"/>
		<h:outputText value="Want to participate?"/>
	</h:form>

As you can see, when the onclick event is fired (the checkbox is checked or unchecked) the submitForm JavaScript function is called. This function receives one argument, representing the id of a simple JSF h:commandLink component. This component contains the form’s action (a redirection to another page) and a simple CSS style for being invisible. Putting this command link in the form will look like the following:

	<h:form id="myForm">
		<h:selectBooleanCheckbox id="checkbox"
			value="#{participateBean.participate}" title="Click it to select or
			deselect" onclick="submitForm('myForm:hiddenCommandLink');"/>
		<h:outputText value="Want to participate?"/>
		<h:commandLink id="hiddenCommandLink"
			style="display:none;visibility:hidden;" action="response?facesredirect=
			true"/>
	</h:form>

Now, the submitForm function simulates a click event on our command link through pure JavaScript code:

	function submitForm(commandLinkId) {
		var fire = document.getElementById(commandLinkId);
		if (document.createEvent) {
			var eventObject = document.createEvent("MouseEvents");
			eventObject.initEvent( "click", true, false );
			fire.dispatchEvent(eventObject);
		} else if (document.createEventObject); { fire.
			fireEvent("onclick"); }

We didn’t say anything about the ParticipateBean, since is not relevant here, it is just for proving that the submission really works.

How it works…

When users check/uncheck the form’s checkbox, the onclick event is fired and the JS submitForm is called. The secret is that this function received the id of a command link—which is in the JSF form—and it is able to submit this form through its action attribute.
This action is forced by JavaScript code by dispatching an artificial click event for the command link.

There’s more…

You can use this recipe for any other JSF component. For example, you may want to submit a form after a radio button is selected, or after a character is typed in a text field, or a combo-box item is selected and so on. The principle remains the same, except that you
need to fire up the correct event (such as onclick or onchange), depending on the JSF component.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Working_with_JSF_hidden_fields_ from_JavaScript.

Passing parameters with HTTP GET within the URL

In the Passing parameters from JS to JSF (client to server) recipe, you saw how to pass parameters from client to server. One of the presented solutions passes parameters with HTTP GET within the URL. In this recipe, you can see a quick method of retrieving those
parameters from JSF code.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

You can retrieve parameters using the #{param.parameter_name} expression, such as the following (notice that the parameter is named id, and we are using #{param.id} to retrieve its value):

	<h:form id="formId">
		<h:commandButton id="btn1Id" value="Pass parameter 100 ..."
			onclick="window.open('pagetwo.xhtml?id=100', 'MyWindow',
			'height=350,width=250,menubar=no,toolbar=no'); return false;" />
	</h:form>
	…
	<h:outputText value="The parameter passed is: #{param.id}" />
	…

Another solution is to retrieve the value through a managed bean, as shown next:

	<h:form id="formId">
		<h:commandButton id="btn2Id" value="Pass parameter 200 ..."
			onclick="window.open('pagethree.xhtml?id=200', 'MyWindow',
			'height=350,width=250,menubar=no,toolbar=no'); return false;" />
	</h:form>
	…
	<h:outputText value="The parameter passed is: #{bean.passedParameter}"/>
	…

The managed bean that actually retrieves the parameter value is:

	package bean;
	import javax.faces.bean.ManagedBean;
	import javax.faces.bean.RequestScoped;
	import javax.faces.context.FacesContext;

	@ManagedBean
	@RequestScoped
	public class Bean {
		private String passedParameter;
		public String getPassedParameter() {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			this.passedParameter = (String) facesContext.getExternalContext().
				getRequestParameterMap().get("id");
			return this.passedParameter;
		}
		public void setPassedParameter(String passedParameter) {
			this.passedParameter = passedParameter;
		}
	}

How it works…

In the first example, the task is performed by the EL, #{param.parameter_name}, while, in the second example, the managed bean uses the getRequestParameterMap function, which has access to the GET request parameters.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Pass_parameters_with_HTTP_GET_within_the_URL.

Populating a JS load function with JSF values

As you know, when a web page is loaded, the code on the page is generally processed from the top down. JS code can interfere in this top-down order in many ways, and the onload function (specified on the body tag) is one of these possibilities. When the page is loaded, the browser will stop at the onload function and will execute the indicated script. In this recipe, you will see how to populate that script with JSF values, provided by a managed bean.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

The onload function calls our JS function, named calledOnLoad. Our function will retrieve some JSF values from a managed bean. Here it is how it will do this:

	<xml version='1.0' >
	<!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:h="http://java.sun.com/jsf/html">
		<h:head>
			<title>Passing parameters on HTTP GET</title>
			<script type="text/javascript" language="javascript">
				function calledOnLoad(){
					var p_1 = '<h:outputText value="#{bean.param_1}"/>';
					var p_2 = '<h:outputText value="#{bean.param_2}"/>';
					var ot = document.getElementById("formId:textId");
					ot.textContent="Parameters from bean are:"+p_1+" and " + p_2;
				}
			</script>
		</h:head>
		<h:body onload="calledOnLoad();">
			<h:form id="formId">
				<h:outputText id="textId" value=""/>
			</h:form>
		</h:body>
	</html>

The managed bean is:

	package bean;
	import javax.faces.bean.ManagedBean;
	import javax.faces.bean.RequestScoped;
	@ManagedBean
	@RequestScoped
	public class Bean {
		private String param_1 = "Me";
		private String param_2 = "You";
		public String getParam_1() {
			return param_1;
		}
		public void setParam_1(String param_1) {
			this.param_1 = param_1;
		}
		public String getParam_2() {
			return param_2;
		}
		public void setParam_2(String param_2) {
			this.param_2 = param_2;
		}
	}

How it works…

The secret of this recipe is in this line:

	var p_1 = '<h:outputText value="#{bean.param_1}"/>';

Notice that JS knows how to parse this line to extract the JSF value, instead of assigning a verbatim text to the p_1 variable.

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Populate_a_JS_load_function_with_JSF_values.

Dynamic images with PrimeFaces

PrimeFaces is a lightweight library for JSF with regard to its functionality, simplicity, and support. Its power consists in AJAX support, providing more than 70 AJAX-based components. The additional TouchFaces module features a Uikit for developing mobile web applications.
In this recipe, you will see how to use PrimeFaces to retrieve images from a database and to provide them dynamically to our JSF page.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library. In addition, we have used PrimeFaces 2.0, which provide support for JSF 2.0. You can download this distribution from http://www.primefaces.org/. The PrimeFaces libraries (including necessary
dependencies) are in the book bundle code, under the /JSF_libs/PrimeFaces – JSF 2.0
folder.

How to do it…

Our recipe will look very simple, thanks to PrimeFaces.Practically, all we do is to pick up the PrimeFaces fruits. The following code retrieves a BLOB from a JDBC ResultSet and provides its InputStream as a StreamedContent (the backing bean is listed next):

	public class PictureBean {
		private StreamedContent myImage;
		public PictureBean() {
			InputStream inputStream = //InputStream of a blob
			myImage = new DefaultStreamedContent(inputStream, "image/png");
		}
		public StreamedContent getMyImage(){
			return myImage;
		}
		public void setMyImage(StreamedContent myImage){
			this.myImage = myImage;
		}
	}

And the p:graphicImage tag can display any binary image, as shown next:

	<p:graphicImage value="#{pictureBean.myImage}" />

How it works…

The entire solution is mapped in PrimeFaces; therefore you will need to go deeply into this framework to understand its secrets. Apparently, everything we have done relates to a simple JSF application with a simple conversational state between a JSF page and a backing bean.

Using resource handlers

Starting with JSF 2.0 we have access to a standard mechanism for defining and accessing resources. We must place our resources under a top-level directory named resources, and use the dedicated JSF 2 tags to access those resources in our views.

Getting ready

We have developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.

How to do it…

First, we create the top-level folder, named resources, and, under it, we create a set of sub-folders that reflect their content by suggestive names. For example, the following figure is our resources folder tree:

Going further, we can access resources with a set of dedicated tags, as follows:

    • Accessing images can be accomplished with h:graphicImage, shown next:
    • Accessing CSS documents can be accomplished with h:outputStylesheet, shown next:
    • Accessing JS documents can be accomplished with h:outputScript, shown next:

Notice that in all tags we have a common attribute, named library. Its value corresponds to the name of a sub-directory of the resources directory—the name of the directory in which the resource resides. The name attribute indicates the resource name and the target attribute indicates where the resource should be placed (as you can see, we placed the JavaScript resource under the tag—remember that if you put JavaScript in the of a page, the browser will execute the JavaScript when the page loads. On the other hand, if you place JavaScript in the of a page, that JavaScript will only be executed when called.).

How it works…

Working with this new mechanism is very simple and intuitive since JSF will automatically search for our resources under the resources folder. All we need to do is to use the corresponding tag as you just saw. The most important thing is to correctly indicate the sub-folder of the resources folder and the resource’s name and JSF will take care of the rest.

There’s more…

Sometimes you’ll need to access a resource using the JSF expression language. For example, you can access an image with h:graphicImage, like this:

	<h:graphicImage value="#{resource['images:RafaelNadal_1.jpg']}"/>

See also

The code bundled with this book contains a complete example of this recipe. The project can be opened with NetBeans 6.8 and it is named: Use_resource_handlers.

Category: JSFTag: JSF 2.0

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « Oracle SQL Developer 2.1
Next Post: How to write a Custom Plugin for Maven? »

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