Sunday, December 13, 2009

How Energy Works

 

My Dad grew up in Ireland in the 1930’s. Actually, my Dad grew up being bounced around Belfast orphanages for the first fifteen or sixteen years of his life. Together, my parents always worked had and made great sacrifices to make sure that my older brother and I never ‘went without.’ But having said that, nothing bothered my Dad more than seeing his two sons take for granted the types things he never had when he was growing up.

“You kids!” my old man would yell when he saw our toys and gadgets not put away, or left out for someone to potentially step on them and break them. “When I was a kid, all I ever got for Christmas was an Orange, and sometimes I didn’t even get that!”

Of course, over thirty years later, I’m still thinking of that little rant old Cecil McKenzie used to yell at me, but not because I need some motivation clean up my apartment. No, I keep thinking about that rant from my Dad, because I keep wondering to myself, “where the hell would you find an orange in 1930’s Belfast in the middle of winter?”

Seriously, oranges don’t grow in Ireland, and even if they did, Oranges don’t get harvested in late December; so seriously, who in the 1930’s was harvesting all of these Belfast-bound oranges?

But pondering the conundrum about who was growing oranges in December in the 1930’s started me thinking about just how messed up our modern day diet has become.

Deal with this piece of logic for a second. For the last million or so years, sugary fruits have always become available for harvest at exactly the same time of the year. And what time of the year is that? Typically, most fruits, berries, and other sugary foods become available to us in the September to October range. You know, the time of year we colloquially refer to as ‘harvest.’ :P

So, for the last million years, the human animal has evolved and adapted to the fact that for about two months of the year, sugary sweets will be aplenty. As humans, we need sugar. Sugar must always be present within our blood – without it, we would die. Sugar provides the energy we need to live, and the human body has adapted in some amazing ways to make sure that whenever sugar enters the body, it is not discarded. When sugar comes into the body, it is either used for energy, or it is very efficiently converted into fat, so that it can be easily converted back into sugar when it’s needed.

And that’s the key. SUGAR is turned into FAT. Your body runs on sugar. Sugar is your bodies fuel. When you run out of sugar in your blood, you die. Your body needs sugar.

Any precursory study of the human body will reveal the fact that your body is driven by the pessimistic assumption that it perilously close to running out of two things: water and sugar. Your body goes to extraordinary lengths to conserve water. Your body filters it, it recycles it, it takes dirty water out of your system, filters it internally, expels any contaminants, and then puts that clean water back into your body. It really is an amazing system of cleansing and conservation that would put any modern water treatment plant to shame.

Of course, your body can only maintain so much water in its system, and when you drink way too much, your body will get rid of it. Anyone that has consumed too many beers too fast knows all too well about the bodies ability to expel too much H20. Humans aren’t dromedary camels, so, while our bodies go to extreme lengths to the preserve and conserve the water that is currently in our system, we don’t have any really creative mechanism to actually store water, which is the one big difference between how the human body manages and conserves water, and how the body craves, hoards and stores sugar.

The human body craves sugar. The human body loves sugar. As far as mammals are concerned, there is no purer form of energy – sugar is the highest octane fuel your body can consume, and when your body gets some sweet sugar, it won’t get rid of it, no matter how much it gets. Seriously, go drink a gallon of water, and assuming you’re not completely dehydrated, you’ll be pissing like a racehorse in no time. Then pour a pound of sugar into a gallon of water and drink that. You’ll again be pissing like a racehorse, but you won’t be pissing out any of that sugar. In fact, if your body does allow any of that fabulous sugar to leave your body, then you have a disease called diabetes. Seriously, that’s how you know if you have diabetes – sugar is released into your urine and your pee tastes sweet. In fact, the word diabetes roughly translates to “sweet pee,” (and to emphasize that’s pee, not pea.)

Now don’t asked me who finally discovered that all of his friends who were suffering various health maladies had sugary, sweet pee. That’s a story I could probably do without knowing. But the point is, your body doesn’t want a single gram of sugar to just leave your body. Sugar

 

Just think about that point for a moment – if you body doesn’t process all of the sugar that enters your body, then you have a disease. You can’t say that about fats or oils. If you body consumes too much olive oil or butter, it will just dispose of it. There is no disease associated with oily pee. And the same is true with protein. If you eat too much protein, your body just discards it. There’s no disease afflicting modern man that’s named for the latin equivalent of ‘protein pee.’ But if your body isn’t using, consuming, converting and storing every little gram of sugar that enters the bloodstream, then you have a disease called diabetes. Your body loves sugar, and it does everything in its power not to let it go.

Your body needs sugar to function. Every physical process that happens in your body requires energy, and that energy comes from a very small and controlled amount of sugar in your bloodstream. There are various forms of sugar, with many different names. The actual name for the sugar in your blood is glycogen, and without a certain amount of gylcogen in your system, you’d die. Gylcogen is important.

So, where does this blood-sugar come from? Well, that depends; what time of the day is it?

If it’s seven o’clock in the morning, and you’re just getting up from a cozy nine hour sleep, and assuming you didn’t have a monstrously huge, insulin coma inducing buffet dinner before going to bed, well, your body shouldn’t have any food in its system, and the only way your body can maintain a steady blood-sugar level is by turning your fat stores into sugar, and putting that sugar into your bloodstream. When your body converts fat to sugar, it creates a byproduct known as a keytone. Keytones stink. That’s why morning breath can be so bad after a long sleep – your body is converting fat into sugar, and the concentrated ketone byproducts are being exhaled. Morning breath is actually a neat indication that your body is getting rid of its fat stores!

 

There’s a myth that says your body can burn fat. That’s simply not true. Your body only burns sugar. The good news is though, when there’s no sugar available from other sources, your body convert your fat stores into sugar, and burn that. Really, that’s all your fat stores are – temporary storage devices for sugar, and when you don’t have any other sugar source in your system, your body uses up its fat stores. So, the secret to losing weight is to simply deplete your bloodsugar – your body will have no other choice than to convert fat into sugar in order to make up for the shortfall.

 

 

 

THE HUMAN BODY DOES NOT BURN FAT! The human body burns sugar.

 

 

 

In the 1930’s, an orange really was a treat to get at Christmas, and it’ wasn’t just because my Dad was living in an orphanage. Historically speaking, oranges in December are rare, and it probably was a pretty darned good treat to bite into a juicy, sugary piece of fruit, at Christmas. Of course, today, you can walk into a grocery store at any time of the year and get a pretty decent sized bag of oranges for less than the change you’ve probably got in your pocket right now.

 

 

 

 

Fat doesn’t make you Fat!

Eat all the protien and oils you want!

Sugar is the Devil

 

 

You’ve probably heard that there are three sources of energy that your body can use: proteins, oils and sugars. Smarter people than mean usually use the terms ‘fats’ instead of ‘oils’ and ‘carbohydrates’ instead of ‘sugars, but I going to just keep things simple.

Now here’s the simple little truth. Your body cannot convert proteins and oils into fat. It’s impossible. There is no chemical process in your body that will convert protein and oils into human fat. So, you can eat as much steak, and down as much melted butter as you like, and none of those oils and protein will ever be stored as fat on your body. When you eat oils and protein, the body will either convert those oils and proteins into instantaneous energy, incorporate those oils and proteins into your skeletal or muscular structure, or they will be discarded by your body entirely, but those oils and proteins you eat will never be deposited on your body as fat.

Of course, here’s the rub. While your body won’t convert oils and proteins into fat tissue, your body will do everything in its power to store every gram of sugar that comes into its body as fat.

 

 

 

Solar

Wind

Coal

 

 

 

 

For the most part, that’s true.

Fats is a bad term, because people make the immediate association between the term ‘fats’ and the actual fat that gets stored on our body. As you will see, there really is no association between the two. I much prefer the term oils, because that’s

 

 

What is insulin?

Insulin is the microscopic, biological equivalent of a hypodermic needle.

Almost every interesting and important biological process that happens within your body, happens within a cell.

Your cells have an outer skin, known as the cell wall. The cell wall is a important protective layer, keeping all of the important innards of the cell together in one place, and protecting those innards from any contaminants or viruses or any other unsavory characters that might want to get inside of the cell and mess things up. Unfortunately, these incredible defense system can be a little bit overzealous, and block out some really, really beneficial nutrients as well. And guess which life sustaining nutrient is simply too large and too gamely looking to make it past the cell wall’s defenses? Well, if you guessed ‘sugar’, you’d be right.

So, in order for your body to be able to function, your cells need sugar. But, the defenses of the cell wall make it impossible for sugar to break through. So, when your body sees elevated levels of sugar in your blood, sugar that’s come from a big glass of orange juice, or a handsome slice of watermelon, your body releases insulin. The insulin rushes through your bloodstream and rounds up every last little molecule of sugar, like a bunch of cowboys bringing in a herd of cattle.The insulin then pierces the wall of an unsuspecting bloodcell, and like a needle vaccinating your arm, the insulin pierces the defensive wall, injecting sugar directly into the bloodcell.

Now here’s one of the problems with insulin. Sure, insulin can poke a hole in a blood cell and push in some sweet sugar, but at the same time, the blood cell’s defensive have been breached, and the potential exists for various viruses and toxins to capitalize on this breach and infect the cell.

Here’s an interesting point to ponder. When does flu season start? In the Northern hemisphere, it starts in October and November. In fact, we coloquially refer to the flu, or just a general virus based sickness as ‘a cold’, because they typically hit us when the weather takes a bit of a turn. But if you look at it in a historical perspective, it’s also the time where the crops have been harvested, blood sugar isn’t being burned off as people are working in the fields, and people are consuming, for the first time all year, large quantities of foods that are extremely high in sugars. Be it the North American ritual of Thanksgiving that is celebrated in October in Canada, and November in the USA, or even the pagan celebration of Halloween, the end of the harvest is ritualized all over the globe, by every culture and religion, with celebrations that incorporate the consumption of sugar laden foods.

And of course, after millions of years of evolution, viruses have figured out that right after the harvest, the human blood cells are being constantly punctured and breached. The defenses of the human blood cell are under attack, and they are weakend, as they repair themselves from the violent onslaught of sugar injecting attacks to which insulin has subjected them.

It’s not simply a coincidence that in both the northern and southern hemispheres, the flu season always comes right after harvest, when blood sugar and insulin levels are at their highest.

Thursday, October 29, 2009

Saturday, September 5, 2009

Progress to VCE

"""

"""

public class Game {

private static final String[] VALID_VALUES = {"ROCK", "SCISSORS", "PAPER"};

private static final Map<String, String> WINNING_MAP = new HashMap<String, String>();

private static final Random RND = new Random();

static {

WINNING_MAP.put("ROCK", "SCISSORS");

WINNING_MAP.put("SCISSORS", "PAPER");

WINNING_MAP.put("PAPER", "ROCK");

}

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

while (true) {

System.out.println("enter ROCK, PAPER or SCISSORS");

String userChoice = console.nextLine().toUpperCase();

String computerChoice = VALID_VALUES[RND.nextInt(VALID_VALUES.length)];

if (computerChoice.equals(userChoice)) {

System.out.println("It's a draw, you both had " + computerChoice);

continue;

}

if (WINNING_MAP.get(userChoice).equals(computerChoice)) {

System.out.println("You won, computer had " + computerChoice);

continue;

}

System.out.println("You lost, computer had " + computerChoice);

}

}

}

Page Navigation and Client Interaction

In this section, we will explore the following concepts:

Page navigation techniques

Taking input from the user

Creating a managed bean

Creating and invoking a do<action> method

These concepts will involve the use of the following JSF centric components, tags and elements:

<h:commandButton>

navigaction-case entries in the faces-config file

managed-bean entries in the faces-config file

So far, we’ve played around a bit with JSF custom tags and internationalization and stuff, but all of that has been largely display generation. If all we wanted to do was display text to the user, we wouldn’t need a Servlet Engine and a JSF framework. No, the really kewl stuff happens when we start taking data from the user, and responding dynamically to the user depending on what type of data and information they deliver to us on the server side.

Two of the biggest challenges associated with building dynamic web applications are

1.getting valid information and input from your clients, and

2. secondly, providing an intelligent and informative response to the client based on the information they have provided.

So, with these two tasks being the biggest challenges facing a modern day web application developer, nobody should be surprised by the fact that two of the most core features of JSF are the framework’s built-in navigation model, and the framework’s built-in facilities for simplifying the job of obtaining valid user input.

Of course, my challenge is to come up with some slick and friendly application that we could build together to effectively demonstrate the JSF framework’s page navigation and input management capabilities. To keep things fairly fun and light-hearted as we explore some fairly complicated concepts, I thought we’d prototype a little “Rock-Paper-Scissors” type of application.

I know, “Rock-Paper-Scissors” isn’t the most professional and technical of applications that we can develop, but the concept is pretty universal, and using this fun little game will help avoid having to spend too much time trying to explain all of the various use cases and non-JSF related details that might go along with an application that is more technical.

The basic idea of our implementation will be that the client will be asked to pick one of three gestures: Rock, Paper or Scissors. When the client has submitted their choice, the server will choose one of the three possible gestures, Rock Paper or Scissors. And then, the results of the game will be evaluated, and a response summarizing the results of the game will be sent back to the client. It’s all a pretty simple concept.

*Note, the term ‘gesture’ is used to describe the three choices of Rock, Paper and Scissors. The reason the term ‘gesture’ is used is because when the game is played interactively between two people, hand gestures are used to represent the choice of rock, paper or scissors.

Our online version of the Rock Paper Scissors game will involve five web pages, with the first page prompting the end user to type either Rock, Paper or Scissors into a textfield, after which, they will need to click on a submit button to initiate game play.

The game has three possible outcomes, either a win, lose, or tie. And actually, I’m going to include a fourth outcome, which is failure, which could happen if something either goes wrong, or perhaps the client hasn’t provided a valid option for game play. So, to accommodate our four possible outcomes, we will need to create an additional four JSP pages, named win.jsp, lose.jsp, tie.jsp and failure.jsp.

Now, don’t get too intimindated by the fact that there will be five JSP pages. For the most part, the win, lose and tie.jsp pages will be minimal at best, and almost identical. You’re not going to get carpel-tunnel syndrome typing them out. But as minimalist as they might be, they will go far in demonstrating the built-in page navigation capabilities of JSF.

***Images go here.

Overall Application Flow

So, we have established that our little application needs five simple JSP pages: one for input, three to represent a potential result of win, lose or tie, and finally, a failure page to handle any errors or problems. But the question is: how do we get from the input page to the results page? I mean, there is a little bit of logic involved in order to decide whether there has been a win or a loss, and of course, we want to see the JSF framework’s neat page navigation features in action, right? Well, here’s how it is all going to work:

The first page the user will touch will have a textfield and a submit button on it. When the user types in a gesture and clicks the submit button, a request will go across the network and subsequently be captured by our application’s JSF framework. Of course, our application is going to need to first figure out what the user chose as their gesture, chose a gesture of its own, and then perform the multi-variable calculus required to figure out if the client won, lost, or tied. Of course, this is application logic, and we will need to code this application logic into a JavaBean. So, we’re going to need to create a JavaBean called the RPSBean (RPS=Rock, Paper, Scissors), and in that bean we will code a method named doRockPaperScissorsGame(). It is inside this method that we will code the required application logic.

The JSF framework will create an instance of the RPSBean for us, it will invoke the doRockPaperScissorsGame() method at the appropriate time for us, and it will take responsibility for figuring out when the Java Virtual Machine’s garbage collector will be able to get it’s greasy little fingers on the JSF created instance of the RPSBean and dispose of it. So, although we’re going to have to code a thing or two into this RPSBean class, the lifecycle of this JavaBean will be managed by the JSF framework. Given this fact, it’s not surprising that in JSF parlance, we call this type of JavaBean a ‘managed bean.’ All JSF managed beans must be described in the faces-config.xml file.

And speaking of the faces-config.xml file, there are a few other salacious entries that we are going to have to make in there if we want our application to work properly. You see, when our doRockPaperScissors() method executes, it must return a String. The String, which for us will simply be the words ‘win’, ‘lose’, ‘tie’ or ‘failure’, map to a navigation-rule from-outcome entry in the faces-config.xml file. The JSF framework then uses the returned String from the doRockPaperScissorsGame() method to figure out which JSP page will be invoked in order to produce a response. When the JSP is invoked, the appropriate markup gets created, and the response is then sent back to the user.

So, in summary, when the client clicks submit, a request is captured by the JSF framework. The JSF framework will look at the request, and not only create in instance of the appropriate JavaBean, but it will also invoke the method needed to implement the required application logic. When the logic is complete, the method will spit out a text String, and based on a corresponding text entry in the faces-config.xml file, the framework will figure out which JSP page will be called upon for generating a response that will get sent back to the client. And that’s it!

***Diagram showing the flow

Dealing with the Logic

So, our application needs some logic. Namely, we need to look at whether the client has gestured ‘rock, paper or scissors’, we need to randomly generate a gesture of our own (actually, the computer will always chose rock for the sake of simplicity, but we can pretend it’s randomly picking ‘Rock’ every time), and we then need to compare the clentGesture with the computerGesture and figure out if the client playing the game has won, lost, or tied.

So, buisiness logic means Java, and coding in Java means creating a Java class. For the Rock Paper Scissors application, I’m going to suggest the creation of a new Java class called RPSBean in a package named com.mcnz.jsf.bean:

package com.mcnz.jsf.bean;

public class RPSBean {

}

Now, this class is going to need to keep track of the gesture the client has made, along with the gesture the computer has made. This sounds like a job that would be perfectly suited for a couple of instance variables. So, I’m going to add two private instance variables of type String named clientGesture and computerGesture:

package com.mcnz.jsf.bean;

public class RPSBean {

private String clientGesture = null;

private String computerGesture = null;

}

Of course, in Java, we don’t like to expose our privates. But we do want to make access to our instance variables possible, so we’re going to need to add the compulsory getters and setters:

package com.mcnz.jsf.bean;

public class RPSBean {

private String clientGesture = null;

private String computerGesture = null;

public String getClientGesture() {return clientGesture;}

public String getComputerGesture() {return computerGesture;}

public void setClientGesture(String cg) {this.clientGesture = cg;}

public void setComputerGesture(String cg) {this.computerGesture = cg;}

}

Now, I know that creating the setters and getters can be tedious, but they are required. If our RPSBean doesn’t have public setters and getters for its properties, the JSF framework won’t be able to work with them! Make sure that all of your private instance variables have public setters and getters.

Of course, our RPSBean is going to be more than just a data holder filled with instance variables. Our RPSBean will also be tasked with performing business logic, and in this case, we’ve got some serious logic to figure out. Not only do we need to figure out the complex algebra needed to implement the Rock Paper Scissors game, but we need to return a text String that tells the JSF framework what to do after the business logic has been processed.

When coding methods inside of a JSF managed bean that is intended to drive page navigation, we typically start the method with the word ‘do’, and the method must return a text String to the JSF framework. The method I’m going to code for this task will be named doRockPaperScissorsGame()

package com.mcnz.jsf.bean;

public class RPSBean {

private String clientGesture = null;

private String computerGesture = null;

public String doRockPaperScissorsGame() {

String result = "failure";

return result;

}

public String getClientGesture() {return clientGesture;}

public void setClientGesture(String cg) {this.clientGesture = cg;}

public String getComputerGesture() {return computerGesture;}

public void setComputerGesture(String cg) {this.computerGesture = cg;}

}

These ‘do’ methods or ‘action’ methods return a String to the JSF framework that ends up being mapped to a JSP page in the faces-config.xml file. It’s common to have a ‘failure’ to deal with any problems that might arise. I always like to start off my do<action> methods by initializing a String named result just to ‘failure’, and then returning this instance named result as the last line of code in the method. The assumption is that the do<action> method will set the result String to a more appropriate value sometime throughout the processing of the method. In this case, more ‘appropriate’ result Strings would be ‘win’, ‘loss’ or ‘draw.’

But before we dive into setting result Strings, we need to initialize the the computerGesture instance variable. For the sake of simplicity, I’m just going to assign the String ‘rock’ to the instance variable named ‘computerGesture.’ I know, it’s lazy, but this book isn’t about randomly generating Strings, it’s about JSF, so simple is how I’m going to keep it!

public String doRockPaperScissorsGame() {

String result = "failure";

this.computerGesture = "rock";

return result;

}

So, with the computerGesture assigned, all we need to do is figure out if the end user playing the game was a win, loss or draw. The code is relatively straight forward, largely helped out by the fact that we assume the computer always chooses rock. So, the logic at play dictates that if the clientGesture is scissors, it’s a loss, if the the clientGesture is paper, it’s a win, and if the clientGesture is rock, it’s a draw. The result String is initialized appropriately based on this logic:

public String doRockPaperScissorsGame() {

String result = "failure";

this.computerGesture = "rock";

if (clientGesture.equalsIgnoreCase("scissors")){

result = "loss";

}

if (clientGesture.equalsIgnoreCase("paper")){

result = "win";

}

if (clientGesture.equalsIgnoreCase("rock")){

result = "draw";

}

return result;

}

So, we have this RPSGame JavaBean with this fancy do<action> method returning various Strings that somehow tells the JSF framework how to facilitate page navigation when the method has completed. The question is, how does this get done?

Well, the key to the page navigation facilities of the JSF framework lies in the faces-config.xml file. Any JavaBean we create that is intended to interact with the JSF framework must be registered in the faces-config.xml file as a ‘managed bean.’

<?xml version="1.0"?>

<!DOCTYPE faces-config PUBLIC

"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"

"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">

<faces-config>

<managed-bean>

<managed-bean-name>rpsbean</managed-bean-name>

<managed-bean-class>com.mcnz.jsf.bean.RPSBean</managed-bean-class>

<managed-bean-scope>session</managed-bean-scope>

</managed-bean>

</faces-config>

The managed bean entry is relatively straight forward. Basically, we give our JavaBean name, rpsbean, which is the name that we must use throughout our application any time we need an instance of the RPSBean. Following the naming of the bean, we specify the fully qualified domain name of the JavaBean, which in this case is com.mcnz.jsf.bean.RPSBean.

Finally, we need to specify a ‘scope’ for the bean. We want to keep the data provided by the user hanging around for as long as the end user is playing out game, so we’re going to take advantage of the session scope.

If we wanted the information to be available only during the current request-response cycle, and then have it purged from memory, we could use the very efficient request scope, and if we wanted data in a JavaBean to be made available to all clients, and have that information survive on the server until the underlying JVM is shut down, we could use the application scope.

Once our RPSBean has been registered in the faces-config.xml file as a managed bean, we can start mapping the various Strings that can be returned from our do<action> method to various navigation rules. Navigation rule entries in the faces-config.xml file are the key to managing page navigation semantics in JSF applications.

So, the textfield that asks for a user to type in either rock paper or scissors is on the landing page of the application, which is named index.jsp. When the user clicks on the submit button on the index.jsp page, the doRockPaperScissorsGame method is invoked, and one of four outcomes is possible: win, loss, draw or failure. Each outcome is associated with a different JSP page that must be invoked in order to generate an HTML view that will be returned to the client. For example, when the String ‘win’ is returned from the doRockPaperScissorsGame method, execution should be forwarded to the win.jsp. We can provide this insight to the JSF framework using the following entry in the faces-config.xml file.

<navigation-rule>

<from-view-id>/index.jsp</from-view-id>

<navigation-case>

<from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>

<from-outcome>win</from-outcome>

<to-view-id>/win.jsp</to-view-id>

</navigation-case>

</navigation-rule>

Of course, we have four possible outcomes, not just one, so we add a navigation case for each outcome that is possible when the doRockPaperScissorsGame method is run.

<?xml version="1.0"?>

<!DOCTYPE faces-config PUBLIC

"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"

"http://java.sun.com/dtd/web-facesconfig_1_0.dtd">

<faces-config>

<managed-bean>

<managed-bean-name>rpsbean</managed-bean-name>

<managed-bean-class>com.mcnz.jsf.bean.RPSBean</managed-bean-class>

<managed-bean-scope>session</managed-bean-scope>

</managed-bean>

<navigation-rule>

<navigation-case>

<from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>

<from-outcome>win</from-outcome>

<to-view-id>/win.jsp</to-view-id>

</navigation-case>

<navigation-case>

<from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>

<from-outcome>loss</from-outcome>

<to-view-id>/lose.jsp</to-view-id>

</navigation-case>

<navigation-case>

<from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>

<from-outcome>draw</from-outcome>

<to-view-id>/tie.jsp</to-view-id>

</navigation-case>

<navigation-case>

<from-action>#{rpsbean.doRockPaperScissorsGame}</from-action>

<from-outcome>failure</from-outcome>

<to-view-id>/failure.jsp</to-view-id>

</navigation-case>

</navigation-rule>

</faces-config>

Of course, this whole exercise of writing JavaBeans and editing xml files is all academic if we don’t have actual web pages that tie the whole thing together. I mean, we have an action method coded, and our JavaBean is registered as a JSF managed bean with a bunch of navigation rules associated with it, but we need some web pages to tie this whole thing together. We’ll start by creating the landing page, the first page the client sees when they use our application. We’ll name the landing page index.jsp, and it will be a fairly simple page with textfield, a submit button, and a prompt telling the user what do to.

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<f:view>

<body>

Please chose between Rock Paper and Scissors:

<h:form id="rpsgameform">

<h:inputText value="#{rpsbean.clientGesture}" />

<h:commandButton action="#{rpsbean.doRockPaperScissorsGame}" value="Play!" />

</h:form>

</body>

</f:view>

</html>

First of all, you should recognize all of the standard JSF taglib directives and standard tags such as f:view and h:form from earlier chapters. There’s nothing too new with regards to the standard tags being used in this JSF page. However, what is interesting is how a few of these JSF tags are being used, namely the value and action attributes of the inputText and commandButton tags.

When the user clicks the submit button, we want the doRockPaperScissorsGame method to be invoked. Recalling that the RPSBean is mapped in the faces-config.xml file with the name rpsbean, in all lower case letters, to have the doRockPaperScissorsGame method invoked when the commandButton is clicked, we simply use a special JSF expression language syntax to assign a value to the h:commandButton’s action attribute:

<h:commandButton action="#{rpsbean.doRockPaperScissorsGame}" value="Play!" />

Of course, when the doRockPaperScissorsGame method is executed, we want to know what the user has typed into the inputText field. By again, using JSF expression language, we link what the client types into the inputText field to the clientGesture property of the RPSBean.

<h:inputText value="#{rpsbean.clientGesture}" />

So, when the client clicks on the submit button, not only is the doRockPaperScissorsGame method invoked, but prior to the method running, the clientGesture variable of the RPSBean is initialized to whatever the client has typed into the textfield. No extra steps need to be taken to take the user’s input and bring it into our JSF application – the JSF framework does this all for us.

And when the doRockPaperScissorsGame method runs, one of four JSPs will be selected for the job of view generation.

I’m anxious to just get this whole Rock, Paper, Scissors application running, so I’m going to keep the win.jsp, lose.jsp, tie.jsp and failure.jsp pages pretty simple. And just so you know, the win.jsp, lose.jsp, tie.jsp and failure.jsp will all reside alongside the index.jsp page in the root directory of the web application.

Here’s the win.jsp:

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>You Win!</title></head>

<f:view>

<body>

<p>I picked rock. You win!</p>

</body>

</f:view>

</html>

As you can see, everything is hard-coded, and there’s not much there more than your standard JSF taglib declarations, a simple f:view tag, and just your average, every day HTML tags that spit out a little message telling the user they have won. The lose.jsp and tie.jsp pages will be exactly the same, while being just a bit different. J

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>You Lost!</title></head>

<f:view>

<body>

<p>I picked rock. You lose!</p>

</body>

</f:view>

</html>

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>A Draw!</title></head>

<f:view>

<body>

<p>I picked rock. We tied!</p>

</body>

</f:view>

</html>

Finally, the failure.jsp page needs to be created. Again, we’re just going to provide a simple message letting the end user know that something went wrong:

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>Failure</title></head>

<f:view>

<body>

<p>There was a problem. Please try again</p>

</body>

</f:view>

</html>

Well, with the last of the JSPs coded, we are ready to deploy and test our JSF application.

Running and Testing the Application

When we run and deploy the application, we end up with a very handsome little application that plays the standard Rock Paper and Scissors game. Seeing the application in action, you get a good feel for what is happening under the covers.

When the submit button is clicked, a request is sent to our application, and captured by the JSF framework.

clip_image001

clip_image002

clip_image003

clip_image004clip_image003[1]clip_image003[2]clip_image003[3]

clip_image006

clip_image005

There isn’t too much magic on this page. The required taglib directives decorate the top of the page, we have the standard form tag which then wraps both the h:inputText and the h:commandButton tags.

<h:form id="rpsgameform" >
<h:inputText id="gesture" value= ”#{rpsbean.clientGesture}” > </h:inputText>
<h:commandButton type="submit" value="Play!"

action="#{rpsbean.doRockPaperScissorsGame}" ></h:commandButton>

</h:form>

The first thing to notice here is the value attribute of the inputText tag. We need to be able to take whatever the client types into the textfield and have that transferred to the server, where we can process it. The ”#{rpsbean.clientGesture}” entry for the value attribute tells the JSF framework that whatever is typed into this textfield should be transferred to a property named clientGesture in a JavaBean that is running on the server that is named rpsbean.

The second thing that needs to be pointed out here is the action attribute of the h:commandButton tag. Notice how the action attribute is set to "#{rpsbean.doRockPaperScissorsGame}"

The hash code sign, #, is a signal that tells the JSF framework that some JSF-specific processing is required. In this case, the JSF framework recognizes the fact that any time a submit button is clicked, processing logic is required, and in this case, the JSF framework will invoke the doRockPaperScissorsGame method of the rpsbean.

Another thing worth pointing out here are the id attributes that have been assigned to the form and inputText elements. JSF links elements and sub-elements according to their names or ids, in a ancestor:parent:child type of syntax. So, when we do processing and try to figure out what a user typed into the textbox, we can identify the inputText field with the id of gesture, inside the form named rpsgame, with the name rpsgame:gesture.

The syntax used here to specify the value of the action attribute is known as JSF expression language, and while the result of using this syntax will be to have the JSF framework invoke a method on a JavaBean, it is worth nothing that the syntax we see here is not a Java syntax. JSF expression langugage is intended to look and feel more like a scripting language, helping to keep JSP pages look cleaner, be free from actual Java code, and subsequently making JSPs easier to write and maintain.

So, our h:inputText tag is looking for a JavaBean named rpsbean so, it would probably be prudent to create such a JavaBean that will fill this need.

The basic outline of the JavaBean will look like this:

package com.mcnz.jsf.bean;

import javax.faces.context.*;

public class RPSBean {
}
}

I’ve placed the bean in a package named com.mcnz.jsf.bean, I have been generous to myself and imported javafaces.context.*, and I have created a simple class named RPSBean. When you create your own class, make sure the RPSB is all capitalized – case is important!

Now, after coding the class declaration, the next thing you’ll want to think about are any instance variables the class might need. Our little RPSBean will probably need to keep track of the client gesture, and the computer’s gesture, so making two String variables, one named computerGesture and the other named clientGesture, probably wouldn’t be such a bad idea.

Now, one thing to note about methods called from the action attribute of a custom tag is the fact that those methods must return a text String.

The text String is supposed to provide the JSF framework some type of guidance as to how to mitigate page navigation, so in our case, we will have four possibilities, the Strings: “failure”, “win”, “lose” and “tie”.

It’s always a good habit to start off your do<action> method by explicitly setting a String named result to a valid value, which in this case we set to failure, and then specifying what will be the last line of code in the method, return result;

package com.mcnz.jsf.bean;

import javax.faces.context.FacesContext;

public class RPSBean {
public String doRockPaperScissorsGame() {
String result = "failure";
/*Method implementation logic will go here. */
return result;
}

}

Of course, we need to keep track of what the client selected, and what the computer has selected, so we’ll add two instance variables of type String to our RPSBean. We will add the setters and getters as well.

The first iteration of our Rock-Paper-Scissors game looks good, but there’s a great deal of room for improvement. One of the first places I’d like to improve our application is on the results pages where we tell the use the result of the game. Right now, we just say “I picked Rock, you lose” or “I picked Rock, you win” but none of the output is dynamic. It would be nice to create some text output dynamically, so that the output of the page can change and adapt, depending upon how a client or the computer chooses a rock-paper-scissors gesture.

Our RPSBean maintains two instance level variables, clientGesture and computerGesture. What would really be nice is if we could use these two instance variables in the output generated in the results win, lose and draw JSPs. So that if the client picks rock, and the computer pics scissors, we can dynamically output: You picked rock. I picked scissors. You win!

Well, wouldn’t you know it that the JSF framework provides two custom tags that work together to create exactly this type of output.

Currently, when the user clicks on the submit button of our form, the gesture the text has typed into the input field gets assigned to the clientGesture property defined as an instance variable in the RPSBean. After the clientGesture property is initialized, our doRockPaperScissorsGame method is invoked, and we randomly assign a value to the instance variable named computerGesture. From there, the results of the game are evaluated, and if all goes according to plan, either the win.jsp, lose.jsp or tie.jsp gets invoked for view generation.

Of course, during view generation, the RPSBean is still available to us to play around with. So, since the clientGesture and the computerGesture properties are already initialized by the time we have forwarded to the JSP, we can simply use an outputText tag and some expression language to display a more dynamic response. Take a look at the improved lose.jsp

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>You Lost!</title></head>

<f:view>

<body>

<p>I picked <h:outputText value="#{rpsbean.computerGesture}" />.

<p>You picked <h:outputText value="#{rpsbean.clientGesture}" />.

<p>You lose!</p>

</body>

</f:view>

</html>

Since the computerGesture and clientGesture properties are already initialized, we can simply assign these initialized properties of the rpsbean to the value attribute of the outputText tag.

Now we can actually simplify our JSPs just a little bit. In the tie.jsp, rather than having some literal text followed by the outputText tag, I’m going to combine the literal text with the expression language reference to the client and computer gestures right there inside of the value attribute of the outputText tag:

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>A Draw!</title></head>

<f:view>

<body>

<p> <h:outputText value="I picked #{rpsbean.computerGesture}". />

<p> <h:outputText value="You picked #{rpsbean.clientGesture}". />

<p> It's a draw! </p>

</body>

</f:view>

</html>

As you can see, an expression can be combined with literal text in the value attribute of a JSF tag to simplify the task of generating output for the client.

Finally, an even easier way to generate out dynamic output in this instance is to use the outputFormat tag from the JSF HTML library, along with the param tag from the JSF core. Here’s how it looks:

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>win</title></head>

<f:view>

<body>

<h:outputFormat value="I picked {0}. You picked {1}. You win!">

<f:param value="#{rpsbean.computerGesture}" />

<f:param value="#{rpsbean.clientGesture}" />

</h:outputFormat>

</body>

</f:view>

</html>

As you can see, with the outputFormat tag, we provide a text String to the value attribute, while placeholders for dynamic content are included as incremented numbers, starting at zero, surrounded by braces, { }. Then for each set of braces, a param tag is included in the body of the outputFormat tags. In this case, the first placeholder, {0}, needs to be replaced at runtime with the value of the computerGesture property, as per the value attribute of the first param tag. The second placeholder, {1}, will be replaced by the value of the clientGesture property. When the code runs, the output looks something like this:

I picked Paper. You picked rock. You win!

Working with Links

After playing our Rock Paper Scissors game, it would be nice to provide a link that would take the user back to the landing page so they could play the game again. To provide such functionality, JSF provides two tags with similar functionality: the commandLink tag, and the outputLink tag.

The outputLink tag is really just a standard, run of the mill anchor tag.

To invoke our landing page, which is implemented through the index.jsp file, all we need to do is type http://localhost:<?port?>/index.faces into the address bar of our browser. When the JSF framework sees the request for index.faces, it knows to look for a corresponding JavaServer Page named index.jsp.

So, to use an outputLink in an effort to generate a link back to our landing page, all we need to do is use the outputLink tag in the following fashion:

<h:outputLink value="http://localhost:9080/index.faces">

<h:outputText value="Play Again" />

</h:outputLink>

Now there are a couple of things to point out about this tag combination. First of all, in order for there to be some type of text for the user to click on to trigger the link, we need to nest an outputText tag between the open and closing outputLink tags. Here we just use the text “Play Again”.

The next thing to notice is the URL specified in the value. Here I used a fully qualified URL, and a port of 9080. Depending upon your own environment, your test server might be 8080, 8081, or even just 80. That’s something you’ll need to figure out on your own.

Of course, since we’re invoking a local resource, a relative URL would be fine as well.

<h:outputLink value="index.faces" >

<h:outputText value="Play Again" />

</h:outputLink>

Now, you’ll be pretty disappointed to discover that all of this work spits out little more than a normal anchor tag, that you could have probably written yourself:

<a href="index.faces">Play Again</a>

Of course, looking at the tag created by the outputLink tag, it makes one wonder what the point of using it at all is? Well, for purely generating link tags, it’s a bit of work. One of the nice features of the outputLink tag is the fact that you can use the JSF core param tag to add name value pairs to the URL. These name value pairs can be processed by any standard web based application, be it a JSP, Servler, CGI script, or .NET program.

<h:outputLink value="http://localhost:9080/NameAgeServlet/">

<f:param name="name" value="Cameron"></f:param>

<f:param name="age" value="36"></f:param>

<h:outputText value="Play Again" />

</h:outputLink>

The above set of JSF tags creates the following output in an HTML page:

<a href="http://localhost:9080/NameAgeServlet/?name=Cameron&age=36">

Play Again

</a>

One thing to notice is that I used the name of a non-existent Servlet, NameAgeServlet, as the resource accepting this request. The reason I did this was to emphasize the fact that passing arguments this way is not a recommended practice when using JSF.

The Problem With Param Tags

When we write JSF applications, we use backing beans, and we like to handle page navigation and business logic through action methods. In order for an action method to be invoked, and for input values to be bound to a backing bean, the tag must be nested within a form tag. Notice that the outputLink tag does not need to be wrapped within a form tag? Due to that fact, navigations prompted from outputLink tags do not invoke actions, and subsequently, values passed from page to page using the f:param tag are not bound to instance variables in backing beans, even if the value attribute of the param tag is initialized using JSF expression language.

So, simple navigation is okay with outputLink tags, and when invoking an external resource, like a Servlet or CGI script that needs a variety of parameters passed in as well, the outputLink tag is perfect. But, when you want page navigation to be subject to to action events and value bindings to managed beans, you will want to use the commandLink tag instead.

It should also be mentioned that this strategy of invoking the index.jsp file will only work if it’s in a publicly accessible folder, such as the root folder of the war file, which is where the index.jsp file currently resides. If the application is secured, and the index.jsp file is moved under the WEB-INF directory, direct invocations like this will fail, and you’re better off using a commandLink which can leverage the page navigation facilities of the faces-config.xml file.

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<head><title>You Lost!</title></head>

<f:view>

<body>

<p>I picked <h:outputText value="#{rpsbean.computerGesture}" />.

<p>You picked <h:outputText value="#{rpsbean.clientGesture}" />.

<p>You lose!</p>

<h:outputLink value="http://localhost:9080/NameAgeServlet/">

<f:param name="name" value="Cameron"></f:param>

<f:param name="age" value="36"></f:param>

<h:outputText value="Play Again" />

</h:outputLink>

</body>

</f:view>

</html>

An alternative to the outputLink tag for generating HTML anchor links is the commandLink tag. Now, the big thing about the command link, as the name implies, is that this tag generates a link that can trigger a form submission in the exact same way a commandButton. So, unlike the outputLink tag, a commandLink must be contained with JSF form tags. But, since a commandLink will behave like a command button, a commandLink can trigger an action, and correspondingly, it triggers the same basic JSF framework that links form input elements to backing beans. So, when a commandLink is triggered, we can expect the same types of JSF events to be triggered as we see with a commandButton.

Now, it should also be noted that since a commandLink triggers a JSF action, we must use the navigation model employed by the JSF framework. Of course, the link on the win.jsp page that we want to code simply take the user back to the index.jsp landing page, so we really don’t want to have any complicated methods involved. So, all we need to do is add a navigation rule to our faces-config.xml file, and specify directly the value of the from-outcome element directly in our commandLink tag. Here’s how the faces-config.xml file entry will look as we use the text ‘playAgain’ to indicate to the navigation model that we want to be taken back to the index.jsp page.

<navigation-rule>

<from-view-id>*</from-view-id>

<navigation-case>

<from-outcome>playAgain</from-outcome>

<to-view-id>/index.jsp</to-view-id>

</navigation-case>

</navigation-rule>

Also notice the * in the from-view-id element. This means any page can use this particular navigation rule, so if we wanted to reference this navigation case in the tie, win, lose and failure.jsp, there would be no need to create duplicate navigation-case mappings.

<h:form>

<h:commandLink value="Play Again..." action="playAgain"/>

</h:form>

The commandLink is a bit easier to use than the outputLink tag, although you do have to ensure the commandLink is nested within a form tag, otherwise you’ll get an exception that looks like this:

Exception thrown : javax.faces.FacesException: Assertion Failed at com.sun.faces.util.Util.doAssert(Util.java:1353)at com.sun.faces.renderkit.html_basic.CommandLinkRenderer.encodeBegin(CommandLinkRenderer.java:200)Resources rolled back due to setRollbackOnly()

Faces Servlet. Exception thrown : javax.servlet.ServletException: Assertion Failed

Exception thrown : javax.servlet.ServletException: BodyContent is null for tag with handler class: 'com.sun.faces.taglib.html_basic.CommandLinkTag'. At org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:660)

javax.servlet.jsp.JspException: BodyContent is null for tag with handler class: 'com.sun.faces.taglib.html_basic.CommandLinkTag'. at com.sun.faces.taglib.html_basic.CommandLinkTag.doEndTag(CommandLinkTag.java:664) at com.ibm._jsp._win._jspx_meth_h_commandLink_0(_win.java:160)

And while this example uses a direct reference to the from-outcome of the navigation case, it is completely valid to reference a do<action> method in a backing bean. In fact, we could re-write our index.jsp to use a commandLink rather than a commandButton:

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<f:view>

<body>

<h:outputText value="Please chose between Rock, Paper, and Scissors:"/>

<h:form id="rpsgameform">

<h:inputText id="gesture" value="#{rpsbean.clientGesture}" />

<!-- h:commandButton id="submit" action="#{rpsbean.doRockPaperScissorsGame}" value="Play!" /-->

<h:commandLink id="submit" action="#{rpsbean.doRockPaperScissorsGame}" value="Play">

</h:commandLink>

</h:form>

</body>

</f:view>

</html>

Notice how the commandButton tag has been commented out, and it has been replaced by the commandLink tag. The attributes for the two tags are identical, emphasizing their similar nature. The only real difference is the fact that one renders a link, and the other renders a button.

Clickable Images

One way we might improve our rock-paper-scissors game is to eliminate the need for a user to actually type text into the input field, and instead, just have the user click on an image representing one of the three possible choices. In order to do this, we’ll need to coordinate three JSF tags, namely the commandLink tag, graphicImage tag, and the param tag.

Of course, before we start adding commandLink tags and graphic images, we should probably just comment out the inputText tag, as we’re not planning on using it during this iteration of the landing page.

<!--h:inputText id="gesture" value="#{rpsbean.clientGesture}" /-->

The graphicImage tag from the JSF HTML tag library is relatively straight forward. In its simplest form, we just place the tag on a JSF page, and set the value attribute to the name and location of an image file, with the path of the image being relative to the root of the war file.

<h:graphicImage value="rock.gif" />

In this case, the rock.gif file would be located right there in the root of my war file.

Of course, we want a clickable image that triggers the execution of our doRockPaperScissorsGame method. To achieve this, we simply wrap the graphicImage tag with the commandLink tag, keeping in mind the fact that the commandLink tag needs to be embedded within a form tag at some point.

<h:form id="rpsgameform">

"""

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}">

<h:graphicImage value="rock.gif"/>

</h:commandLink>

"""

</h:form>

Now, the problem with using three links is the fact that we can’t easily link a value from the commandLink URL to the clientGesture property of the backing bean, as we did with the inputText field

<h:inputText id="gesture" value="#{rpsbean.clientGesture}" />

So, instead of using a sweet combination of the value attribute and expression language, we’re going to use the JSF core param tag to pass a name-value pair to the server when a link is clicked. So, when the user clicks on a graphic image of a rock, a name-value pair of gesture=ROCK will be delivered to the server.

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}" >

<h:graphicImage value="rock.gif" />

<f:param name="gesture" value="ROCK" />

</h:commandLink>

<BR/>

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}" >

<h:graphicImage value="rock.gif" />

<f:param name="gesture" value="PAPER"/>

</h:commandLink>

<BR/>

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}">

<h:graphicImage value="rock.gif" />

<f:param name="gesture" value="SCISSORS" />

</h:commandLink>

<BR/>

Earlier on in this book, I spoke about my dislike for the param tag, and although I am using it here, don’t take that as a sign that I have somehow become soft on my stance.

A big problem with the param tag when used like this is that it bypasses the whole process of linking an input value from a web page to the property of a backing bean. With our inputText tag, we were able to very easily link whatever a luser typed into a textfield with the clientGesture property of our RPSBean. We can’t do that with the param tag, and instead, must manually dig the value of the gesture our of the HTTP request object, and that’s messy. Furthermore, the name we use to dig the value out of the HTTP request map must match exactly in case and spelling to the name used in the param tag, which in this case is the word “gesture”. In my opinion, that’s a pretty tight linking between a visual component and a model component, and that type of linking, which is not checked and verified by the compiler, can be very difficult to troubleshoot when it causes a problem. And finally, because we are going to pull the value of the param tag out of the HTTP request map in our do<Action> method, we’re going to lose out on any conversion, validation or error checking that the JSF framework is apt to do for us.

Whenever a request comes into the JSF, the framework generates a special collection class of type Map that maintains a listing of any and all name-value parameters that came in as part of the request URL.

java.util.Map requestParameterMap = null;

Of course, getting this requestParameterMap is a moderately intimidating method call, as you need to dig deep into the ExternalContext of the FacesContext associated with the current request-response cycle.

requestParameterMap = javax.faces.context.FacesContext.

getCurrentInstance().

getExternalContext().

getRequestParameterMap();

***CAREFUL: There is a method called getRequestMap() which is different from the getRequestParameterMap() which we are using here. Make sure you have coded a call to the correct method of the ExternalContext!

Don’t let the FacesContext intimidate you. Basically, it’s created by the JSF framework any time a new request comes into the server, and it is cleaned up when a response is released back to the client. You can easily gain access to the FacesContext by calling the getCurrentInstance() method of the FacesContext in any method that is being run within your JSF application.

“FacesContext contains all of the per-request state information related to the processing of a single JavaServer Faces request, and the rendering of the corresponding response.”

The ExternalContext that we dig up from the current instance of the FacesContext is the core class that gives us access to the RequestParameterMap and other classes with the real information we want about the request-response cycle. While it might seem like needless indirection to us right now, the purpose of the ExternalContext class is to provide a core class for interacting with the request-response cycle, while abstracting out details about the current environment. For example, a Servlet envionment will have the underlying ExternalContext class implemented in a slightly different way than a Portlet enivornment’s ExternalContext class. Of course, as developers, the difference isn’t important to us, because the methods of the class remain the same. This class basically allows our application to be unaware of the actual environment in which it runs.

“This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment.”

With the requestParameterMap obtained, we can discover which image was clicked by getting the value associated with the name of the param associated with the surrounding commandLink.

this.clientGesture = (String)requestParameterMap.get("gesture");

An important point to notice here is that we are not only extracting the value of the gesture associated with the image that was clicked, but we are also directly assigning this value to the clientGesture property so that the remaining business logic in our method can run properly. This type of assignment was not necessary in earlier iterations, as the JSF framework used the value of the text field we were using to the clientGesture property of our backing bean.

You should also notice how the String used to extract the value from the parameterMap matches in both spelling and case the name attribute used in the param tag:

<f:param name="gesture" value="PAPER"/>

Notice how the String used to extract the value from the parameterMap matches in both spelling and case the name attribute used in the param tag.

By the way, using the requestParameterMap to obtain information about form data being submitted to the server is not unique to the param attribute. Any form data that gets sent to the server is delivered as name-value pair Strings, be it information in a textfield, or the name of a button that was clicked when a form was submitted. However, the challenge with JSF is knowing the name that was used when the form data was sent to the server.

Take a look at our original rock-paper-scissors form:

<h:form id="rpsgameform">

<h:inputText id="gesture" value="#{rpsbean.clientGesture}" />

<h:commandButton id="submit"

action="#{rpsbean.doRockPaperScissorsGame}" value="Play!" />

</h:form>

If someone typed “Rock” into the inputText element of the rpsgameform, we could easily extract that data using the requestParameterMap. However, the first temptation is typically to make a call such as:

this.clientGesture = (String)requestParameterMap.get("gesture");

In this case, the developer uses the actual id property of the inputText custom tag to extract the data associated with the inputText field. Unfortuntely, this simple approach will fail, due the the way JSF assigns ids to fields at runtime.

If an element is named, and that element contains sub-elements, then the names of the sub-elements are daisy chained together with a colon acting as a delimiter. So, with our rpsgameform, the form itself, which is not ‘contained’ by any other element that is assigned an id, will simply use the name rpsgameform as its name in its name value pair.

If we looked at the HTML code generated by our h:form tag, it would look like this:

<form id="rpsgameform" method="post" action="/JSFBookWeb/index.faces" enctype="application/x-www-form-urlencoded">

However, the inputText field assigned the id ‘gesture’ is nested within the form tag, so the actual name JSF assigns this textfield at runtime is not simply ‘gesture’, but is instead, rpsgameform:gesture. Similarly, the button is assigned the name rpsgameform:submit.

<form id="rpsgameform" method="post" action="/JSFBookWeb/index.faces" enctype="application/x-www-form-urlencoded">

<input id="rpsgameform:gesture" type="text" name="rpsgameform:gesture" />

<input id="rpsgameform:submit" type="submit" name="rpsgameform:submit" value="Play!" />

<input type="hidden" name="rpsgameform" value="rpsgameform" />

</form>

(Note that to facilitate internal processing, JSF also adds a hidden input field that is assigned the name of the form. This is to identify the form submitting the input data to the server, as the actual <form> tag does not send anything about itself to the sever.)

So, with the knowledge of how JSF is naming our input fields, we can find out what a user has typed into our textfield with the following line of code:

this.clientGesture = (String)requestParameterMap.get("rpsgameform:gesture");

Similarly, we can find out if the end user has clicked on our submit button by checking to see if the following line of code returns a non-null value:

String button = (String)requestParameterMap.get("rpsgameform:submit ");

And in fact, this process is extremely similar to how we typically did form handling in Servlet and JSP applications. When coding directly against the Servlet API, to extract form data, we simply used the HttpServletRequest object and called the getParameter(String param) method, proving the name of the inputfield for which we were interested. The only major difference here is that the ExternalContext class provides a level of indirection, hiding direct access to the HttpServletRequest class, although that is exactly what is happening under the covers.

Of course, I want to emphasize that I am not recommending this approach to extracting form data from your clients. Doing this type of direct access to form elements not only skips some of the most important aspects of the JSF framework, such as value binding, conversion and input validation, but it also creates a logic layer that is bound very tightly to names of fields used in the view layer. This is not an optimal approach, and should only be used when it strategically makes sense – which will be a very small percentage of time.

****************Not Working As Planned *************************

So, as you can tell, I’m not a huge fan of grabbing form attributes directly out of the ExternalConext’s requestParameterMap. I hate the tight linking between the text used to name the input field in the form, and the matching of that name to the text String used to extract that data in the managed bean. I much prefer to use expression language in my JSPs and have the JSF framework loosely link input elements in forms to associated properties in managed beans. But unfortunately, with the param tag, such a linking wasn’t possible using the value attribute.

Well, one neat aspect that we haven’t looked at yet is the binding property of a cutom tag.

Every custom tag we use in our JSF pages has a corresponding Java class implementation that makes the custom tag work. So, for our h:form tag, there is a corresponding HtmlForm class in the javax.faces.component.html package. For the h:outputLink tag, there is a corresponding HtmlOutputLink class. For the h:inputText tag, there is a corresponding HtmlInputText tag. For every custom tag we use, there is always a corresponding Java class implementation somewhere in the JSF API.

When the JSF framework generates an HTML page, it actually creates instances of each of the Java classes that correspond to the various JSF custom tags on a page. During this ‘encoding’ process, attributes that are specified in the custom tag are appropriately applied to these Java class implementations, and then finally, after a little razzle-dazzle on the server, each Java class is asked to essentially convert itself to HTML that gets sent back to the client as a web page.

When a JSF form is submitted, a similar process takes place again, with each element on a form that gets submitted being converted by the JSF framework into corresponding Java classes that contain all and any of the extra information that may have been submitted back to the server.

So, when a form is submitted to the server, the JSF framework creates an instance of a Java class corresponding to each element of the submitted form. Any time we want to take advantage of this process, and grab onto one of the instances the JSF framework has already created, all we need to do is declare an instance of the corresponding class in our managed bean, create the appropriate setters and getters, and then use expression language in the binding attribute of the custom tag in the JSP to link the given tag to the instance in our managed bean. This is all getting rather complicated in it’s explanation, so lets look at some code.

Let’s just say that I didn’t want to use the ExternalContext’s getRequestParameterMap to extract a param attribute associated with a commandLink. I could just declare an instance of the UIParameter class in my managed bean.

package com.mcnz.jsf.bean;

import javax.faces.component.*;

public class RPSBean {

private String clientGesture = null;

private String computerGesture = null;

private javax.faces.component.UIParameter parameter = null;

public UIParameter getParameter() {return parameter;}

public void setParameter(UIParameter parameter) {

this.parameter = parameter;

}

""" """

}

With the UIParameter instance declared in the managed bean, we can then use expression language to bind the f:param tags in our JSP page directly to this UIParameter instance:

<h:form id="rpsgameform00">

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}" >

<h:graphicImage value="rock.gif" ></h:graphicImage>

<f:param name="gesture" value="ROCK" binding="#{rpsbean.parameter}" />

</h:commandLink>

</h:form>

The only caveat here is that each link will need to be in separate form, with each form having its own name, rpsgameform00, rpsgameform01 and rpsgameform02. This reality elutes from the fact that we can’t have three different tags binding to the same property in a backing bean. If we attempt to do this, only the last binding in the file usually gets bound to the backing bean, although this behavior itself isn’t completely predictable, further emphasizing that it is not an proper practice.

<h:form id="rpsgameform00">

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}" >

<h:graphicImage value="rock.gif" ></h:graphicImage>

<f:param name="gesture" value="ROCK" binding="#{rpsbean.parameter}" />

</h:commandLink>

</h:form>

<BR/>

<h:form id="rpsgameform01">

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}" >

<h:graphicImage value="rock.gif" ></h:graphicImage>

<f:param name="gesture" value="PAPER" binding="#{rpsbean.parameter}" />

</h:commandLink>

</h:form>

<BR/>

<h:form id="rpsgameform02">

<h:commandLink action="#{rpsbean.doRockPaperScissorsGame}">

<h:graphicImage value="rock.gif" />

<f:param name="gesture" value="SCISSORS" binding="#{rpsbean.parameter}" />

</h:commandLink>

</h:form>

And now, with these bindings in place, we can actually extract information about which link was clicked simply by asking the instance of the UIParameter, which we uncreatively named ‘parameter’ in the managed bean, about it’s value:

this.clientGesture = (String)parameter.getValue();

***One thing to note is that a when using a binding, you must bind the tag to a corresponding class that provides an implementation of that class. You cannot simply use the binding attribute to link a tag to a String or a Long, or some other datatype that does not correspond to the tag.

When a JSF form is submitted, a similar process takes place again, with each element on a form that gets submitted being converted by the JSF framework into corresponding Java classes that contain all and any of the extra information that may have been submitted back to the server.

**************** Not Working As Planned *************************


package com.mcnz.jsf.bean;

import javax.faces.component.*;

import javax.faces.component.html.*;

public class RPSBean {

private String clientGesture = null;

private String computerGesture = null;

public String doRockPaperScissorsGame() {

String result = "failure";

java.util.Map requestParameterMap = null;

requestParameterMap = javax.faces.context.FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

this.clientGesture = (String)requestParameterMap.get("gesture");

this.computerGesture = "rock";

try {

if (clientGesture.equalsIgnoreCase("scissors")){

result = "loss";

}

if (clientGesture.equalsIgnoreCase("paper")){

result = "win";

}

if (clientGesture.equalsIgnoreCase("rock")){

result = "draw";

}

} catch (RuntimeException e) {

System.out.println("Excetion");

}

return result;

}

public String getClientGesture() {return clientGesture;}

public void setClientGesture(String cg) {this.clientGesture = cg;}

public String getComputerGesture() {return computerGesture;}

public void setComputerGesture(String cg) {this.computerGesture = cg;}

}


Having originally designed our user interface to use a textfield, and then redesigned it to use clickable images, we may as well do another couple of quick redesigns to demonstrate a few of the other kewl options JSF provides for making a single choice when given a list of different options. Namely, we’ll look at the selectOneListbox, selectOneMenu and the selectOneRadio.

The selectOneListbox, selectOneMenu and selectOneRadio all work in a very similar fashion, although they generate markedly different displays. They key to these JSF custom tags is the JSF core tag named selectItem which defines the various items that are intended to be displayed for selection. There are really two pivotally important properties that need to be specified for the selectItem tag: itemLabel and itemValue. The itemLabel attribute of the selectItem tag specifies the text that gets displayed to the user on the web page, and the itemValue attribute defines the text String that gets sent to the server if the item is actually selected.

Here’s how the basic selectOne JSF tags would look if stuffed with five selectItem objects. Notice how we’ve added in two new options – spock and lizard.

<h:selectOneListbox id="selectOneListBoxGesture" value="rock" >

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="Paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

<f:selectItem itemValue="spock" itemLabel="Spock" itemDisabled="true" />

<f:selectItem itemValue="lizard" itemLabel="Lizard" itemDisabled="true" />

</h:selectOneListbox>

<h:selectOneMenu id="selectOneMenu" value="paper" >

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="Paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

<f:selectItem itemValue="spock" itemLabel="Spock" itemDisabled="true" />

<f:selectItem itemValue="lizard" itemLabel="Lizard" itemDisabled="true" />

</h:selectOneMenu>

<h:selectOneRadio id="selectOneRadio" value="scissors" >

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="Paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

<f:selectItem itemValue="spock" itemLabel="Spock" itemDisabled="true" />

<f:selectItem itemValue="lizard" itemLabel="Lizard" itemDisabled="true" />

</h:selectOneRadio>

With each of the selectOne tags, you can use the value tag to specify which of the various selectItems should be initially selected when the element displays.

Updating our web page to use a listbox that initially has the rock option selected would look like this:

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<f:view>

<body>

<h:outputText value="Please chose between Rock, Paper, and Scissors:"/>

<h:form id="rpsgameform">

<h:selectOneListbox id="selectOneListBoxGesture"

value="#{rpsbean.clientGesture}" >

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="Paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

<f:selectItem itemValue="spock" itemLabel="Spock" itemDisabled="true" />

<f:selectItem itemValue="lizard" itemLabel="Lizard" itemDisabled="true" />

</h:selectOneListbox>

<h:commandButton id="submit" type="submit" value="Play!" action="#{rpsbean.doRockPaperScissorsGame}" />

</h:form>

</body>

</f:view>

</html>

Notice how the value of the selectOneListbox is bound to the clientGesture property of the RPSBean. With this binding, the itemValue of the chosen selectItem will be used to update the clientGesture property. Unfortunately, the value property is also the property used to set an initially selected value in the list of selectItems. Since our RPSBean does not have a default value for the clientGesture, by default, no property in the list will be selected. Alternatively, if we initialized clientGesture to “paper” when the property is initially declared, we would effectively be making “paper” the default choice when the list is first displayed.

The selectOneMenu is almost identical to the selectOneListbox, with the primary difference being of course the name of the tag, and the component that gets generated when viewed on a web page.

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<f:view>

<body>

<h:outputText value="Please chose between Rock, Paper, and Scissors:"/>

<h:form id="rpsgameform">

<h:selectOneMenu id="selectOneMenuGesture" value="#{rpsbean.clientGesture}" >

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="Paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

<f:selectItem itemValue="spock" itemLabel="Spock" itemDisabled="true" />

<f:selectItem itemValue="lizard" itemLabel="Lizard" itemDisabled="true" />

</h:selectOneMenu>

<h:commandButton id="submit" type="submit" value="Play!" action="#{rpsbean.doRockPaperScissorsGame}" />

</h:form>

</body>

</f:view>

</html>

And just to keep things as uninteresting as possible, you’ll notice that the selectOneRadio tag is practically identical to the other selectOne tags, with the exception being the name of the tag, and the manner in which the component is presented to the user.

Of course, one extra little attribute that the selectOneRadio has that the other tags do not have is the layout attribute, which can take on one of two values: lineDirection (which is the default) and pageDirection.

When the layout is set to lineDirection, the radio buttons are laid out horizontally from left to right. When the layout is set to pageDirection, the radio buttons are laid out vertically from top to bottom.

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<f:view>

<body>

<h:outputText value="Please chose between Rock, Paper, and Scissors:"/>

<h:form id="rpsgameform">

<h:selectOneRadio id="selectOneRadioGesture" value="#{rpsbean.clientGesture}" layout="lineDirection">

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="Paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

<f:selectItem itemValue="spock" itemLabel="Spock" itemDisabled="true" />

<f:selectItem itemValue="lizard" itemLabel="Lizard" itemDisabled="true" />

</h:selectOneRadio>

<h:commandButton id="submit" type="submit" value="Play!"

action="#{rpsbean.doRockPaperScissorsGame}" />

</h:form>

</body>

</f:view>

</html>


Hardcoding the various SelectItem for a given selectOneListbox or selectOneRadio is a fun thing to do when learning JSF, but more likely than not, the various options that are available for a given user to select are likely pulled from a database, and if their exact number and values is uncertain, you can’t simply can’t hardcode selectItem tags into your JSF pages. But don’t worry, there is a simple solution to that problem.

Any backing bean can provide a ‘get’ method that returns a programmatically generated list of SelectItems, and this list of SelectItem objects can be set to the value property of a single JSF SelectItems tag that will replace any hard coded SelectItem tags. So, if we had a method named getOptions() in our RPSBean that returned a List of already initialized SelectItem objects, we could rewrite our selectOneListbox tag like this:

<h:selectOneRadio id="selectOneRadioGesture" value="#{rpsbean.clientGesture}">

<f:selectItems value="#{rpsbean.options}" />

</h:selectOneRadio>

And while the expression language syntaxt, value="#{rpsbean.options}", makes it look as though we are going after a property named options in the RPSBean, all we really need is a public getOptions() method that returns a java.util.List:

public List getOptions() {

List options = new ArrayList();

options.add(new SelectItem("Rock", "rock"));

options.add(new SelectItem("Paper", "paper"));

options.add(new SelectItem("Scissors", "scissors"));

return options;

}

Now, in this instance, I have hard coded the creation of three SelectItem objects into this method, but a more typical scenario might involve invoking a data access object, querying a database, and appropriately initializing SelectItem objects based upon the number of results that are returned from thedatabase.

You’ll find that in typical, day to day JSF programming, you will find the ability to create dynamic selection lists with the SelectItems tag to be much more useful than hard-coding in various SelectItem tags.


The next iteration of our Rock Paper Scissors application is going to involve a little GUI razzle dazzle.

I’d like to create a user interface that has both a textfield and a listbox on it, giving the user to either type a choice into a textfield, or select a choice from a listbox. However, the razzle-dazzle involved is the ensure that if a user types something into the textfield, then the listbox gets updated, and alternatively, if an item in the listbox is updated, the textfield will automatically be populated with the appropriate text.

This iteration will start out with the index.jsp being adjusted just slightly, to include a textfield, along with a listbox, side by side:

<h:form id="rpsgameform">

<h:inputText value="#{rpsbean.clientGesture}" />

<h:selectOneListbox value="#{rpsbean.clientGesture}" >

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

</h:selectOneListbox>

<h:commandButton id="submit" type="submit" value="Play!" action="#{rpsbean.doRockPaperScissorsGame}" />

</h:form>

One of the things you might notice here is that both the selectOneListbox and the inputText both specify the same rpsbean property for their value attribute. That’s bad, and will need to be changed, but it will help our application to ‘look’ like it’s working, so I’m going to leave it in for now. Logically, it makes sense, because we want both the textfiled and the listbox to be synchronized to show the same data, so we’ll leave it in and see what type of troube it gets us into.

Now, this type of JSF form will visually give us what we want, which is a textfield and a listbox, side by side on the web page displayed to the user. However, our goal is to have the two textfields sync up with each other whenever one of them changes. So, if someone clicks “Rock” in the listbox, the textfield will be populated with the word “Rock”, and when someone finishes typing ‘paper’ into the textfield, the item in the listbox that says “Paper” will be highlighted.

One thing we need to remember is that JSF happens on the sever side, so if we want any processing to occur, we must trigger a form submission. So far, the only way we have triggered form submissions is through either having a user press a button, or click on a commandLink. So, the question becomes, how do we get an inputfield or a listbox to trigger a form submission.

Well, it’s not overly elegant, but to get a GUI component like an inputfield or a listbox to trigger a form submission, we have to write a small little line of JavaScript into one of the standard DHTML event attributes of a JSF tag.

“Standard event” are triggered by a web browser when something ‘happens’ to an element on a web page. For example, when an element of an HTML form like a textbox gets focus, the onfocus event is triggered. When someone types a letter in an inputfield, an onkeydown event is triggered. And most importantly for us, when the content of an input field like a listbox or a textfield is altered, an onchange event is triggered.

Now, again, let me emphasize that these events are triggered by the web browser, and no real JSF processing happens on the client side unless we as developers explicitly place it there. In order to take advantage of the JSF framework, we need a request to go across the network and hit our applications running on the server. So, if we want to respond to a user selecting a new item in a listbox, or typing something into a textfield, we need to use the onchange event to trigger a form submission.

Making the following addition to both the inputText and the selectOneListbox is a good start:

onchange="this.form.submit();"

Here’s how the new iteration of our form looks with th onchange event attribute appropriately assigned:

<h:form id="rpsgameform">

<h:inputText value="#{rpsbean.clientGesture}" onchange="this.form.submit();" />

<h:selectOneListbox value="#{rpsbean.clientGesture}" onchange="this.form.submit();" >

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

</h:selectOneListbox>

<h:commandButton id="submit" type="submit" value="Play!" action="#{rpsbean.doRockPaperScissorsGame}" />

</h:form>

Now, the funny thing is, if you run this application, and start playing around with the listbox, it would appear that everything is working correctly. When the user clicks on any element of the list, the form is submitted, and when the page refreshes, the textfield is populated with the name of the item selected in the list. So, if a user clicks on “Rock”, the text String “Rock” appears in the textfield.

However, the reverse does not work, that is, when a user types “paper” into the textfield and moves focus to another element by either clicking off the textfield, or tabbing away, while the form still submits, when the page refreshes, the listbox is not updated, and in fact, if an item was selected in the listbox before the form was submitted, the whatever the user had typed into the textfield gets overwritten. So, what’s going on?

Well, right now, there’s really two phases of JSF processing on the server with which we need to be concerned. The first stage is where values are read from the webpage being submitted are read by the framework and subsequently used to update the gesture property of the RPSBean, and the second stage is where the JSF framework uses the various properties of RPSBean to initialize various fields in the updated HTML page that will get sent back to the server.

Now, we’ve confused the hell out of the JSF framework by lining two input fields to the same property in our RPSBean. Our JSP instructs the JSF framework to take the value of both the inputText field and the listbok and use those values to update the gesture property defined in the RPSBean. This sets up a scenario where the last runner through the gate ends up winning. In this case, the JSF framework first updates the gesture property in the RPSBean using the value of the textfield, and then, right after that, the value of the gesture property is set again, but this time to the value of the item selected in the listbox. At runtime, any selected value in the listbox will override any value specified by the textfield.

Once the RPSBean class is updated by the JSF framework with the latest values from the incoming HTTP request, the framework uses the newly updated model classes, which in this case is the RPSBean, to assign values to the inputText field and the listbox in our form. Since both the textfield and the listbox are linked to the gesture property, and since the listbox gets the last shot at updating the gesture property of the RPSBean, both the textfield and the listbox end up getting assigned the value of the listbox. This explains why when we select an item in the listbox, the textfield gets updated appropriately, but the listbox does not get updated when the content of the textfield changes.

So, how can we fix this?

First off, we need to stop having two form elements updating the single, gesture property. So, I’m going to remove the value="#{rpsbean.clientGesture}" entry in the listbox, although we still need to keep the onchange="this.form.submit();"

<h:selectOneListbox onchange="this.form.submit();" >

With this one change, we will stop the JSF framework from initializing the gesture property of the RPSBean based on the value of the item selected in the listbox, while at the same time, we will also stop the JSF framework from selecting an item in the listbox based on gesture property of the RPSBean when generating a webpage as a response.

Of course, this simply improves our design and eliminates some peculiar, undesired behavior, but it doesn’t actually solve our problem of trying to sync up the listbox and the inputText field. So, how do we do it?

Creating a Page Bean

Up to this point, the Java code we have written has really focused on managing a domain model, and implementing core application logic. But what we are trying to achieve right now is much more ‘page-centric.’ That is, the task of trying to synchronize the display of the textfield and the listbox is really more of a user-interface enhancement, as opposed to being a change or addition to the core business logic of our Rock Paper Scissors game. Our application logic should go in our model classes, which in this case is the RPSBean. But synchronizing form elements is much more JSP centric, so to perform this page centric logic, we are going to create what is typically referred to as a ‘page-bean.’ Out page bean will be very uncreatively called the PageBean.

Now, although I am bequesting this particular class with the title “Page Bean,” the fact is, it’s really no different from any other JSF managed bean, as it is simply a regular Plain Old Java Object (POJO), and since we will be expecting JSF to manage the lifecycle of this bean, we will need to register the PageBean in the faces-config.xml file.

<managed-bean>

<managed-bean-name>pagebean</managed-bean-name>

<managed-bean-class>com.mcnz.jsf.bean.PageBean</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

</managed-bean>

Now, how is a so-called ‘page bean’ different from a regular ‘managed bean’ where we would see regular business logic? Well, one big difference is the fact that in a page bean, it is acceptable to declare actual instances of JSF-centric components. So, since we want to have control of our HtmlSelectOneListbox and our HtmlInputText, we will need to create instances of these classes in our PageBean class, along with the requise setters and getters:

package com.mcnz.jsf.bean;

import javax.faces.component.html.*;

public class PageBean {

private HtmlInputText inputText = null;

private HtmlSelectOneListbox listbox = null;

public HtmlInputText getInputText() {return inputText;}

public void setInputText(HtmlInputText inputText) {

this.inputText = inputText;

}

public HtmlSelectOneListbox getListbox() {return listbox;}

public void setListbox(HtmlSelectOneListbox listbox) {

this.listbox = listbox;

}

}

And of course, our goal here is to have the textfield and the listbox constantly in sync with each other – that is, whenever a value changes for the listbox, the textfield will be instantly updated, and vice-versa. So, to perform this little trick, we are going to take advantage of a very special JSF event known as the ValueChangeEvent. Whenever the value of a form element occurs, a ValueChangeEvent is triggered, and we can take advantage of this ValueChangeEvent by implementing a ValueChangeListener.

The easiest way to implement a ValueChangeListener is to simply code a public and void method in a managed bean that takes an instance of a ValueChangeEvent as an argument. We want to respond to the listbox and the inputText fields changing, so we will have two methods which will be uncreatively named listboxChanged and inputTextChanged:

public void listboxChanged(ValueChangeEvent changeEvent) {

}

public void inputTextChanged(ValueChangeEvent changeEvent) {

}

The ValueChangeEvent contains both the old value of the form element that has changed, and the new value as well. So, when the listbox changes, we can simply call the getNewValue() method to find out what the newly selected gesture is. From there, we can update the value property of the HtmlInputText instance that we have declared in our PageBean, and will bind to the JSF inputText tag in our index.jsp:

public void listboxChanged(ValueChangeEvent changeEvent) {

String newGesture = (String)changeEvent.getNewValue();

this.inputText.setValue(newGesture);

}

And when the inputText changes, we will perform similar logic to update the instance of the HtmlListbox instance that is declared in our managed PageBean:

public void inputTextChanged(ValueChangeEvent changeEvent) {

String newGesture = (String)changeEvent.getNewValue();

this.listbox.setValue(newGesture);

}

So, we now have a PageBean that defined an instance of both an HtmlListbox and an HtmlInputText field. We also have two methods that can be used to react to a change in the value of a selectOneListbox or an inputText field. The task now is to bind the inputText and listbox elements that are defined in the index.jsp page to the instances that are declared in the PageBean.

To link an element declared through a JSF custom tag, all we need to do is ‘bind’ that tag to an instance declared in a backing bean, which is easily done using expressing language and the bind attribute. So, to link the h:inputText tag in our index.jsp page to the HtmlInputText instance defined in our PageBean with the name inputText, we update the inputText tag as so:

<h:inputText binding="#{pagebean.inputText}" value="#{rpsbean.clientGesture}" onchange="this.form.submit();" />

We then make a similar change to the selectOneListbox tag, binding the tag to the instance of the listbox defined in the PageBean class:

<h:selectOneListbox binding="#{pagebean.listbox}" onchange="this.form.submit();" >

Of course

Of course, we don’t simply want to bind the inputText and selectOneListbox to corresponding instances in the PageBean, but we also want to have the inputText field trigger the inputTextChanged method, and we want the selectOneListbox to trigger the listboxChanged method in the PageBean. To take advantage of the ValueChangeEvents these input fields will trigger, we use the valueChangeListener attribute of the form tags to invoke the appropriate ValueChangeListener event. Here’s how the inputText tag links to the inputTextChanged method:

<h:inputText

valueChangeListener="#{pagebean.inputTextChanged}" binding="#{pagebean.inputText}"

value="#{rpsbean.clientGesture}" onchange="this.form.submit();" />

And here’s how the selectOneListbox looks when updated with both the binding and the valueChangeListener attributes:

<h:selectOneListbox

valueChangeListener="#{pagebean.listboxChanged}"

binding="#{pagebean.listbox}"

onchange="this.form.submit();" >

Notice that both the inputText and selectOneListbox trigger a form submission through the onchage attribute of the tag: onchange="this.form.submit();"

The standard JSF tags process on the server, so if we wish for our ValueChangeListeners to actually run, we must ensure that the form gets submitted whenever the textfield or the listbox changes. Our little JavaScript placed in the onchange attribute ensures a form submission happens and our code runs.

package com.mcnz.jsf.bean;

import java.util.*;

import javax.faces.component.*;

import javax.faces.component.html.*;

import javax.faces.event.ValueChangeEvent;

import javax.faces.model.*;

public class RPSBean {

private String clientGesture = null;

private String computerGesture = null;

private HtmlInputText inputText = null;

private HtmlSelectOneListbox listbox = null;

public void listboxChanged(ValueChangeEvent changeEvent) {

System.out.println("listboxChanged changeEvent");

System.out.println("InputText: " + inputText.getValue());

System.out.println("Listbox: " + listbox.getValue());

inputText.setValue(listbox.getValue());

inputText.setDisabled(true);

inputText.setSize(80);

}

public void inputTextChanged(ValueChangeEvent changeEvent) {

System.out.println("inputTextChanged changeEvent");

System.out.println("InputText: " + inputText.getValue());

System.out.println("Listbox: " + listbox.getValue());

listbox.setValue(inputText.getValue());

}

public List getOptions() {

List options = new ArrayList();

options.add(new SelectItem("Rock", "rock"));

options.add(new SelectItem("Paper", "paper"));

options.add(new SelectItem("Scissors", "scissors"));

return options;

}

private javax.faces.component.UIParameter parameter = null;

private HtmlCommandLink link = null;

public UIParameter getParameter() {return parameter;}

public void setParameter(UIParameter parameter) {

this.parameter = parameter;

}

public String doRockPaperScissorsGame() {

String result = "failure";

System.out.println(clientGesture);

this.computerGesture = "rock";

try {

if (clientGesture.equalsIgnoreCase("scissors")){

result = "loss";

}

if (clientGesture.equalsIgnoreCase("paper")){

result = "win";

}

if (clientGesture.equalsIgnoreCase("rock")){

result = "draw";

}

} catch (RuntimeException e) {

System.out.println("Excetion");

}

return result;

}

public String getClientGesture() {return clientGesture;}

public void setClientGesture(String cg) {this.clientGesture = cg;}

public String getComputerGesture() {return computerGesture;}

public void setComputerGesture(String cg) {this.computerGesture = cg;}

public HtmlInputText getInputText() {

return inputText;

}

public void setInputText(HtmlInputText inputText) {

this.inputText = inputText;

}

public HtmlSelectOneListbox getListbox() {

return listbox;

}

public void setListbox(HtmlSelectOneListbox listbox) {

this.listbox = listbox;

}

}

<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<html>

<f:view>

<body>

<h:outputText value="Please chose between Rock, Paper, and Scissors:"/>

<h:form id="rpsgameform">

<h:inputText valueChangeListener="#{pagebean.inputTextChanged}" binding="#{pagebean.inputText}" value="#{rpsbean.clientGesture}" onchange="this.form.submit();" >

<f:valueChangeListener type="com.mcnz.jsf.bean.GenericValueChangeListener" />

</h:inputText>

<h:selectOneListbox valueChangeListener="#{pagebean.listboxChanged}" binding="#{pagebean.listbox}" onchange="this.form.submit();" >

<f:valueChangeListener type="com.mcnz.jsf.bean.GenericValueChangeListener" />

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

</h:selectOneListbox>

<h:commandButton id="submit" type="submit" value="Play!" action="#{rpsbean.doRockPaperScissorsGame}" />

</h:form>

</body>

</f:view>

</html>

It should also be noted that if your managed beans are getting a little bloated, or your faces-config file is getting a little too long, you can simply create a class that implements ValueChangeListener and has its own processValueChange method that takes a ValueChangeEvent as an argument. Here I’ve created a very simple class named GenericValueChangeListener which simply does some logging, printing out the old value, the new value, and the Java type of the class that has generated the event.

package com.mcnz.jsf.bean;

import javax.faces.component.UIComponent;

import javax.faces.event.ValueChangeEvent;

import javax.faces.event.ValueChangeListener;

public class GenericValueChangeListener implements ValueChangeListener {

public void processValueChange(ValueChangeEvent vce) {

String oldValue = (String) vce.getOldValue();

String newValue = (String) vce.getNewValue();

UIComponent component = vce.getComponent();

System.out.println("Old Value was: " + oldValue);

System.out.println("New Value is: " + newValue);

System.out.println("Component: " + component.getClass());

}

}

To use a class that implements a ValueChangeListener, as opposed to one that is defined within a managed bean, you can attach it to a JSF component by using the f:valueChangeListener tag and specifying the fully qualified name of the class. Here’s how it looks for the inputText tag:

<h:inputText valueChangeListener="#{pagebean.inputTextChanged}" binding="#{pagebean.inputText}" value="#{rpsbean.clientGesture}" onchange="this.form.submit();" >

<f:valueChangeListener type="com.mcnz.jsf.bean.GenericValueChangeListener" />

</h:inputText>

And we can use the same semantics to apply the GenericValueChangeListener to the listbox:

<h:selectOneListbox valueChangeListener="#{pagebean.listboxChanged}" binding="#{pagebean.listbox}" onchange="this.form.submit();" >

<f:valueChangeListener type="com.mcnz.jsf.bean.GenericValueChangeListener" />

<f:selectItem itemValue="rock" itemLabel="Rock" />

<f:selectItem itemValue="paper" itemLabel="paper" />

<f:selectItem itemValue="scissors" itemLabel="Scissors" />

</h:selectOneListbox>

Followers