So it is pretty apparent that I haven't been updating this blog in a while. The reason for this is that we are going through a period where we are converting MS Access files into full fledged applications.
Now MS Access is fine and what not, but after a certain point, it can get a bit abused. That point was crossed some time ago in my company that I work for. So what are we switching to? Not Java, no that would have been too awesome. However, I can't say that I am really down about what platform we are going with. We are going to be using Qt! Qt 5 to be exact.
I'm a bit thrilled to be tasked to start working back in my favorite language, C++. Not only that, Qt 5 supports many of the most recent additions to the C++ language. I can hardly wait to start digging in.
I'm going to pick back up on the JSF tutorial here in a bit. The next step it looks like was a read/write JSF managed bean. So I'll do a quick run through of that, but I doubt that I'll have the namesapces match up with what they were in the previous post.
I don't fully remember where I was going with all of the JSF stuff, but I guess after the Read/Write thing, moving into AJAX in JSF.
Cheerio!
Monday, July 15, 2013
Friday, April 19, 2013
Moving on, using a managed bean
So let's try using what is known as JSF managed beans. Managed beans are plain old Java objects (POJO) that get managed by the JSF controller.
How it technically works is that the JSF library will scan the classes in your project for the @ManagedBean annotation. When it finds a class, it registers it as a managed type.
Once registered, you can create beans all over the place in your JSF pages. Beans can have one of six scopes:
Right mouse click on your project and select New » Other…
Choose the JSF Managed Bean and click Next >
Fill in the information about your bean and I'm going to set it to request scope. The package will be lan.testing. You can also add a little description to the bean. No idea where this description gets saved at the moment. Go ahead and click finish.
Now you will have a newly minted request bean.
Now at the moment this bean does absolutely nothing other than suck memory. So let's make it do something more interesting. Let's add a field in the Java class called message. We will make this field private. So let's add that now. While we are at it, let's set the fields default value by placing that in the constructor.
Now let's expose that bean so that it can be used on our pages. We do that by creating standard getters and setters. Just press Alt+Insert in the IDE to get a popup.
Your Java class should look like the following:
Now that we have exposed the field, let's go ahead and add that to our JSF page. To access JSF managed beans we need to replace the static text in our tag with #{}. The pound sign and curly brackets indicate to the JSF libraries that it needs to look at all of the registered classes.
Once we type that into the value you'll notice a code completion pop-up appear.
In the completion box you should see the name of your managed bean. Go ahead and select it. It will now appear as #{whateverYouNamedYourBean}.
Go ahead and type period to get the next bit, this will show you what has been exposed by this bean.
Go ahead and select the exposed message field.
Once you have done that, go ahead and press the giant play button to see the results.
Ta-da! Your field in the Java class is now exposed and being used by the JSF libraries. Right now, not very useful, but good to know that it is working. All of this on Tomcat!
Quick point:
Beans are meant to allow you to create useful components to be used in your JSF application. Right now it might be a bit hard to see that, but eventually you'll start building beans that are for all kinds of purposes, with all kinds of different scopes.
The thing to remember about beans is that you should take the million little cogs approach with them. As opposed to building one giant bean or one huge session bean and one huge request bean, beans should be for a specific purpose in your web application. You may have one that hold the current user's profile information, another to hold the current conversation that they are in, and so on.
Right now we are only using the read function (get) of the bean. I'll show you next how to write (set) to the bean and explain a bit about why it works.
How it technically works is that the JSF library will scan the classes in your project for the @ManagedBean annotation. When it finds a class, it registers it as a managed type.
Once registered, you can create beans all over the place in your JSF pages. Beans can have one of six scopes:
- @RequestScope - This means the bean is created for the life of the HTTP request. Once the HTTP request has been fully processed the bean is destroyed. Basically, these beans exist so long as the request for a web page lasts. Once the page has been serviced, the bean is no longer available. This also applies to AJAX requests.
- @SessionScope - This bean is created for the life of the HTTP session. Once a HTTP session is started, the JSF library will create this bean and allow it to last so long as the HTTP session is still open. Once the HTTP session ends, due to inactivity or closing the web page, the bean is destroyed.
- @ViewScope - This is an interesting bean that will last through requests, so long as the current view has not changed. This is useful is you present a single view to the user and then do a lot of AJAX in the background to modify that view.
- @ApplicationScope - This is a bean that is created as soon as the application is started. That means as soon as you publish it to the server or upon the first HTTP packet to the application (this is dictated by the eager=true flag, setting to true is as soon as you publish it.) Only use this kind of bean for things that can safely be shared between instances of sessions. Just FYI, don't assume that this automatically means thread safety.
- @NoneScope - This is a bean that is created as soon as it is requested in a JSF page and destroyed as soon as it was created. If you use the bean three times in your JSF page, then the bean is created and destroyed three times. In my example to follow, the none scope would have sufficed. Use this kind of bean for one shot stuff that doesn't need to be remembered, or if you intend on using this bean within another bean.
- @CustomScope - This is exactly what it says. You define when and where the bean exists and get destroyed by modifying a Map that is created for managing this bean. When you add an entry to the Map, the bean is created, when you remove the entry the bean is destroyed. Use this when nothing above seems to fit your use-case.
Right mouse click on your project and select New » Other…
![]() | |
This screen appears |
![]() |
We're just going to go with the defaults here with a little bit of extra like package name, generally you are going to name this something actually useful. |
Now you will have a newly minted request bean.
![]() |
New JSF Managed Bean |
![]() |
Adding a field to the bean |
Now let's expose that bean so that it can be used on our pages. We do that by creating standard getters and setters. Just press Alt+Insert in the IDE to get a popup.
![]() |
Select the Getter and Setter… option |
![]() |
Check the boxes of the fields you want to expose, since we have one, we are exposing them all. |
![]() |
Your field is now exposed by the bean. |
Once we type that into the value you'll notice a code completion pop-up appear.
![]() |
Code completions is happening. |
Go ahead and type period to get the next bit, this will show you what has been exposed by this bean.
![]() |
Our field exposed by the bean |
![]() |
Our completed code |
Ta-da! Your field in the Java class is now exposed and being used by the JSF libraries. Right now, not very useful, but good to know that it is working. All of this on Tomcat!
Quick point:
Beans are meant to allow you to create useful components to be used in your JSF application. Right now it might be a bit hard to see that, but eventually you'll start building beans that are for all kinds of purposes, with all kinds of different scopes.
The thing to remember about beans is that you should take the million little cogs approach with them. As opposed to building one giant bean or one huge session bean and one huge request bean, beans should be for a specific purpose in your web application. You may have one that hold the current user's profile information, another to hold the current conversation that they are in, and so on.
Right now we are only using the read function (get) of the bean. I'll show you next how to write (set) to the bean and explain a bit about why it works.
First JSF web application on Tomcat 7
Okay as promised, here is the first Netbeans 7.3 + JSF 2.1 + Tomcat 7 web application.
First download Netbeans, if you haven't already. Go ahead and select the full all out, no hold bars download. Next install the software and make sure you install the Tomcat that is included with Netbeans installer.
Okay now that you have all of that out of the way, go ahead and start up Netbeans and head over to the services tab and start up the Tomcat Server installed on your system.
Now go ahead and start a new project. Choose Java Web | Web Application. See the following images for the wizard screenshots.
So to ensure that we are running JSF and not that the server is doing some sort of pseudo translation here, let's use an actual JSF tag.
I'll use the tag which does exactly what it says, it outputs text. Here I'll just use some static value for the value attribute.
So there you go, your very first JSF 2.1 application on a Tomcat server.
Here's some highlights. Tomcat 7 does not come with JSF baked in. It is a simple servlet server. Ergo, you must include the JSF library with your project. The nice thing is that Netbeans will go ahead and do that for you, because it knows that Tomcat doesn't have these libraries by default.
Now here's the deal. If at some point down the road, you add these libraries to the Tomcat server itself, then you need to make sure that Netbeans doesn't try to "help" you out here. To do that, you need to indicate that the libraries do not need to be pushed to the server with the application. Right mouse click on the libraries icon and choose properties.
Once you do that this window appears:
Notice the check boxes highlighted. When they are checked, that means the library will be "packaged" with the application. If the libraries are already on the server, you don't need to package them.
Disclaimer:
Don't include the JSF libraries inside your server, just package them with the application. Once you toss the libraries into the server, that pretty much makes that server a JSF Tomcat server.
The downside of this is, this could potentially ruin any old JSP applications that you have on the server. Now it shouldn't but I would count on something jacked up happening the second you toss JSF libraries on a Tomcat running JSP applications.
I'll start covering some more fun stuff with JSF next post! Have fun!
First download Netbeans, if you haven't already. Go ahead and select the full all out, no hold bars download. Next install the software and make sure you install the Tomcat that is included with Netbeans installer.
Okay now that you have all of that out of the way, go ahead and start up Netbeans and head over to the services tab and start up the Tomcat Server installed on your system.
![]() |
Starting up the Tomcat server. Netbeans 7.3 automatically detects this installed if you did it with the installer from the web. |
Now go ahead and start a new project. Choose Java Web | Web Application. See the following images for the wizard screenshots.
![]() |
Step 1 - Title your new web application. |
![]() |
Step 2 - Choose the server to deploy to and the context to use. MAKE SURE YOU SELECT THE TOMCAT INSTALL! |
![]() | ||||
Step 3 - Include what libraries you might need. Make sure you click the JavaServer Faces library. Tomcat doesn't come with JSF built in, you must manually add it! |
Okay you should now have a shell project with the default index file.
![]() | |||||||
Behold! The default index file! |
So to ensure that we are running JSF and not that the server is doing some sort of pseudo translation here, let's use an actual JSF tag.
I'll use the
![]() |
Adding in a JSF tag, don't forget the tag. |
Now go ahead and click on the run project icon, it's that giant play button up there. If your Tomcat server is running (you better go catch it, ha ha) then it will deploy the project to the server and open up your browser to the context that you provided.
![]() |
Pushing the Play button. |
![]() |
Ta-da! Our project runs! |
Here's some highlights. Tomcat 7 does not come with JSF baked in. It is a simple servlet server. Ergo, you must include the JSF library with your project. The nice thing is that Netbeans will go ahead and do that for you, because it knows that Tomcat doesn't have these libraries by default.
![]() |
Draw your attention to the highlighted area. |
![]() | |
If you do not see Properties, then it's because you aren't right clicking in the correct 16x16 space. |
Notice the check boxes highlighted. When they are checked, that means the library will be "packaged" with the application. If the libraries are already on the server, you don't need to package them.
Disclaimer:
Don't include the JSF libraries inside your server, just package them with the application. Once you toss the libraries into the server, that pretty much makes that server a JSF Tomcat server.
The downside of this is, this could potentially ruin any old JSP applications that you have on the server. Now it shouldn't but I would count on something jacked up happening the second you toss JSF libraries on a Tomcat running JSP applications.
I'll start covering some more fun stuff with JSF next post! Have fun!
Loss of data and moving on.
Of course,
I've lost the whole project that I was doing in JSP and Tomcat. I really don't feel like going back and going over the whole things…again.
So I'm going to need a new project now. Hmmm…
Okay, let's do the good old fashion Tomcat 7 + JSF 2.0 + NetBeans IDE.
Not to say that I don't like Eclipse, but I'm a bigger fan of NetBeans. Sorry for all of the Eclipse fan boys out there. If it helps, I use Eclipse everyday with Android stuff.
In fact! How about something Android? That sounds like fun too! So here's what I'm going to do going forward.
Monday and Friday I'll do a post about JSF and pretty much J2EE stuff.
Wednesday I'll do something about Android. Why the hate for Android? Because I spend so much time developing Android stuff for work, I get tired of even looking at the IDE. I guess that's why my interest in the JSP thing waned so much.
I'm so capricious it's not even funny. I'll setup some labels. We will name the J2EE stuff with the J2EE label and when it includes TomCat, I'll add in TomCat. When it deals with Glassfish I'll add Glassfish. For the Android stuff, I'll just add the label Android.
Okay, so there we go. Something to do. Oh look it's Friday! Better start working on my first J2EE post.
Cheers!
I've lost the whole project that I was doing in JSP and Tomcat. I really don't feel like going back and going over the whole things…again.
So I'm going to need a new project now. Hmmm…
Okay, let's do the good old fashion Tomcat 7 + JSF 2.0 + NetBeans IDE.
Not to say that I don't like Eclipse, but I'm a bigger fan of NetBeans. Sorry for all of the Eclipse fan boys out there. If it helps, I use Eclipse everyday with Android stuff.
In fact! How about something Android? That sounds like fun too! So here's what I'm going to do going forward.
Monday and Friday I'll do a post about JSF and pretty much J2EE stuff.
Wednesday I'll do something about Android. Why the hate for Android? Because I spend so much time developing Android stuff for work, I get tired of even looking at the IDE. I guess that's why my interest in the JSP thing waned so much.
I'm so capricious it's not even funny. I'll setup some labels. We will name the J2EE stuff with the J2EE label and when it includes TomCat, I'll add in TomCat. When it deals with Glassfish I'll add Glassfish. For the Android stuff, I'll just add the label Android.
Okay, so there we go. Something to do. Oh look it's Friday! Better start working on my first J2EE post.
Cheers!
Wednesday, February 27, 2013
Where have I been?
You'll have to excuse me, I haven't updated the blog in some time. I've been doing the road warrior thing for a couple of weeks now, which keeps me from my standard machine that I use and have all my code on at home.
I'll jump back to the JSP demonstration here in a bit. I know you've all heard that before.
I'll jump back to the JSP demonstration here in a bit. I know you've all heard that before.
Thursday, January 03, 2013
Doing this MVC thing! Part 1
Let's get back to our web application shall we?
First let's remove everything in our project and start fresh. Here is what I have for the Contact Keeper project.
So basically all that we are keeping is the "com.blogger.contacts.beans" package and the JSTL libraries. Now let's begin where any sensible project would begin. On the information that we are trying to store. In other words, I like to look at the problem as "what to store, before presentation." Some developers like to work on presentation first and then data. I always get confused when I work this way, hence the reason I like to focus on data first. However, to each their own.
First let's remove everything in our project and start fresh. Here is what I have for the Contact Keeper project.
![]() |
My current layout for the project. |
So basically all that we are keeping is the "com.blogger.contacts.beans" package and the JSTL libraries. Now let's begin where any sensible project would begin. On the information that we are trying to store. In other words, I like to look at the problem as "what to store, before presentation." Some developers like to work on presentation first and then data. I always get confused when I work this way, hence the reason I like to focus on data first. However, to each their own.
Now our "database" isn't going to be a real database, we are just going to use a memory structure to store the information. If our server gets turned off, then we loose all of our information. That's okay, because we are going to make the interface to our database generic so that if we decide to ditch the memory storage and replace it with a real DB like PostgreSQL later on, then it will require very little code change.
So the first thing we need to do is create the actual object that we plan to store. That means we need to model our contact in Java code. If we were using a real database then we'd add another layer on top of our contact model to implement JPA. JPA is just a fancy system that you use to translate Java objects into SQL code automatically (I am really simplifying the heck out of JPA here, but the premise holds.)
So we are just going to have a basic naked model here. Our contacts should have the following:
So the first thing we need to do is create the actual object that we plan to store. That means we need to model our contact in Java code. If we were using a real database then we'd add another layer on top of our contact model to implement JPA. JPA is just a fancy system that you use to translate Java objects into SQL code automatically (I am really simplifying the heck out of JPA here, but the premise holds.)
So we are just going to have a basic naked model here. Our contacts should have the following:
- First name - string
- Last name - string
- Phone number - string (we are not going to deal with validation here, at least not now)
- Age - integer (real contact keepers would ask for Birthdate and calculate age from that, be we aren't doing that here, at least not now)
That's it. Pretty simple. I want to keep it pretty simple for the time being.
So let's create your Java code for this model. We are going to store this Java class in a new package called, "com.blogger.contacts.entity" Entity is the technical term for an object that models to something one would store in a database (or relates to something in the real world if you want a much fuller idea of the term), honestly if you really want a better technical definition, feel free to hit up Wikipedia. At any rate, we are going to create anything that maps to the real problem in the entity package.
So here is the code:
package com.blogger.contacts.entity; import java.io.Serializable; public class Contact implements Serializable { /** * Serial version of our contact class, so that version stay compatible. */ private static final long serialVersionUID = 1L; private String firstName; private String lastName; private String phoneNumber; private Integer age; public Contact() { this.firstName = null; this.lastName = null; this.phoneNumber = null; this.age = null; } public Contact(String firstName, String lastName, String phoneNumber, Integer age) { super(); this.firstName = firstName; this.lastName = lastName; this.phoneNumber = phoneNumber; this.age = age; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Contact other = (Contact) obj; if (age == null) { if (other.age != null) return false; } else if (!age.equals(other.age)) return false; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; if (phoneNumber == null) { if (other.phoneNumber != null) return false; } else if (!phoneNumber.equals(other.phoneNumber)) return false; return true; } @Override public String toString() { return "Contact [firstName=" + firstName + ", lastName=" + lastName + ", phoneNumber=" + phoneNumber + ", age=" + age + "]"; } }
So you may be asking yourself, why isn't this a bean? Well it is, to an extent, back in the day you'd be absolutely correct about this being a bean, as this used to be called an Entity Bean. However, as Java EE matured it became clear that Entities were stuff that mapped to real world things, and Beans were used to access stuff. So in a basic case like ours here, our Entity could very well function as the bean as well, since the logic needed to access our entity is pretty simple stuff. However, in more complex cases we might want Access beans that handle the needed logic to access our entities.
For now what we are going to do is let our entity stand by itself and we will create a DAO (Data Access Object) bean that will provide the basic CRUD (Create, Read, Update, and Delete) that we need to have a functioning application.
So there is our entity. I've provided a hash code function, an equals function, and a to string function. I usually do this for my benefit rather than any application need. Your taste to do so may vary.
There you go, we've created the entity. Now we need to create somewhere to actually store these things! This needs to be a memory based storage, remember what I said earlier, and it needs to be simple and not overly complex. What I am going to do, and this isn't something you'd normally do on production code, is just create a regular old collection and set it to the application scope, so that any sessions can access it. Now you don't do this in normal production code because it is not thread safe at all. People could come in and create the same contact at the same time and there would be nothing to stop them, or they could delete a contact that was deleted by someone else while the first person was deleting it. In other words, it could lead to all kinds of badness.
We are going to use a basic Array List collection because it is fast on insert (adding contacts), fast on update (changing information or updating a contact), normal speed on listing (viewing all contacts), and slow on delete and random access (getting rid of contacts and finding a contact). The only down side is the last part, random access, a contact list's number one feature is "finding" contacts. We could use a hash map, but then our program would a bit more memory hungry but finding contacts would be very fast, and since we are not actually going to be using this code in any production system, I doubt that our contact list will ever grow to the size where a hash map makes more sense than an array list. (I would need at least the assumption that the contact list would be at least 100 contacts or more before I would consider the hash map a good fit.)
break time...
Just noticed it is getting late, better call it a night for the time being. We will implement our Array List next and we are going to create an interface DAO and DAO for that implementation that implements our interface. So in case you missed that, part two will do the following.
For now what we are going to do is let our entity stand by itself and we will create a DAO (Data Access Object) bean that will provide the basic CRUD (Create, Read, Update, and Delete) that we need to have a functioning application.
So there is our entity. I've provided a hash code function, an equals function, and a to string function. I usually do this for my benefit rather than any application need. Your taste to do so may vary.
There you go, we've created the entity. Now we need to create somewhere to actually store these things! This needs to be a memory based storage, remember what I said earlier, and it needs to be simple and not overly complex. What I am going to do, and this isn't something you'd normally do on production code, is just create a regular old collection and set it to the application scope, so that any sessions can access it. Now you don't do this in normal production code because it is not thread safe at all. People could come in and create the same contact at the same time and there would be nothing to stop them, or they could delete a contact that was deleted by someone else while the first person was deleting it. In other words, it could lead to all kinds of badness.
We are going to use a basic Array List collection because it is fast on insert (adding contacts), fast on update (changing information or updating a contact), normal speed on listing (viewing all contacts), and slow on delete and random access (getting rid of contacts and finding a contact). The only down side is the last part, random access, a contact list's number one feature is "finding" contacts. We could use a hash map, but then our program would a bit more memory hungry but finding contacts would be very fast, and since we are not actually going to be using this code in any production system, I doubt that our contact list will ever grow to the size where a hash map makes more sense than an array list. (I would need at least the assumption that the contact list would be at least 100 contacts or more before I would consider the hash map a good fit.)
break time...
Just noticed it is getting late, better call it a night for the time being. We will implement our Array List next and we are going to create an interface DAO and DAO for that implementation that implements our interface. So in case you missed that, part two will do the following.
- Implement our Array List to store our Contact entities.
- Create an interface for our DAO so that we keep a standard interface regardless of if we are using memory or actually DB back ends.
- Create a concrete object for our DAO interface that has all the logic to connect our interface and Array List implementation.
Sunday, December 30, 2012
Rough Holidays
So where have I been?
Doing some serious down time. I've been forcing myself to really take it easy the last few weeks. I was sick, got better, and then suddenly really got sick.
I didn't really want to come back to the computer until I had a few days of what might be called good health. I'm still sick, don't get me wrong, but I'm at least well enough to post that I'm still on some downtime.
However, just to be me...
How to write a simple HTML5 Canvas web page.
HTML5 is pretty slick! The neatest thing that I can show and not take five years trying to explain it is how to use the HTML5 canvas.
First you need a basic HTML file with the magical canvas tag included. Here is an example of such an HTML file.
So as you can a pretty easy to understand HTML file. As you can see, this file alone does absolutely nothing. All the magic is in the canvas.js file. However, do note the DOCTYPE html tag, that is needed for most browsers to understand that the file is an HTML5 file.
So let's take a look at that instead.
So that should be obvious to anyone who's ever worked in javascript, but just in case, here's the breakdown.
The first part adds a function that contains all our logic to the webpage's "load" trigger. In other words, the code within will fire as soon as the page is loaded. The first things we do is create a canvas, context, and painting variable. The canvas var will hold the location of the canvas tag which we will be using to grab a context from. The context var is the handle to the browser system resource for the 2d context, aka, that's what we are really going to be drawing to. The painting var will act as a Boolean var telling us if we should be painting or not when we move the mouse.
Pretty simple stuff and if you've ever used Java's AWT then you might have noticed how similar this all looks to AWT.
We create a function within called init. It gets the canvas tag, pulls the context from the tag (we use a simple test to make sure that this did happen for each step), set the painting flag to false, and store some states to the context. (Basically, a state is something you set and it stays that way until you change it again.)
After creating that function, we call it.
Finally, we add some event listeners to the canvas tag, because you cannot add listeners to a context. On the mouse down event, we set the painting flag to true, we tell the context "to put the pen down on the paper" at the current mouse position.
On the mouse move event we update the readout (which prints out the current mouse coordinates) and if the painting flag is on, we tell the pen to move to the current mouse coordinates.
On the mouse up event we turn off the painting flag and tell the pen to be "picked up."
That's it! Pretty simple stuff. Save the two files, open the HTML file in a nice browser (aka, not Internet Explorer) and poof!
Pretty simple and fast HTML5 canvas demo! Ta-da!
Doing some serious down time. I've been forcing myself to really take it easy the last few weeks. I was sick, got better, and then suddenly really got sick.
I didn't really want to come back to the computer until I had a few days of what might be called good health. I'm still sick, don't get me wrong, but I'm at least well enough to post that I'm still on some downtime.
However, just to be me...
How to write a simple HTML5 Canvas web page.
HTML5 is pretty slick! The neatest thing that I can show and not take five years trying to explain it is how to use the HTML5 canvas.
First you need a basic HTML file with the magical canvas tag included. Here is an example of such an HTML file.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Canvas Example</title> <script src="canvas.js" type="text/javascript"></script> </head> <body style="background: #fefeef"> <h3>Hi there!</h3> <canvas width="400px" height="400px" id="paintingCanvas" style="border: thick solid teal"> Canvas not supported. </canvas> </h:body> </html>
So as you can a pretty easy to understand HTML file. As you can see, this file alone does absolutely nothing. All the magic is in the canvas.js file. However, do note the DOCTYPE html tag, that is needed for most browsers to understand that the file is an HTML5 file.
So let's take a look at that instead.
window.addEventListener("load", function() { var canvas, context, painting; function init() { canvas = document.getElementById("paintingCanvas"); if (canvas == null) return; context = canvas.getContext("2d"); if (context == null) return; painting = false; context.strokeStyle = "#00f"; context.lineWidth = 3; context.font = "15px Helvetica"; } init(); canvas.addEventListener("mousedown", function(ev) { painting = true; context.beginPath(); context.moveTo(ev.offsetX, ev.offsetY); }, false); canvas.addEventListener("mousemove", function(ev) { updateReadout(ev.offsetX, ev.offsetY); if (painting) { paint(ev.offsetX, ev.offsetY); } function updateReadout(x, y) { context.clearRect(0, 0, 100, 20); context.fillText("x: " + x + ", y: " + y, 5, 15); } function paint(x, y) { context.lineTo(ev.offsetX, ev.offsetY); context.stroke(); } }, false); canvas.addEventListener("mouseup", function() { painting = false; context.closePath(); }, false); }, false);
So that should be obvious to anyone who's ever worked in javascript, but just in case, here's the breakdown.
The first part adds a function that contains all our logic to the webpage's "load" trigger. In other words, the code within will fire as soon as the page is loaded. The first things we do is create a canvas, context, and painting variable. The canvas var will hold the location of the canvas tag which we will be using to grab a context from. The context var is the handle to the browser system resource for the 2d context, aka, that's what we are really going to be drawing to. The painting var will act as a Boolean var telling us if we should be painting or not when we move the mouse.
Pretty simple stuff and if you've ever used Java's AWT then you might have noticed how similar this all looks to AWT.
We create a function within called init. It gets the canvas tag, pulls the context from the tag (we use a simple test to make sure that this did happen for each step), set the painting flag to false, and store some states to the context. (Basically, a state is something you set and it stays that way until you change it again.)
After creating that function, we call it.
Finally, we add some event listeners to the canvas tag, because you cannot add listeners to a context. On the mouse down event, we set the painting flag to true, we tell the context "to put the pen down on the paper" at the current mouse position.
On the mouse move event we update the readout (which prints out the current mouse coordinates) and if the painting flag is on, we tell the pen to move to the current mouse coordinates.
On the mouse up event we turn off the painting flag and tell the pen to be "picked up."
That's it! Pretty simple stuff. Save the two files, open the HTML file in a nice browser (aka, not Internet Explorer) and poof!
![]() |
Master Artist, I am not. |
Pretty simple and fast HTML5 canvas demo! Ta-da!
Sunday, December 16, 2012
Wow! Also, MVC theory
I just have to applaud the flu virus that I got, because it was kicking my butt and putting my name to shame...
Well, I'm on the mend now, not entirely mind you, so I figure I would get back to JSPs.
You might remember waaaaayyyyy back when I talked about servlets? Well today, what I'm going to cover real quick is creating a servlet that will forward us to another JSP.
Basically, what the servlet will do when you try to access it is "forward" the request. That's pretty much it.
So the overview is this, index.jsp will have a link that will send us to to ContactKeeper/App servlet. The servlet will then send us to the welcome.jsp page.
The servlet will become the main hub for our application. Basically, anytime we click on a link within the ContactKeeper application, it will just basically send us back to the ContactKeeper/App servlet.
In fact, let's skip the coding for now, I will get to that tomorrow. For now let's learn a little theory.
The reason for this, primarily, is so that our application logic can be stored in the Servlet code. Our display logic will be stored in the JSPs that we create. This separation is the starting point for something known as Model-View-Controller or (MVC) for short.
Like I said we created beans so that we store data logic in Java code outside of the JSP. Thus our JSPs focus more on just display and page control and the beans deal with storing the information.
At the moment our beans don't do much, they just store the information in memory. However, we could easily change that so that we store the data in something like a database.
Our JSPs handle page control at the moment which is basically done via tags which is standard HTML stuff. However, this pretty much leaves us in linear mode for page logic, which granted for an address book, you don't need a whole lot of logic.
However, what if we needed more powerful logic? Javascript? No way! Putting Java code in the JSP? No way! We're trying to get away from that. The goal would be to allow some piece of Java code decide where the application should go next based on the current session's values. Enter the Servlet as the central hub.
To get an overview of what this looks like, here is a rough draft of what we will be doing. (Shout out to http://www.draw.io, you all rock!)
Our client, aka the web browser, will keep sending HTTP GET requests to the servlet. The Servlet then reads in all of the parameters on the URL and the current session's values to decide what to do next. It can interpret values into request for either create, view, update, or remove data.
The servlet can send these request for data to the Data Access Object (DAO). The DAO will handle all the little details about the actual data, so the servlet may ask to add a contact. The DAO will actually know how to do this. The DAO sends back to the servlet a pass or fail result, and then the servlet will forward the request to the proper JSP.
The servlet will pass to the JSP an entry point in the DAO to see the detail results of what was requested. (Why a name couldn't be added, the name has been successfully added, the listing of all contacts, etc...) The JSP will use that entry point to display the results from the DAO.
As you can see each section is concerned with one part of logic. The Model deals with handling all of the data ins and outs. It creates data, removes data, and so on. It is the data handler.
The Controller makes sure that everything happens in a controlled manner. If the model says that a name cannot be added, the controller forwards the client to the error page. However, do note, that the Controller doesn't actually check to see if the incoming data is valid or not, that is the job of the Model. The controller simply passes the data to the correct department to be handled and if the data is invalid, let's the user know that.
The view is what our users see. It is primarily concerned with displaying what is going on and what has been requested. The view presents all the forms our users will be entering and formats all of the data for the user that is sent to us from our Model. Forms that get filled out and submitted are sent to the controller for processing, from there the controller may delegate the processing of a form to some other subsystem and so on...
So while the MVC architecture looks a bit confusing at first, it provides a method for separating the major functions of a web application into manageable bits. Each bit is pretty independent of the other.
For example, we can change our JSPs to have a new style without messing up any of the navigation code or how we access a database. We can change our system from a in-memory style system to an actual database so long as the DAO keeps the same interface for the controller to call. We can implement a new navigation scheme by changing the controller, without messing up our JSPs or our data access.
The ability to break into independent pieces is a requirement for service flexibility.
You might notice that in my model I have the DAO using data beans and direct access. Using direct access is sometimes a necessary evil in models. Especially if your data requires a lot of calling stored procedures to get the data. However, I recommend that you try to limit as much as possible "direct access". Use data beans as much as possible, eventually I will get to entity frameworks and what ORM means, and this is like data beans on database steroids.
Okay I know I talked a whole lot and didn't give much code. I'll do that next visit. I'm just not strong enough yet to really do one of my go for the gusto posts where I talk forever and then code forever. Maybe when I get over the flu completely I will come back to the twenty page posts.
cheers!
Well, I'm on the mend now, not entirely mind you, so I figure I would get back to JSPs.
You might remember waaaaayyyyy back when I talked about servlets? Well today, what I'm going to cover real quick is creating a servlet that will forward us to another JSP.
Basically, what the servlet will do when you try to access it is "forward" the request. That's pretty much it.
So the overview is this, index.jsp will have a link that will send us to to ContactKeeper/App servlet. The servlet will then send us to the welcome.jsp page.
The servlet will become the main hub for our application. Basically, anytime we click on a link within the ContactKeeper application, it will just basically send us back to the ContactKeeper/App servlet.
In fact, let's skip the coding for now, I will get to that tomorrow. For now let's learn a little theory.
The reason for this, primarily, is so that our application logic can be stored in the Servlet code. Our display logic will be stored in the JSPs that we create. This separation is the starting point for something known as Model-View-Controller or (MVC) for short.
Like I said we created beans so that we store data logic in Java code outside of the JSP. Thus our JSPs focus more on just display and page control and the beans deal with storing the information.
At the moment our beans don't do much, they just store the information in memory. However, we could easily change that so that we store the data in something like a database.
Our JSPs handle page control at the moment which is basically done via tags which is standard HTML stuff. However, this pretty much leaves us in linear mode for page logic, which granted for an address book, you don't need a whole lot of logic.
However, what if we needed more powerful logic? Javascript? No way! Putting Java code in the JSP? No way! We're trying to get away from that. The goal would be to allow some piece of Java code decide where the application should go next based on the current session's values. Enter the Servlet as the central hub.
To get an overview of what this looks like, here is a rough draft of what we will be doing. (Shout out to http://www.draw.io, you all rock!)
![]() |
Quick overview what exactly we will be doing. |
The servlet can send these request for data to the Data Access Object (DAO). The DAO will handle all the little details about the actual data, so the servlet may ask to add a contact. The DAO will actually know how to do this. The DAO sends back to the servlet a pass or fail result, and then the servlet will forward the request to the proper JSP.
The servlet will pass to the JSP an entry point in the DAO to see the detail results of what was requested. (Why a name couldn't be added, the name has been successfully added, the listing of all contacts, etc...) The JSP will use that entry point to display the results from the DAO.
As you can see each section is concerned with one part of logic. The Model deals with handling all of the data ins and outs. It creates data, removes data, and so on. It is the data handler.
The Controller makes sure that everything happens in a controlled manner. If the model says that a name cannot be added, the controller forwards the client to the error page. However, do note, that the Controller doesn't actually check to see if the incoming data is valid or not, that is the job of the Model. The controller simply passes the data to the correct department to be handled and if the data is invalid, let's the user know that.
The view is what our users see. It is primarily concerned with displaying what is going on and what has been requested. The view presents all the forms our users will be entering and formats all of the data for the user that is sent to us from our Model. Forms that get filled out and submitted are sent to the controller for processing, from there the controller may delegate the processing of a form to some other subsystem and so on...
So while the MVC architecture looks a bit confusing at first, it provides a method for separating the major functions of a web application into manageable bits. Each bit is pretty independent of the other.
For example, we can change our JSPs to have a new style without messing up any of the navigation code or how we access a database. We can change our system from a in-memory style system to an actual database so long as the DAO keeps the same interface for the controller to call. We can implement a new navigation scheme by changing the controller, without messing up our JSPs or our data access.
The ability to break into independent pieces is a requirement for service flexibility.
You might notice that in my model I have the DAO using data beans and direct access. Using direct access is sometimes a necessary evil in models. Especially if your data requires a lot of calling stored procedures to get the data. However, I recommend that you try to limit as much as possible "direct access". Use data beans as much as possible, eventually I will get to entity frameworks and what ORM means, and this is like data beans on database steroids.
Okay I know I talked a whole lot and didn't give much code. I'll do that next visit. I'm just not strong enough yet to really do one of my go for the gusto posts where I talk forever and then code forever. Maybe when I get over the flu completely I will come back to the twenty page posts.
cheers!
Wednesday, December 12, 2012
Sunday, December 09, 2012
Little break.
As you all may have guessed, I'm taking a bit of a break for the moment.
I'll pick back up Monday.
However, if you are new to Java you may want to read up on what exactly clone()does by checking out the Wikipedia page for it.
The reason for this is in our contact keeper web application that we will build, we are going to implement the ability to copy a contact.
Also, you may want to get familiar with what CRUD means. Because other than the copy a contact function, we are going to stick pretty close to having a fully CRUD web application.
Cheers!
I'll pick back up Monday.
However, if you are new to Java you may want to read up on what exactly clone()does by checking out the Wikipedia page for it.
The reason for this is in our contact keeper web application that we will build, we are going to implement the ability to copy a contact.
Also, you may want to get familiar with what CRUD means. Because other than the copy a contact function, we are going to stick pretty close to having a fully CRUD web application.
Cheers!
Monday, December 03, 2012
Read-Write Bean and JSP
Okay this will have to be a quickie because I have to be on site in six hours.
Okay we are going to create a simple test of creating a read-write bean. Let's go ahead and in our ContactKeeper project create a new bean called com.blogger.contacts.beans.SimpleNameBean
Now your SimpleNameBean should have two fields, a firstName and a lastName field. Generate your getters and setters this time in the wizard as opposed to just getters. In the default constructor set the firstName and lastName fields to some value. You should end up with this as your Java code:
Now let's go ahead and create a new JSP called testname.jsp. Here's the code for the JSP page and I'll explain each part:
Okay so this again is our JSP 2.0 page using the full out XML syntax (Also, let me know [if anyone is reading this] if you prefer the full XML syntax or the old JSP tag syntax. I know the XML syntax can be a bit verbose and I'm considering dropping it because it takes up a ton of space and is really hard to type and hit all the finer points.)
Which I bring up those finer points because one of the things you will need to do with all that XML is change one of the attribute in the jsp:directive.page tag near the top. You will need to change the "session" attribute from false to true. What this tells the JSP compiler is that the JSP plans to use sessions and that all the needed stuff to make that happen needs to be created. To save on overhead, some JSPs can be written so that they don't take part of sessions, however, we are going to need to use sessions in order to remember values every time we click the "Submit" button.
Okay so you see the jsp:useBean tag, which shouldn't be new here, but notice that the scope is now set to session as oppose to page. The reason being is that the bean will need to exist in the session as oppose to a new bean being created for every time you view the page. This is also why the JSP needs to take part in sessions. By putting the bean in the session scope, it will remember the values in the bean between page views.
The next tag is a new one. jsp:setProperty. This is much like the jsp:getProperty, but instead uses the setters. Notice that I've set the "property" attribute to "*". This is a special token for this attribute. The "*" means that it will do it's best to try to match names to fields. This can save you a lot of time and can also cause you a lot of headache. It's one of those double edge sword things.
Moving on down, you see the EL for outputting the name in the paragraph tag. Nothing new here. The next part is pretty much your standard HTML input form. You'll notice that the name attributes for the text inputs has been set to my field names. The jsp:setProperty tag should take care of the matching up here. The submit button is your run of the mill HTML submit button that will redirect you to the page that you're currently on, so you really don't go anywhere when you click the "Submit" button.
When you do click the "Submit" button, the jsp:setProperty tag goes to work. It finds the HTML form and searches inside of it for field name match ups, if it finds a match, it calls the matching setter method. Once the jsp:setProperty tag is all done with it's work, the web container moves to the page given in the action attribute. Because the bean is session scope, the values that were pushed to the bean by the jsp:setProperty remain. The page comes back with the new first and last names now!
Ta-Da!
Like I said this was going to be a real quickie. I hope this has shown you a bit about read-write beans. We'll get a little more advance on the next round.
Cheers!
Okay we are going to create a simple test of creating a read-write bean. Let's go ahead and in our ContactKeeper project create a new bean called com.blogger.contacts.beans.SimpleNameBean
Now your SimpleNameBean should have two fields, a firstName and a lastName field. Generate your getters and setters this time in the wizard as opposed to just getters. In the default constructor set the firstName and lastName fields to some value. You should end up with this as your Java code:
package com.blogger.contacts.beans; public class SimpleNameBean { private String firstName; private String lastName; public SimpleNameBean() { this.firstName = "First Name"; this.lastName = "Last Name"; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }Pretty cut and dry code here, however, by having setter methods you make your bean opened up to being written to.
Now let's go ahead and create a new JSP called testname.jsp. Here's the code for the JSP page and I'll explain each part:
<?xml version="1.0" encoding="UTF-8" ?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:c="http://java.sun.com/jsp/jstl/core" version="2.0"> <jsp:directive.page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="true"/> <jsp:output doctype-root-element="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" omit-xml-declaration="true" /> <jsp:useBean id="namebean" class="com.blogger.contacts.beans.SimpleNameBean" type="com.blogger.contacts.beans.SimpleNameBean" scope="session"></jsp:useBean> <jsp:setProperty property="*" name="namebean"/> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Insert title here</title> </head> <body> <p> Welcome ${namebean.firstName} - ${namebean.lastName} </p> <form method="post" action="testname.jsp"> Enter new first name: <input type="text" name="firstName" /> < br /> Enter new last name: <input type="text" name="lastName" /> < br /> <input type="submit" name="action" value="Submit"/> </form> </body> </html> </jsp:root>
Okay so this again is our JSP 2.0 page using the full out XML syntax (Also, let me know [if anyone is reading this] if you prefer the full XML syntax or the old JSP tag syntax. I know the XML syntax can be a bit verbose and I'm considering dropping it because it takes up a ton of space and is really hard to type and hit all the finer points.)
Which I bring up those finer points because one of the things you will need to do with all that XML is change one of the attribute in the jsp:directive.page tag near the top. You will need to change the "session" attribute from false to true. What this tells the JSP compiler is that the JSP plans to use sessions and that all the needed stuff to make that happen needs to be created. To save on overhead, some JSPs can be written so that they don't take part of sessions, however, we are going to need to use sessions in order to remember values every time we click the "Submit" button.
Okay so you see the jsp:useBean tag, which shouldn't be new here, but notice that the scope is now set to session as oppose to page. The reason being is that the bean will need to exist in the session as oppose to a new bean being created for every time you view the page. This is also why the JSP needs to take part in sessions. By putting the bean in the session scope, it will remember the values in the bean between page views.
The next tag is a new one. jsp:setProperty. This is much like the jsp:getProperty, but instead uses the setters. Notice that I've set the "property" attribute to "*". This is a special token for this attribute. The "*" means that it will do it's best to try to match names to fields. This can save you a lot of time and can also cause you a lot of headache. It's one of those double edge sword things.
Moving on down, you see the EL for outputting the name in the paragraph tag. Nothing new here. The next part is pretty much your standard HTML input form. You'll notice that the name attributes for the text inputs has been set to my field names. The jsp:setProperty tag should take care of the matching up here. The submit button is your run of the mill HTML submit button that will redirect you to the page that you're currently on, so you really don't go anywhere when you click the "Submit" button.
When you do click the "Submit" button, the jsp:setProperty tag goes to work. It finds the HTML form and searches inside of it for field name match ups, if it finds a match, it calls the matching setter method. Once the jsp:setProperty tag is all done with it's work, the web container moves to the page given in the action attribute. Because the bean is session scope, the values that were pushed to the bean by the jsp:setProperty remain. The page comes back with the new first and last names now!
Ta-Da!
Like I said this was going to be a real quickie. I hope this has shown you a bit about read-write beans. We'll get a little more advance on the next round.
Cheers!
Using JSTL and why I lie.
I cannot keep to a script to save my life.
So I keep talking about some better application but I've picked to go over JSTL first and we will move on to the other later. Sorry I lied, but I think that getting some background on JSTL will help you out a bit. Besides, you've got to know how to add tag libraries to your project!
Okay so in the last post I covered how to download the JSTL 1.2 (which is the current version) libraries. These two JAR files provide a basic JSTL 1.2 implementation. The JSTL 1.2 is a spec (I believe that it is JSR-52, but don't quote me on that, I didn't look it up) and there are maybe two or three different implementations of that spec. All of them work pretty much the exact same as the others, so any implementation is going to be boss here. The Apache Tomcat team has yet to build their own implementation so your going to have to seek outside sources for this. I choose the Glassfish Project's implementation because I pretty much use Glassfish all the time. I'm sure you could use Red Hat's implementation.
Anyway, getting off topic here. You need these JARs to have JSTL. JSP Standard Tag Library defines a set of tags that can be used in JSP pages to expose pretty freaking basic functionality that we've been beating around. These tags, combined with EL (which I briefly talked about in this post) allow web developers to express page logic in JSP development. This is the kind of logic like, having a particular piece of HTML repeat a set amount of times (if you were showing records or a list of things), turn on or off UI elements based on the status of your java beans or servlets (like if a shopping cart was empty), and a whole lot of other page related logic. Using JSTL makes this easy for web developers because it is expressed as tags much like HTML, which is what web developers are more accustom to working with. This avoids have scriptlets or other Java like stuff in pages (because remember, code in web pages is harder to maintain, than code in other places.)
So once you have the libraries it's time to decide where to put them. With Tomcat and for that matter pretty much every single Java Web/Application server, you usually can put libraries in one of two locations. The first is within your project so that the libraries are available to your application and only your application. The second is in the server's classpath, this makes the libraries available to every application on your server, whether they need it or not. Now I know some people would say that the choice is a no brainier in the server's classpath, for the simple fact of not having a ton of copies of the same libraries on your server. However, consider this, while the JSTL may not cause this, some class libraries or tag libraries may cause some applications to break. So if you have multiple applications on your server, you could break one of them by having the server's classpath bring in changes that the application wasn't expecting. Of course the converse is, very rarely do people have multiple applications per server (there are cases mind you), however, usually it goes down that each instance of Tomcat is a single application and a machine just runs multiple instances of Tomcat. If that's the case, then there is very little advantage to the per application approach, or for that matter in the server classpath approach as both options are the same.
For now, I'm going to show you the per application approach. I'll put up instructions if you want to go the per server approach. The reason being is that most development boxes use the per application approach, for pretty obvious reasons.
Okay, enough blah, blah, blah. Let's start an entire new web application. Remember how to do that? Here's that post. You don't have to actually follow the step where you make a servlet. I will call this project "ContactKeeper", guess what I have in mind for my next project to talk about.
Okay so you have a blank web project called contact keeper. Let's move the JSTL JAR's into our project. According to the rules (the web container spec, I have no idea what JSR that is) we MUST put these files into the [project]/WEB-INF/lib folder. Otherwise, the server is free to ignore the JAR completely, and most web containers WILL ignore JARs found outside of this folder.
As you can see, the Eclipse wizard automatically creates this folder (and also the META-INF folder which is where you put your Java code side libraries).
One of the craziest things people new to Eclipse stress about is how the heck to copy files into a project. I'll have to admit, coming from Netbeans, I found this to be a bit quirky to say the least. Go ahead and select your lib folder there and right mouse click. You will see an entry on the context menu called Import... Select that and you get a dialog asking what kind of import you want to do. For the longest time I thought that Archive File was the way to go, but no, the correct answer is File System. (Reason being that I thought that is that JAR is short for Java Archive).
Now go ahead and click Next, you will see a From Directory text box with a browse button beside it, just click on that browse button and move to the directory where you have the libraries stored. Once there, click OK and you should now see everything populate in the dialog like this:
Now everything just seems so logical once you figure that part out. Check the files that you want to import, which are the two files that I have in the directory. Double check to make sure that you are importing these files into [project name]/WebContent/WEB-INF/lib. Once you have done so, click finish and the files will be imported into your project. Yes that means that if you delete the source files from the Download directory, you will still have a copy of the files in your local project. You should be able to now expand the lib folder and see the two JARs there.
Now you are ready to create your first JSP using the new JSTL tag library. Let's create a Java bean called PeopleList first, I'm going to put it into the package, "com.blogger.contacts.beans". To create a bean refer to this post. In this bean we are going to create a collection list of Strings. To do so add this code for a field.
private List peopleList;
You should get a wavy line under List. You want to import the java.util.List class into your bean, which you can do using the quick fix. The java.util.List is considered a "Collection". I won't really get too deep into what that means, but is allows you to group a lot of similar things together in a way that is much better than arrays. I really recommend that you use collections, unless you are really on a memory strap budget, or you just want a really simple structure without all the fancy frills of collections. Collections do come with a bit of overhead in return for ease.
Go ahead and create a getter for this field, we're going to make it read-only for the time being. Now the last thing we need to do is actually fill this list with some data so that we can use it. We will do that in the constructor. Now List is an abstract class, we need to add a concrete class before we can use the list. For simplicity we are just going to use ArrayList as our concrete class.
Just as an aside here: Abstract classes are there because they expose a common interface. All lists allow you to add items, remove items, clear the list, see how big the list is, and so forth. A concrete class deals with the actual implementation of that interface. An ArrayList is basically a regular Java array storage with all the methods that List exposes bolted on. As a counter example, LinkedList is not implemented as a regular Java array, instead it is indeed a linked up listing of actual objects. The difference is, an ArrayList is harder to sort and insert in the middle of, because a temporary Java array has to be created to sort things, or to shuffle items down the in the array. A LinkedList is much faster at those things, but takes more memory to just keep the structure, an ArrayList would use more memory if you were constantly shuffling things around, but uses less memory if the data just sits there most of the time. There are all kinds of abstract and concrete classes in the Collections library, that represent all kinds of different data models. Some models are better suited for different applications, which is literally a whole year's course of college to explain, so if you really want to know more about data structures, there is no shortage of books and opinions out there for your to read up on, but it's W-A-Y out of scope here.
Ahem, so let's add this code to our constructor.
this.peopleList = new ArrayList();
this.peopleList.add("John");
this.peopleList.add("Bill");
this.peopleList.add("Frank");
this.peopleList.add("Betty");
this.peopleList.add("Mary");
this.peopleList.add("Jill");
This code should be pretty clear here. Basically, we make our peopleList concrete so that we can use it. Then we start adding some names to the list. The final bit of code for your bean should look like this:
Now we are going to create a simple JSP page that will use this bean. So go ahead and create a JSP page (named index.jsp, obviously), but this time on the second step use the full-out JSP 2.0 XML style. This should be the last entry in the dialog box.
You will see near the top of the newly created page the jsp:root element. This is the core element of every JSP page using the 2.0 standard. Basically, this tells the JSP compiler that you are using the new syntax over the old stuff. In that jsp:root element we need to add the namespace of our tag library to the page so that the JSP compiler imports those tags for use in this page. Your jsp:root element should look like this:
As you can see I've added the xmlns:c stuff. This means that anything prefixed with c will be using JSTL core tag library as opposed to the jsp built in library. Autocomplete and what-not, will work for you on the c namespace just as it has for you on the jsp namespace. Now go ahead and make your JSP page look like the following, I'll explain later:
Okay a lot going on here. First you notice the jsp:useBean tag that brings the bean into the page so that we can use it. The next thing is this new c:forEach tag! Remember that the c means that this tag comes from the JSTL core tag library. The JSTL core forEach tag allows you to iterate through an array or Collection. For each item found in the array or Collection, the code between the open and close forEach tag is repeated.
You will notice a "var" attribute. Basically, when we find an item in the collection, that item that is currently selected becomes a value known as "i" in this case, you could have called it something more logical. The next attribute is the "items" attribute. This is either the Collection or array that you want the forEach tag to run through, you'll notice that I've used EL. You have to. The EL returns databean.peopleList, which is our collection's getter method. You use EL here because the JSTL doesn't allow you to use another tag (like jsp:getProperty) in the attributes. This is why I said earlier that EL is not exactly like a replacement for jsp:getProperty, it has it's own engine and everything. That's why EL can figure out that we need the getter method here.
Okay so moving on is the next tag, c:out. This one is pretty simple, it basically take an expression and outputs the result. If the result of the expression isn't a String object, then the toString() method is called. EL again is used in the "value" attribute. The reason being is that we need to resolve the expression "i". If we just typed the letter i, the the output would be the literal letter i. I put a BR tag right after that so that each entry appears on a line. We close our c:forEach tag. Let's run this program and see what happens!
Ta-da as you can see, each name in the Collection is placed onto the web page. Now you can see why JSTL is really freaking important. Trying to do that same thing would have required a scriptlet, which would have really tied the Java bean code to the web page code. If someone came in and changed the Java bean code, we would have had to update our page code as well. At least here, we've separated the two enough that non-major changes will require no changes to the web page. You can easily change the code to be a List if you wanted and no changes to the web code would be needed.
There are a lot more tags in the code JSTL and there are more sections than just the core to JSTL. I'll get to those as I go, but for now, you can start to get the idea of where I'm heading with this.
Cheers!
So I keep talking about some better application but I've picked to go over JSTL first and we will move on to the other later. Sorry I lied, but I think that getting some background on JSTL will help you out a bit. Besides, you've got to know how to add tag libraries to your project!
Okay so in the last post I covered how to download the JSTL 1.2 (which is the current version) libraries. These two JAR files provide a basic JSTL 1.2 implementation. The JSTL 1.2 is a spec (I believe that it is JSR-52, but don't quote me on that, I didn't look it up) and there are maybe two or three different implementations of that spec. All of them work pretty much the exact same as the others, so any implementation is going to be boss here. The Apache Tomcat team has yet to build their own implementation so your going to have to seek outside sources for this. I choose the Glassfish Project's implementation because I pretty much use Glassfish all the time. I'm sure you could use Red Hat's implementation.
Anyway, getting off topic here. You need these JARs to have JSTL. JSP Standard Tag Library defines a set of tags that can be used in JSP pages to expose pretty freaking basic functionality that we've been beating around. These tags, combined with EL (which I briefly talked about in this post) allow web developers to express page logic in JSP development. This is the kind of logic like, having a particular piece of HTML repeat a set amount of times (if you were showing records or a list of things), turn on or off UI elements based on the status of your java beans or servlets (like if a shopping cart was empty), and a whole lot of other page related logic. Using JSTL makes this easy for web developers because it is expressed as tags much like HTML, which is what web developers are more accustom to working with. This avoids have scriptlets or other Java like stuff in pages (because remember, code in web pages is harder to maintain, than code in other places.)
So once you have the libraries it's time to decide where to put them. With Tomcat and for that matter pretty much every single Java Web/Application server, you usually can put libraries in one of two locations. The first is within your project so that the libraries are available to your application and only your application. The second is in the server's classpath, this makes the libraries available to every application on your server, whether they need it or not. Now I know some people would say that the choice is a no brainier in the server's classpath, for the simple fact of not having a ton of copies of the same libraries on your server. However, consider this, while the JSTL may not cause this, some class libraries or tag libraries may cause some applications to break. So if you have multiple applications on your server, you could break one of them by having the server's classpath bring in changes that the application wasn't expecting. Of course the converse is, very rarely do people have multiple applications per server (there are cases mind you), however, usually it goes down that each instance of Tomcat is a single application and a machine just runs multiple instances of Tomcat. If that's the case, then there is very little advantage to the per application approach, or for that matter in the server classpath approach as both options are the same.
For now, I'm going to show you the per application approach. I'll put up instructions if you want to go the per server approach. The reason being is that most development boxes use the per application approach, for pretty obvious reasons.
Okay, enough blah, blah, blah. Let's start an entire new web application. Remember how to do that? Here's that post. You don't have to actually follow the step where you make a servlet. I will call this project "ContactKeeper", guess what I have in mind for my next project to talk about.
Okay so you have a blank web project called contact keeper. Let's move the JSTL JAR's into our project. According to the rules (the web container spec, I have no idea what JSR that is) we MUST put these files into the [project]/WEB-INF/lib folder. Otherwise, the server is free to ignore the JAR completely, and most web containers WILL ignore JARs found outside of this folder.
As you can see, the Eclipse wizard automatically creates this folder (and also the META-INF folder which is where you put your Java code side libraries).
![]() |
The WEB-INF/lib folder |
![]() |
This is the correct answer. |
![]() |
There now we are ready to import in the JAR files. |
Now you are ready to create your first JSP using the new JSTL tag library. Let's create a Java bean called PeopleList first, I'm going to put it into the package, "com.blogger.contacts.beans". To create a bean refer to this post. In this bean we are going to create a collection list of Strings. To do so add this code for a field.
private List
You should get a wavy line under List. You want to import the java.util.List class into your bean, which you can do using the quick fix. The java.util.List is considered a "Collection". I won't really get too deep into what that means, but is allows you to group a lot of similar things together in a way that is much better than arrays. I really recommend that you use collections, unless you are really on a memory strap budget, or you just want a really simple structure without all the fancy frills of collections. Collections do come with a bit of overhead in return for ease.
Go ahead and create a getter for this field, we're going to make it read-only for the time being. Now the last thing we need to do is actually fill this list with some data so that we can use it. We will do that in the constructor. Now List
Just as an aside here: Abstract classes are there because they expose a common interface. All lists allow you to add items, remove items, clear the list, see how big the list is, and so forth. A concrete class deals with the actual implementation of that interface. An ArrayList is basically a regular Java array storage with all the methods that List exposes bolted on. As a counter example, LinkedList is not implemented as a regular Java array, instead it is indeed a linked up listing of actual objects. The difference is, an ArrayList is harder to sort and insert in the middle of, because a temporary Java array has to be created to sort things, or to shuffle items down the in the array. A LinkedList is much faster at those things, but takes more memory to just keep the structure, an ArrayList would use more memory if you were constantly shuffling things around, but uses less memory if the data just sits there most of the time. There are all kinds of abstract and concrete classes in the Collections library, that represent all kinds of different data models. Some models are better suited for different applications, which is literally a whole year's course of college to explain, so if you really want to know more about data structures, there is no shortage of books and opinions out there for your to read up on, but it's W-A-Y out of scope here.
Ahem, so let's add this code to our constructor.
this.peopleList = new ArrayList
this.peopleList.add("John");
this.peopleList.add("Bill");
this.peopleList.add("Frank");
this.peopleList.add("Betty");
this.peopleList.add("Mary");
this.peopleList.add("Jill");
This code should be pretty clear here. Basically, we make our peopleList concrete so that we can use it. Then we start adding some names to the list. The final bit of code for your bean should look like this:
package com.blogger.contacts.beans; import java.util.ArrayList; import java.util.List; public class PeopleList { private List<String> peopleList; public PeopleList() { this.peopleList = new ArrayList<String>(); this.peopleList.add("John"); this.peopleList.add("Bill"); this.peopleList.add("Frank"); this.peopleList.add("Betty"); this.peopleList.add("Mary"); this.peopleList.add("Jill"); } public List<String> getPeopleList() { return peopleList; } }
Now we are going to create a simple JSP page that will use this bean. So go ahead and create a JSP page (named index.jsp, obviously), but this time on the second step use the full-out JSP 2.0 XML style. This should be the last entry in the dialog box.
You will see near the top of the newly created page the jsp:root element. This is the core element of every JSP page using the 2.0 standard. Basically, this tells the JSP compiler that you are using the new syntax over the old stuff. In that jsp:root element we need to add the namespace of our tag library to the page so that the JSP compiler imports those tags for use in this page. Your jsp:root element should look like this:
As you can see I've added the xmlns:c stuff. This means that anything prefixed with c will be using JSTL core tag library as opposed to the jsp built in library. Autocomplete and what-not, will work for you on the c namespace just as it has for you on the jsp namespace. Now go ahead and make your JSP page look like the following, I'll explain later:
<?xml version="1.0" encoding="UTF-8" ?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:c="http://java.sun.com/jsp/jstl/core" version="2.0"> <jsp:directive.page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false"/> <jsp:output doctype-root-element="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" omit-xml-declaration="true" /> <jsp:useBean id="databean" class="com.blogger.contacts.beans.PeopleList" type="com.blogger.contacts.beans.PeopleList"></jsp:useBean> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Insert title here</title> </head> <body> <c:forEach var="i" items="${databean.peopleList}"> <c:out value="${i}"></c:out>< br /> </c:forEach> </body> </html> </jsp:root>
Okay a lot going on here. First you notice the jsp:useBean tag that brings the bean into the page so that we can use it. The next thing is this new c:forEach tag! Remember that the c means that this tag comes from the JSTL core tag library. The JSTL core forEach tag allows you to iterate through an array or Collection. For each item found in the array or Collection, the code between the open and close forEach tag is repeated.
You will notice a "var" attribute. Basically, when we find an item in the collection, that item that is currently selected becomes a value known as "i" in this case, you could have called it something more logical. The next attribute is the "items" attribute. This is either the Collection or array that you want the forEach tag to run through, you'll notice that I've used EL. You have to. The EL returns databean.peopleList, which is our collection's getter method. You use EL here because the JSTL doesn't allow you to use another tag (like jsp:getProperty) in the attributes. This is why I said earlier that EL is not exactly like a replacement for jsp:getProperty, it has it's own engine and everything. That's why EL can figure out that we need the getter method here.
Okay so moving on is the next tag, c:out. This one is pretty simple, it basically take an expression and outputs the result. If the result of the expression isn't a String object, then the toString() method is called. EL again is used in the "value" attribute. The reason being is that we need to resolve the expression "i". If we just typed the letter i, the the output would be the literal letter i. I put a BR tag right after that so that each entry appears on a line. We close our c:forEach tag. Let's run this program and see what happens!
![]() |
Output of our new web application |
There are a lot more tags in the code JSTL and there are more sections than just the core to JSTL. I'll get to those as I go, but for now, you can start to get the idea of where I'm heading with this.
Cheers!
Sunday, December 02, 2012
JSTL 1.2 tag libraries for Tomcat 7
OMG! Trying to find stable taglibs for Tomcat is like pulling teeth.
Fear not! If you are looking for JTSL 1.2 libraries for Tomcat 7, since Tomcat doesn't ship with any, then you can actually pull the JSTL libraries from the Glassfish project and use them in Tomcat. The libraries are top notch, so I recommend that you use them.
Here are the links to the files, note: these are not directly from the Glassfish projects website , these are from the mvnrespository.
JSTL-API version 1.2 -- Link
JSTL-IMPL version 1.2 -- Link
So what is JSTL you may ask? It is the JSP Standard Tag Library. You've been seeing the jsp:useBean tag and what-not. The jsp namespace has been using the "built-in" tag library. Now it is time to bring in some more tags that we can use. The JSTL is an essential tag library for everyone to know.
Pretty much every server out there includes the built in tag library (jsp) and usually includes the JSTL. Tomcat is the exception to this, however, it comes only with the built in library. Apache is working on their implementation of the JSTL version 1.2, but no telling when that will ever make it out. So we're just going to borrow the Glassfish project's implementation of the JSTL.
As you can guess, there are tons of other tag libraries out there that do all kind of stuff. Each one is a little niche, some are pretty wide known. However, all JSP developers need to know JSTL. It's just like C++ programmers needing to know the standard template library (STL).
So, I'll go over how to use these in the next post. Or something.
Cheers!
Fear not! If you are looking for JTSL 1.2 libraries for Tomcat 7, since Tomcat doesn't ship with any, then you can actually pull the JSTL libraries from the Glassfish project and use them in Tomcat. The libraries are top notch, so I recommend that you use them.
Here are the links to the files, note: these are not directly from the Glassfish projects website , these are from the mvnrespository.
JSTL-API version 1.2 -- Link
JSTL-IMPL version 1.2 -- Link
So what is JSTL you may ask? It is the JSP Standard Tag Library. You've been seeing the jsp:useBean tag and what-not. The jsp namespace has been using the "built-in" tag library. Now it is time to bring in some more tags that we can use. The JSTL is an essential tag library for everyone to know.
Pretty much every server out there includes the built in tag library (jsp) and usually includes the JSTL. Tomcat is the exception to this, however, it comes only with the built in library. Apache is working on their implementation of the JSTL version 1.2, but no telling when that will ever make it out. So we're just going to borrow the Glassfish project's implementation of the JSTL.
As you can guess, there are tons of other tag libraries out there that do all kind of stuff. Each one is a little niche, some are pretty wide known. However, all JSP developers need to know JSTL. It's just like C++ programmers needing to know the standard template library (STL).
So, I'll go over how to use these in the next post. Or something.
Cheers!
Expression Language quickie!
Okay I'll make this post really quick!
Let's head back to our project that we've been working on and open up index.jsp.
Change your code to look like this...
Here what I've done is replace our jsp:getProperty code with what is known as expression language, or better known as EL.
The nice thing is that Tomcat 7 supports EL out of the box. Now I know that you are tempted to think that EL is just a simple replacement for getters, but as you can see in my code I've done some addition. You can do mathematical operations in EL to things that make sense. That can cast to a numeric automatically. So that basically limits you to floats, ints, doubles, and what not.
However, the cool thing about EL is that you can also do logic within EL. That's right you can compare things in equality, or less than/great than, or other types of logical testing. In addition, you can call methods and access arrays in EL. EL is a pretty important thing in the world of JSP 2.
So here's what we've done so far:
We started at JSP 1.0 with the <% %> tags, which eventually we will drop completely to come fully into JSP 2.
We started using beans as opposed to scriptlets, which brings us deeper into JSP 2.
We are now using EL which will help us understand some new concepts in JSP 2.
As you can see, brick by brick we are tearing down JSP 1.0 and moving to the world of JSP 2. The next thing I want to do it show you how to use servlets, JSP 2, EL, and beans together to make a more interactive web application.
Cheers!
Let's head back to our project that we've been working on and open up index.jsp.
Change your code to look like this...
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <jsp:useBean id="mybean" type="com.blogger.beans.HelloBean" class="com.blogger.beans.HelloBean" scope="page"></jsp:useBean> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <p> ${mybean.currentDate}<br /> ${mybean.randomNumber}<br /> ${mybean.randomNumber+5}<br /> ${mybean.someMessage} </p> </body> </html>
Here what I've done is replace our jsp:getProperty code with what is known as expression language, or better known as EL.
The nice thing is that Tomcat 7 supports EL out of the box. Now I know that you are tempted to think that EL is just a simple replacement for getters, but as you can see in my code I've done some addition. You can do mathematical operations in EL to things that make sense. That can cast to a numeric automatically. So that basically limits you to floats, ints, doubles, and what not.
However, the cool thing about EL is that you can also do logic within EL. That's right you can compare things in equality, or less than/great than, or other types of logical testing. In addition, you can call methods and access arrays in EL. EL is a pretty important thing in the world of JSP 2.
So here's what we've done so far:
We started at JSP 1.0 with the <% %> tags, which eventually we will drop completely to come fully into JSP 2.
We started using beans as opposed to scriptlets, which brings us deeper into JSP 2.
We are now using EL which will help us understand some new concepts in JSP 2.
As you can see, brick by brick we are tearing down JSP 1.0 and moving to the world of JSP 2. The next thing I want to do it show you how to use servlets, JSP 2, EL, and beans together to make a more interactive web application.
Cheers!
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.
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!)
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?
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.)
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.
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.
There you go, you have now "wired" the bean into your JSP!
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.
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:
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.
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.
Cheers!
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.
- Current Date/Time
- Random number
- 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 |
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. |
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. |
![]() |
Using auto-complete, as you can see the default value of this attribute will be page |
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)
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. |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <jsp:useBean id="mybean" type="com.blogger.beans.HelloBean" class="com.blogger.beans.HelloBean" scope="page"></jsp:useBean> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <p> <jsp:getProperty property="currentDate" name="mybean"/><br /> <jsp:getProperty property="randomNumber" name="mybean"/><br /> <jsp:getProperty property="someMessage" name="mybean"/> </p> </body> </html>
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. |
![]() |
Location of refresh button |
Cheers!
Subscribe to:
Posts (Atom)