Integrating Images with JSF, CSS with JSF and, JS with JSF

Exclusive offer: get 50% off this eBook here
JSF 2.0 Cookbook

JSF 2.0 Cookbook — Save 50%

Over 100 simple but incredibly effective recipes for taking control of your JSF applications

£16.99    £8.50
by Anghel Leonard | June 2010 | Java Open Source Web Development

In this article by Anghel Leonard, author of the book JSF 2.0 Cookbook, we will cover the following:

  • Injecting CSS in JSF
  • JSF, CSS, and tables
  • Integrating JavaScript and JSF
  • Getting a JSF inputText value from JavaScript
  • Working with JSF hidden fields from JavaScript
  • Passing parameters with HTTP GET within the URL
  • Populating a JS load function with JSF values
  • Dynamic images with PrimeFaces
  • Using resource handlers

Starting from the presented recipes, you can then extrapolate them to obtain more complex solutions for your own websites. We have tried to put on the line the main aspects of integrating JSF with images, CSS, and JS.

(For more resources on JSF, see here.)

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 flexible and supports more kinds of attributes for injecting CSS code in JSF pages.

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:

Name

Description

columnClasses

This is used to specify the comma-separated list of CSS style

classes to be applied on the columns of the table.

headerClass

This is used to specify the spaces-separated list of CSS style

classes to be applied on the header of the table.

footerClass

This is used to specify the spaces-separated list of CSS style

classes to be applied on the footer of the table.

rowClasses

This is used to specify the comma-separated list of CSS style

classes to be applied on the rows of the table.

styleClass

This is used to set the CSS class for the component.

style

This is used to set the CSS style definition for the component.

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.

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.

JSF 2.0 Cookbook Over 100 simple but incredibly effective recipes for taking control of your JSF applications
Published: June 2010
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

(For more resources on JSF, see here.)

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.

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?faces-
redirect=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.

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.

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.

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 UI kit 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

W e 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/.

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.

See also

You also may want to check:

PrimeFaces tag documentation: http://primefaces.prime.com.tr/docs/tag/

PrimeFaces home page: http://www.primefaces.org/

PrimeFaces ShowCase: http://www.primefaces.org:8080/prime-showcase/ui/ imageCropperExternal.jsf

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:

Integrating Images with JSF, CSS with JSF and, JS with JSF

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

  • Accessing images can be accomplished with h:graphicImage, shown next:

    <h:graphicImage library="images" name="RafaelNadal_1.jpg"/>
    <h:graphicImage library="images" name="RafaelNadal_2.jpg"/>

  • Accessing CSS documents can be accomplished with h:outputStylesheet, shown next:

    <h:outputStylesheet library="css" name="simple.css"/>

  • Accessing JS documents can be accomplished with h:outputScript, shown next:

    <h:outputScript library="javascript" name="simple.js"
    target="head"/>

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 <head> tag—remember that if you put JavaScript in the <body> of a page, the browser will execute the JavaScript when the page loads. On the other hand, if you place JavaScript in the <head> 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']}"/>

Summary

In this article, we saw a set of recipes that discussed integrating images with JSF, CSS with JSF and, JS with JSF.


Further resources on this subject:


JSF 2.0 Cookbook Over 100 simple but incredibly effective recipes for taking control of your JSF applications
Published: June 2010
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

About the Author :


Anghel Leonard

Anghel Leonard is a senior Java developer with more than 13 years of experience in Java SE, Java EE, and related frameworks. He has written and published more than 50 articles about Java technologies and more than 500 tips and tricks for many websites that are dedicated to programming. In addition, he has written the following books:

  • Tehnologii XML XML în Java, Albastra
  • Jboss Tools 3 Developer's Guide, Packt Publishing
  • JSF 2.0 Cookbook, Packt Publishing
  • JSF 2.0 Cookbook: LITE, Packt Publishing
  • Pro Java 7 NIO.2, Apress
  • Pro Hibernate and MongoDB, Apress

Currently, Anghel is developing web applications using the latest Java technologies on the market (EJB 3.0, CDI, Spring, JSF, Struts, Hibernate, and so on). Over the past two years, he's focused on developing rich Internet applications for geographic information systems.

Books From Packt

Amazon SimpleDB Developer Guide
Amazon SimpleDB Developer Guide

Spring Security 3
Spring Security 3

Oracle JRockit: The Definitive Guide
Oracle JRockit: The Definitive Guide

Drupal 7 First look
Drupal 7 First look

Moodle 1.9 for Design and Technology
Moodle 1.9 for Design and Technology

Hacking Vim 7.2
Hacking Vim 7.2

Oracle Application Express 3.2 – The Essentials and   More
Oracle Application Express 3.2 – The Essentials and More

Grok 1.0 Web Development
Grok 1.0 Web Developmentg

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software