A Simple JSF2 Ajax Example

Time to look at how to get some Ajax into Oddjob’s new JSF2 Front End. But first a simple example to see how it works.

Here’s a form without Ajax:

Colour Selector Without Ajax

Colour Selector Without Ajax

Press a button and the colour of the box changes. Here’s the code:

<?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 lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"> 
    <head>
    	<style type="text/css">
.box { 
	margin: 20px; 
	width: 100px; 
	height: 100px; 
	border: solid 2px;
}

    	</style>
    </head>
	<body>

		<h1>Pick A Colour</h1>

			<h:form>
				<h:commandButton value="Blue"
					action="#{colourSelector.blue}" />
				<h:commandButton value="Red"
					action="#{colourSelector.red}" />
				<h:commandButton value="Green"
					action="#{colourSelector.green}" />
			</h:form>

			<div style="background-color: #{colourSelector.colour};" class="box"/>				

			<p>(Colour changed at #{colourSelector.currentTime})</p>

			<p>(Page loaded at #{colourSelector.currentTime})</p>

    </body>
</html>

and:

@ManagedBean
public class ColourSelector {

	private String colour = "grey";

	public void blue() {
		colour = "blue";
	}

	public void green() {
		colour = "green";
	}

	public void red() {
		colour = "red";
	}

	public String getColour() {
		return colour;
	}

	public String getCurrentTime() {
		return new SimpleDateFormat("HH:mm:ss").format(new Date());
	}
}

Now let’s add Ajax:

	<body>

		<h1>Pick A Colour</h1>

		<f:ajax render="square">
			<h:form>
				<h:commandButton value="Blue"
					action="#{colourSelector.blue}" />
				<h:commandButton value="Red"
					action="#{colourSelector.red}" />
				<h:commandButton value="Green"
					action="#{colourSelector.green}" />
			</h:form>
		</f:ajax>

		<h:form id="square">
			<div style="background-color: #{colourSelector.colour};" class="box"/>				

			<p>(Colour changed at #{colourSelector.currentTime})</p>
		</h:form>		

			<p>(Page loaded at #{colourSelector.currentTime})</p>

    </body>

I need the second <h:form> because in the ajax tag I need to specify the id of a JSF component to render and JSF doesn’t come with a generic panel type component so I used a form.

Now when we press the buttons only the area in the form square updates. You can see this from the times.

Colour Selector With Ajax

Colour Selector With Ajax

And that’s how simple it is to add Ajax to a page with JSF2.

Comments are closed.