Saturday, December 01, 2012

Moving on up and beans!

TAG!  Because markup is all the rage...

Well as you might have figured out, if I hadn't explicitly said it earlier, doing JSPs with the old style <% %> style tags is, well just that, old school.  Now don't get me wrong, a lot of code out there in the world still uses this syntax.  Of course, a lot of business code out there also uses COBOL.

At some point in the long history of Java EE, JSP version 1 was just a pain to use.  To clean things up a bit, the Java people came up with the idea (not really came up with) to use tags as opposed to marked up code.  Basically, you could put some code behind the scene and wire it into the page via a tag.  This allowed Java coders to think about Java and web developers to think about web developing.

So we are going to up the ante here and play both roles for the time being.  Basically we are going to create a simple Java class and use POJO (Plain Old Java Object, you hear POJO tossed around A LOT in Java circles) in our pages by using markup tags.

Our Java class will pick a number randomly and display it when you hit the page.  At the same time, we are going to say Hello, World again and display our Date/Time that we've come to know so much.  We will be using the outline pane (the one on the right) a lot here to add prebuilt methods to the class.  Also, we will be using the auto-completion feature of Eclipse a bit as well in the JSP page.  To activate the auto-complete function just press CTRL+Space and a small little box should call up.

So let's begin with our Java code.  Basically we want to expose three things here and those things are going to be read-only.

  1. Current Date/Time
  2. Random number
  3. Message: "Hello, World!"
So let's begin by creating a new Java class.  Right mouse click on the Java resources in the project explorer (left pane) under your project and select new class: New → Class

We want to keep thing organized, so our Java classes that are not servlets we will put into a package called, com.blogger.beans.  We will call this class HelloBean.  While you are at the dialog, go ahead and check the generate constructor from superclass.  That will give us a default no argument constructor for our new class.

Now we need to create what the Java people like to call fields.  In the C++ world we call them members.  Basically, these are variable that are private to the class.  We are going to create three, each to hold a bit of information that I enumerated earlier.

So click in your generated class file just between the public class statement and the constructor, this is usually where I like to put fields.  Here go ahead and start typing:

private Date currentDate;
private Integer randomNumber;
private String someMessage;

You'll notice the word Date is underlined.  That's because the "java.util" package has not been imported.  Click on the underlined word and the quick fix box shows up.  Go ahead and select the quick fix to import "java.util.Date".

Choose the first quick fix
At this point, you should see some warning light bulbs appear for your fields.  This means that they aren't being used and are good candidates for being removed from your code.  Instead let's use them.  Head over to the Outline pane (again, it's on the right) and right mouse click your class (Green ball with a C).  In the context menu select: Source → Generate Getters and Setters...

This will fire up yet another Eclipse wizard (at this point I'm just going to stop calling the wizards by name).  This wizard allows you to quickly generate the standard get and set names for each field in your class.  Since we are making our fields "read-only" we are only going to generate the "getters" and not the "setters".

(Hint:  In C++ the Java "getters" are called accessor, and the Java "setters" are called mutators.  I'm sure in C# they call them something else completely.  See how computer terms are fun!)

Click on the Select Getters for read-only.
So click on the Select Getters button and that will select only the getter methods to be generated.  Click OK and you'll be put back into your Java code editor and see the newly created methods.  These methods follow the Java Bean Standard (JSR-273) which basically puts the word "get" in front of the field's name and capitalizes the first letter of the name.  See hard standard to follow, eh?

Now in our constructor, we are going to set the values of these fields.  This way the fields are given a value when someone requests the POJO, and they can only read those values.  When someone requests a new POJO, new values are pumped into the fields.

Here's the final code for our class:

package com.blogger.beans;

import java.util.Date;

public class HelloBean {

 private Date currentDate;
 private Integer randomNumber;
 private String someMessage;
 public HelloBean() {
  this.currentDate = new Date();
  this.randomNumber = (int) (Math.random() * 10);
  this.someMessage = "Hello, World!";

 public Date getCurrentDate() {
  return currentDate;

 public Integer getRandomNumber() {
  return randomNumber;

 public String getSomeMessage() {
  return someMessage;


As you can see in the constructor, I've given each field a value.  So now we save our bean and let's create a new JSP page.  In our Project Explorer (left side), go ahead and find our current index.jsp and delete it, by right mouse clicking on the file and choosing Delete from the context menu.  You'll get a pop up asking if you are sure.

Now let's create a new one by right mouse clicking on the WebContent folder and choosing New → JSP File.  In the wizard dialog thing, name the file index.jsp (again) and in the second step of the wizard pick the HTML one again.

We are now going to tell the JSP compiler that we wish to use our Java bean that we just created.  To do that we need to use one of the standard JSP tags.  These are located in the built in namespace called jsp.

The tag that we wish to use is

So just above the element in your newly generated JSP page, add a space between the DOCTYPE declaration and the html tag and press CTRL+Space to call up the auto complete.  You'll see a slew of jsp tags that you can use.  Go ahead and start typing jsp:us  and you should see the tag that you are looking for pop into the box.  (It is important that when you want to auto-complete tags that you NOT type the opening marker "<", Eclipse will do it for you.)

Using auto-completion

You will note that it goes ahead and puts in one of the attributes called "id".  Go ahead and give this attribute the value of "mybean".  Now we need to tell the JSP compiler which Java class to associate with this ID.  We do that with the "type" attribute.  For good measure we will also do the "class" attribute.  We want to fill both of these attributes with the fully qualified name of our bean: com.blogger.beans.HelloBean.  However, the nice thing is that if we type enough say, "com.blo" we can then use auto-completion.

Using auto-completion for the type attribute, do this for the class attribute as well.
The final attribute that we need to set is called "scope".  This basically tells the JSP compiler how often it should build the POJO from our Java class.  Right now, the default is page.  This means that the POJO will exist as long as the page.  If you refresh the page, then you get a new POJO.  There is all kinds of request scopes and in a later post, I'll cover them.  However, let go ahead and explicitly declare this.

Using auto-complete, as you can see the default value of this attribute will be page
There you go, you have now "wired" the bean into your JSP!

Now let's use the bean in the JSP.  In the body of the web page create a paragraph element
and in paragraph element go ahead and create a jsp:getAttribute element.  (Remember you can press CTRL+Space and then type "jsp:getA" to auto-complete it)

You'll see two attributes in this element "property" and "name".  The "name" attribute is the name you gave in the ID of the jsp:useBean tag.  Go ahead and fill that in with the name "mybean".  Move back over to the property attribute and CTRL+Space.  You'll see a list of fields that comply with the JSR-273 standard.  Go ahead and select the currentDate field.

Using auto-complete in the property attribute to grab the bean fields.
Go ahead and do the same thing for the random number and the message as well.  I'll add in a couple of BR elements to break up the information on multiple lines.  Here's what my final code looks like.

<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<jsp:useBean id="mybean" type="com.blogger.beans.HelloBean" class="com.blogger.beans.HelloBean" scope="page"></jsp:useBean>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <jsp:getProperty property="currentDate" name="mybean"/><br />
  <jsp:getProperty property="randomNumber" name="mybean"/><br />
  <jsp:getProperty property="someMessage" name="mybean"/>

Now you are ready to run this web application on your server.  You can quickly run the project by click on the run icon in the toolbar (about time I started talking about the toolbar, eh?)  Here's a picture of what it looks like:

Quickly run your project by clicking on this icon.
You should see your web page appear with all the information.  You can click the refresh button to see the information updated with every page.

Location of refresh button
Ta-Da!  You've now built a more powerful web application by using beans!  You've also ditched the <% %> tag method to start using the more XML friendly JSP tags.  There's a lot of places to go now, but we've only created a read-only bean.  How do we make and use read-write beans?  We'll create a slightly more powerful and interactive web application on the next go round.  For now, get use to using the auto-completion and building JSP pages.  I'm going to start dropping the step-by-step and start looking at the general overview.  So get cozy with creating Java classes, servlets, and JSP pages.


No comments: