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.


<?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!)

Quick overview what exactly we will be doing.
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!

Wednesday, December 12, 2012

Sick

Sorry came down with the flu. Be back soon.

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!

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:

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).

The WEB-INF/lib folder
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).

This is the correct answer.
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:

There now we are ready to import in the JAR files.
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:

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
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!

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!

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...

<%@ 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.

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

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

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

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

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

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

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

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

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

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

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

Here's the final code for our class:

package com.blogger.beans;

import java.util.Date;

public class HelloBean {

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

 public Date getCurrentDate() {
  return currentDate;
 }

 public Integer getRandomNumber() {
  return randomNumber;
 }

 public String getSomeMessage() {
  return someMessage;
 }

}

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

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

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

The tag that we wish to use is

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

Using auto-completion

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

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

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

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

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

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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    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.
You should see your web page appear with all the information.  You can click the refresh button to see the information updated with every page.

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

Cheers!