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!

Friday, November 30, 2012

JSP so you don't kill yourself

OMG you could never do a webpage in servlet!!

You are absolutely correct.  You could not realistically do an entire website in servlets.  So what gives?  Why even use this technology in the first place?!

Ah bear with me here.  For now I'm going to show you some basic JSP and when I mean basic, I mean old school baby!  However, it's good to have a good foundation.  So why didn't I show you Servlet 2.5, which is still supported by Tomcat?  I'll get to it, it was actually easier to show Servlet 3 first before anything else, that's how far Servlet has come in its life.

So JSP = Java Server Pages.  Tomcat has a third piece to it called a JSP compiler.  This JSP compiler takes a JSP page and creates a servlet from it.  I know cool!  The JSP can be a mix of Java code and HTML/CSS/JavaScript and if you have ever used PHP, you wouldn't be wrong to say that JSP looks a lot like JSP.

So let's write a basic JSP page that shows us the current date/time and says "Hello, World!".

We are going to continue to use our project called helloone.  First head over to the Project Explorer (on the left) pane and right mouse click on the WebContent folder.  Select New → JSP Page.  No I won't make you make a shell of a JSP page the hard way.  On the first dialog we are going to choose the location and the file name.  The location should be in the root of the WebContent folder and we are going to call this page, index.jsp.  I know how surprising.

Click next and you'll get another dialog.  On this dialog, you get to select a template.  There are JSF templates, which I will get to soon enough, and then there are like four or five type of JSP templates.  Right now we are going to learn the New JSP File (html) version.  This is the old school version.  Now click finish and the new semi-blank JSP page should appear in your code window.

Select location and file name
Select JSP template to begin with.
So let's type a bit into this code window.  Here's the code and I'll explain after the bump.

<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <h3>This is the JSP version.</h3>
 <h1><%= new java.util.Date() %></h1>
 <p>Hello, World!</p>
</body>
</html>

As you can see I've added an H3 tag, so we can tell the difference between our JSP version of this and our servlet version of this.  I've added a H1 tag with a weird tag enclosed by it.  And of course our "Hello, World!".

If you look closely you'll notice a tag at the top that is <%@ %> that was added by the template.

Let's go over each and all of the JSP tags while we're at it.

Type of tag What it means
<%@ %> JSP Directive — This is usually followed by an action or target like <%@ page %> or <%@ import %> These modify how the servlet is compiled.
<%= %> JSP Expression — An express is a single line of Java code, that if it is not a java.lang.String, then the toString() method is called. The JSP compiler turns these into printwriter.println([expression]);
<%! %> JSP Declaration — This expresses a piece of code that is located outside the doGet, doPost methods. If you needed your compiled servlet to have user defined methods, this be the place to put them.
<% %> JSP Scriptlets — This is code that is entered as you have typed it into the doGet and doPost method. The JSP compiler actually puts the code in a section called _jspService, but for all intents the effect is the code is inserted in verbatim into the resulting servlet.

There see, just four types of tags. I also tried to explain where a JSP compiler will put the code specified by each kind of tag into the resulting servlet.

So our first piece of JSP is a directive which will modify "page" attributes.  Here we set the content type to HTML and set the character encoding to UTF-8.  A DOCTYPE for HTML 4.01 compliance, some HTML and then we make it to the next piece of JSP code.  This is an expression, the piece of code emits a java.util.Date object, so the JSP compile will call the object's toString() method.  That converts the entire piece to:

printer_writer.println((new java.util.Date()).toString());

within the servlet.

The rest of the HTML code comes after that, and that's it.

Go ahead and save the JSP page and run the project in Eclipse.  Right mouse click on the project icon in the project explorer and choose Run as... → Run on Server.

Since this is called index.jsp, it will appear as the index page for the web application.  So you should see it by default in the Eclipse web browser.

Ta-da!  You've written your first JSP!  Now like I said this syntax is the JSP verions 1 way of doing stuff.  Eventually I'd like to show JSP 2.2 stuff as it is a lot more powerful.  However, as you can see.  Writing JSPs are a lot easier than writing servlets.  However, Servlets play a very big role in web applications.

Eclipse serves servlets on the quick.

You know I always say that it is better to learn something the manual way first before seeing it done the automatic way.  In this post, we created a servlet, but we did it the manual way.  Slowly adding the annotation, extending the class, over riding the methods we needed to over ride.

However, this isn't the 1990's.  Your IDE will do most of your work for you if you like.  When we right moused clicked you may have noticed something that I didn't touch on in the last post.  Here's a photo of what I'm talking about.

Wait, what?!  Add Servlet?!
Yes, that is correct.  Eclipse has a wizard for adding servlets to your project.  So let's go ahead and see what this wizard does by adding a Goodbye servlet.

Here's step 1 of the wizard:

Basic servlet properties
Here on step 1, you pick the class name of the servlet and the package it will be located in.  REMEMBER:  It is strongly recommend to not leave the package name blank, especially for web applications that are going to be facing the public web.  I cannot stress that enough.

Okay so I'm going to create my SayGoodByeServlet in the com.blogger.testing package, since I already have my SayHelloServlet in the same package.  On to step 2!

Basic Annotation properties for servlets
This step covers pretty much the stuff you'd see in the annotations, in this case the @WebServlet annotation.  When it comes to annotations it's pretty much convention over configuration.  If you change nothing here, then your @WebServlet annotation will follow convention.  Everything here is acceptable except the URL mapping.  I would like it to be "/Goodbye" so I'll click on it, click Edit and change that.

That's better
Now that we have that all setup let's move on to step 3!

The meat and potatoes of the class
Ah as you can see from this step, the wizard wants to know which methods you'd like to over ride.  By default the doGet and doPost are already selected.  Pretty much everyone on this planet is pretty convinced that at a minimum, these two should always be overridden.  I would have to agree with that, except in the case of super simple test servlets that people do on web blogs.  Pretty much you can get away with just doGet for "Hello, World!" but beyond that, you're going to at some point need doPost, to do anything useful with servlets.

Everything on this final step is fine as is, so I'll click the finish button., the generated code appears in the code editor windows.  Here's what it says:

package com.blogger.testing;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SayGoodByeServlet
 */
@WebServlet("/Goodbye")
public class SayGoodByeServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SayGoodByeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

}

As you can see the automatically generated code, is pretty much on par with the code that we wrote just the other day.  Now we can remove those TODO comments and put down some actual code that will tell our system what to do.  Publish the new information to the server and see the wonderful results.

Having a good start on manually building a servlet really helps you to understand the bits that the wizard is doing for you automatically.  So I really recommend getting a peek at how it is done manually and then come and do this and see how it is done automatically.

Cheers!

Getting examples and your first Tomcat application

The examples included with Tomcat and a bit of silliness...

Okay so now you have Tomcat integrated with Eclipse.  When you integrate with Eclipse, Eclipse keeps what's known as a "metadata" copy of Tomcat information.

The reason for this is apparent if you were using a remote Tomcat that you didn't have the configuration files on some network share that you could access.  Tomcat provides a way to "publish" a web application via an upload.  However, for security reasons, you cannot change configuration files like this.  So you have to tune the Eclipse copy of the configuration files to match the server configuration before you have an In-Sync copy of the server on the local machine.

Let's head to Eclipse and understand this a little better.  On the Server tab right mouse click on your Tomcat server and select Properties.

The Properties of the server.  Location circled in red.
As you can see from the screenshot, the location is current set to [workspace metadata].  When you start the server from Eclipse, it will use the binary program that we have in "bin/apache-tomcat" but it will use the files located in the Eclipse metadata as the web and configuration repository.

This metadata location is [wherever you have your Eclipse workspace]/.metadata/.plugins/org.eclipse.wst.server.core/tmp0

I store my workspace in ~/src/eclipse-workspace, so my metadata copy of Tomcat is located in ~/src/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0

Also note one more thing.  If you have more than one server in Eclipse, then you'll notice a tmp0, tmp1, tmp2…  The servers are numbered in the order in which they appear in Eclipse from top down.

Okay, so basically we could just change our location that we are using, but it is important to keep our copy in-sync in the Eclipse metadata.  So we are going to copy the example pages from the Tomcat install that we have in our bin folder to our copy in the metadata storage.

So head over to "bin/apache-tomcat-7.0.33/webapps/", or wherever you've extracted your Tomcat install.  There you will see the web applications that come with Tomcat.  They are:

  • docs  —  which is really just a bunch of pages of Tomcat documentation bundled up as a web application.
  • examples  —  which are the example servlets and JSPs and the code for those examples.  I'll go ahead and state that a lot of the examples are a bit out of date.
  • host-manager  —  I've never really used this web application but I believe that it allows you to control somethings in Tomcat via the web, which is silly, because that's a huge security hole.
  • manager  —  Which I think is a program that allows you to handle the web container side of Tomcat via the web.  Again, I've never used it.
  • ROOT  —  This is just a little welcome to Tomcat JSP application.  It acts as a hub for linking to all of the other web applications I just listed.
I'm sure you are starting to notice that web applications that you install in Tomcat are basically, stored in a folder and that folder is stored in the "webapps" folder.  You would be absolutely correct.  When we go to install an application into Tomcat, we simply just put the folder with all our files, images, and java classes into the webapps folder in Tomcat.  There a little more to it, like configuring connections to a database, restricting access to authenticated users and what-not, but that's the gist of very basic web applications.

So, basically what we are going to do, is copy the ROOT and examples web applications from the Tomcat folder and paste the folders into our metadata copy.

  1. Copy the ROOT and examples folder from the ~/bin/apache-tomcat-7.0.33/webapps/ folder.
  2. Paste the folders in the ~/src/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps folder.
If you get a prompt to "merge" thing just go ahead and click "OK".

Now hope back into Eclipse, start up your server from Eclipse, open browser to http://localhost:8080 and poof!  You should now see the Tomcat welcome page as oppose to the 404 error you got last time.

Making your first servlet...

And now it is time to make your very own servlet!  I know exciting!  Here's the basic breakdown.

Tomcat is expecting your Java class files to have certain hooks that it can latch onto, in order to run your Java code.  It use to be that your class would have to extend a standard base class and then you'd create an XML file that the server would read which would help it to figure out how to latch onto your class file.  It was all a very crazy mixture of XML files and Interfaces.  The nice thing about Java servlet version 3.0 is, you don't have to do that any more!  Hooray!!  There are these things now called Java annotations that you can add to your class file.  Annotations don't do anything code wise, but they allow you to mark certain sections of your code as something, sort of like HTML markup.  Basically, you can now annotate you Java class, and Tomcat will read the annotations to figure out how to hook into your Java class.

Easy stuff!  You can still do it the old way.  In fact, if you do provide an XML file, it will override whatever annotations are found.  The old way is still very useful for commercial products that just give you compiled class files and allow you to fine tune the program for your needs by editing XML files.  You obviously can't change the annotations in a compiled class file.

So our very first servlet is basically going to write to the screen, the current time and "Hello, world!".  To begin, let's click on the "New Project" button on the toolbar.  Here's a picture of the button.

This creates a new project
When you click that button, basically a dialog will appear and ask you what kind of project do you want to start.  In Eclipse, there are easily enough type of projects do keep you guessing.  The type we want to start is in the "Web" folder and is called a "Dynamic Web Project".

Dynamic Web Project
You can always use the filter box if you aren't crazy about scrolling towards the near bottom to find this folder.  Once you have it selected, click the Next button to begin setting up the project.  Now you'll get a screen with what looks like a ton of options.

This is one of three screens in the wizard but this is the only one I'll be covering for now.
In this dialog of the wizard you set the basic properties of your web project.  I'm going to call the project "helloone".  I go ahead and use the default location for the project, which would be in my workspace.  The target runtime should be our Tomcat server that we have installed.  You will notice a drop down that shows "Dynamic web module version".  Use version 3 as this is the latest version and corresponds to servlet 3.0.  We will use the default Tomcat configuration for our project (note, this is the project configuration, not the server configuration).  You don't have to worry about the other options.

Go ahead and click Finish as you won't need any of the other steps from the wizard.

You will now see your new project in the "Project Explorer".

The new project "helloone" and all the different groups under it.
Inside your project you'll see a bunch of different groups.  Like JAX-WS, WebContent, etc…  For there being a lot of stuff, your project is actually empty at the moment.  These groups are just there to help you create stuff, if you needed to create a new Web Service point in your servlet, well you can see where you'd go for that.  Right now we are just going to create a simple servlet that will print the current date/time and "Hello, World!".

A servlet is a Java resource so we will right mouse click on "Java Resources" and choose New → Class and get the "New Java Class Wizard".  We just want to create a very basic class, so just fill out the dialog as follows:

This creates a very, very basic class in Java
Basically, I am putting the class into the package called "com.blogger.testing" and the name of the class is "SayHelloServlet".  Click Finish and who should have your class appear on the coding window.

Our new class added
Now let's add some code to get to handle all the needed things for being a servlet, because at the moment our Tomcat server would have no idea what to do with this class.  Begin by placing the cursor just above the class statement (public class…) and type 

@WebServlet("/Hello")

Eclipse will underline this statement with a red wavy underline.  That means there is a problem with the code.  move you cursor so that it is somewhere within the offending code and a "quick fix" tool tip will appear.  Click on the quick fix to "import javax.servlet.annotation.WebServlet".  This will add the import statement to your class file.

Now we are going to say our class extends the basic HttpServlet class.  We need to extend this class as it brings in all the needed hooks into our class that Tomcat is expecting.  To extend our class we just need to add a bit of code.

Change this... To this...
public class SayHelloServlet public class SayHelloServlet extends HttpServlet

So basically you are just adding "extends HttpServlet" to the end of the class statement.  Eclipse will yet again, underline the new code.  Click on the code and in the quick fix, import the javax.servlet.http.HttpServlet class.

You should now see a little light bulb with a warning exclamation sign on it.

That means Eclipse wants to help you out on something.  Usually, these things won't keep your code from working but it's good form to address something here.  In this case, HttpServlet is marked Serializable, and thus your class should provide a Version UID.  It's a good idea to go ahead and do this.  I usually just go for the default value as opposed to a randomly generated one.  Click on the light bulb and make your choice.

The default UID looks like this:

private static final long serialVersionUID = 1L;

Okay now, all of the underlines and light bulbs have been dismissed.  We now have all the hooks that we need for Tomcat to interact with with our class, but at the moment, absolutely nothing will happen.  So let's make something happen!

First things, first.  Let's create a no argument constructor.  It's important that we at the very least have this going forward.  To do this in the outline pane on the right, right mouse click the class (that's the green ball C).

This is the outline pane, very useful for moving around in classes

Once you right click select Source → Generate Constructors From Superclass...  You don't really need to mess with the dialog that pops up, just click OK.  Now you have your no argument constructor.  Next we need to override the "doGet" method from HttpServlet.

The reason we will be over riding this method is that when the web server receives a HTTP GET request from a client, the web container will call this method.  By default the method does nothing, in fact, by default all of the methods do nothing.  You are going to over ride this method with your own custom method.

To over ride the method, again, right mouse click on the class in the Outline pane and select Source → Override / Implement Methods...  A dialog will appear and you should select the "doGet" method by checking the box beside it.  You can also do some automatic generation of the comments for this over ride by checking the box to do so toward the bottom of the dialog.  I usually don't however as I like my own comments on code.

You'll see that in the code editor pane the new code has been added.  Go ahead and remove the code that says:

super.doGet(req, resp);

That removes any reference to the default code of "do nothing".  Now, you are ready to implement your own response.  Take a look at my code below and I'll explain what I did right after.

package com.blogger.testing;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Hello")
public class SayHelloServlet extends HttpServlet {

 public SayHelloServlet() {
  super();
  // TODO Auto-generated constructor stub
 }

 private static final long serialVersionUID = 1L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  java.util.Date d = new java.util.Date();
  java.io.PrintWriter pw = resp.getWriter();
  resp.setContentType("text/html");
  pw.println("<html><head><title>Sample 01</title></head><body>");
  pw.println("<h1>" + d.toString() + "</h1>");
  pw.println("Hello, World!");
  pw.println("</body></html>");
 }

}

You can always remove all of those TODO comments out of the code.  As you can see.  I create a new java.util.Date called d.  That stores our date.  Next I created a PrintWriter called pw.  This will provide us a way to write to the response that will be sent back to the client.

I then start writing HTML to the print writer and I convert the date to a string so that it can be written to the print writer.

So that's about it, now let's go ahead and run this servlet and see what happens!  To run the program that we've just created, in the project explorer (remember the pane on the left), right mouse click on the top level object of our project (looks like a blue folder called helloone) and choose Run As → Run on Server option.

A run dialog will appear but you can just click on the Finish button.

And...  WAIT!  You got a 404 error!?  Of course you did.  If you look back at our code notice the @WebServlet("/Hello") part.  The part in quotes is what you need to add to the URL to get the results.  So the correct location should be…

http://localhost:8080/helloone/Hello

The helloone is the name of the web application and Hello is the name of the servlet inside the web application.

Hooray our first servlet!
Now you've had a taste of your first web servlet.  I know most likely you are thinking that this has got to be a pain to code in if I have to encode a whole web page into Java code.  However, servlets aren't exactly made for serving up pages as it is more along the lines of doing the leg work in web applications.

I will try to make it clearer as to the purpose of servlets, but for now, you've had the ability to sink your teeth into it a little bit.  I'll try not to make the post this crazy long again, but I did cover a lot of fundamentals here.

Cheers!

Thursday, November 29, 2012

Tomcat 7 and Eclipse Integration

Well it'd be a shame if you have Eclipse installed but had no servers to publish to!  So let's fix that, eh?  Let's go out there and get the most loved Java web servlet container out there...

The Apache Tomcat Server.  You can click that for the download page.

So, first thing.  Yes, this is the same place that has the Apache HTTP Server, that everyone knows and loves.  Second, what, you might ask, is a Java web servlet container?  Well it is simply put, a java environment (aka, a program that is ran in the JVM) that will listen to packets and will respond based on the configuration and Java classes that you add to it.  Tomcat serves up webpages, but you can modify how it serves them, modify the pages themselves, and even carry out all kinds of actions behind the scene, simply by dropping Java class files into specific folders in your Tomcat installation.

I won't go too deep into the history, but Servlets came about as a solution to the proliferation of CGI on the Internet.  Basically, in order to make the web more dynamic, a web server would run a program (didn't matter if it was written in Perl, Python, C, C++) and whatever the output of that program was, that's what the web server would send back to the person.  CGI just defined certain standards for how that worked.  The problem with CGI was launching a program every time someone requested it, was pretty costly for CPU and memory.  If the program was written in a script versus compiled code, oh it was worst!

Servlets allows the web server to start up in a JVM, that web server also has what is known as a "web container".  The web container is a different part of the same program that talks to the web server.  A request comes into the web server end and it checks to see if it can find a page or a container controlled resource that matches the request.  If it is a page, the web server part sends the web page on to the requester.  If it is a resource the web container handles, the web server asks the web container to do something about fulfilling the request.  The web container runs the required Java class file, gets the output, and sends it to the web server to send back to the requester.

That all sounds a lot like CGI right?  You'd be exactly right, but the difference is, the JVM is already running.  So there is no cost associated with starting up a new instance of something for each request.  The web container can intelligently handle requests, by pooling the requests together.  If we have twenty requests for the Java resource called "FOO", then it would make sense to load "FOO", run all of the requests, and then load something else.  Rather than serve the request for Java resource "BAR" after serving five requests for "FOO", while the other fifteen wait.

If you've ever used php_mod with Apache HTTP Server, then this is basically the exact same thing.  Except instead of Java, we're using PHP.  Basically the Apache HTTP Server hands off requests to the php_mod system to fulfill PHP resource request.

There are some finer detail differences that ├╝ber-geeks would argue, and also, mod_php uses PHP.  While Tomcat uses Java.  So if you're more of a Java person, then it'd make sense to sink into Java servlets rather PHP.

Anyway, let's get started on downloading us some Tomcat...

The download link was provided above, but here it is again.  We are downloading Tomcat version 7.0.33, which is the latest and greatest at the moment.  However, that link should take you to the "7" page, so the link takes you to the latest and greatest Tomcat 7 version.  So if by the time you read this, if Tomcat 7.0.46 is the newest version, the link will get you to the right place.  However, if there's a Tomcat 8 (which there isn't a stable Tomcat 8, yet), that link won't get you there.

Tomcat 7 offers Java Servlet version 3.0 and Java Server Page (JSP) version 2.2.  That might tell you squat at the moment.  However, rest assured, that those are the most recent versions of those two standards.  The standards are (in case you're curious) JSR-315 (Servlet 3.0) and JSR-245 (JSP version 2.2).

I highly recommend never, ever go back to the pre-Servlet 3.0 days.  Eventually, I hope you'll agree with me and not just because I told you so.

Okay, so you've gone to the download page.  I grab the tar.gz, but you might want to grab an installer or the zip file or what have you.  Remember that we are looking at the section that says: core.  There is also an embedded version (which does not mean it will run on a phone, it means that this version is for embedding in your own homemade Java web server program), some add-ons, and what-not.  Right now we just want the core package.

Once, you've downloaded the tarball (or zip).  You basically extract it wherever you want the server to reside.  I usually extract it in "~/bin" which is where my Eclipse install is located, however, you can put it any where.  Just remember where you placed it and make sure that you have permissions wherever you do put it, to read/write/execute.

Congrats you've just installed Tomcat, however, let's not start it up...just yet.

Eclipse integration...

Now we are going to tell Eclipse about our Tomcat install and allow Eclipse to handle starting and stopping the server.  Also this will allow us to easily publish stuff to Tomcat from Eclipse.  In a typical setup, you might have several servers listed in Eclipse.  One for local development, one for remote testing, one for demonstrations  and another as your actual production machine.  Basically, you'll write your stuff in Eclipse and just change where it gets published to as the project matures.  However, for now, we're just going to have the one.

Okay start up Eclipse, this is why we chose the EE bundle.  It is going to already have the needed plugins required to manage servers.  If you did not, download the EE bundle, then you need to install the EE plugins.  To do that, from the Eclipse main menu choose: Help -> Install New Software...

You will see a dialog like the one below appear.

The Install Dialog.

You'll see a drop box labeled, Work With.  Just drop that box and select the entry that says: Juno - http://download.eclipse.org/releases/juno.  Now the middle box will begin to populate with software that it finds at that location.  Look for the group called: Web, XML, JavaEE and OSGi Enterprise Development, basically install that whole group.  Restart Eclipse and now you have all of the EE plugins.

Once you have done that, switch over to the "Java EE" perspective in Eclipse.  A perspective is just a collection of useful tools for that type of task.  To switch to the "Java EE" perspective, if it is not your default, click the Open Perspective button and select the new perspective and click OK.

Open Perspective button circled in red.
Selecting the new perspective.
At the bottom of the IDE you will see the Servers tab.  Click on the tab, this is where we are going to tell Eclipse about our new Tomcat installation.  You do so by clicking on the link inside that panel called the New Server Wizard.

The server tab, it's a bit bare at the moment.
You'll now be presented a dialog that allows to tell Eclipse what kind of server you want to add to the Eclipse environment.  This shouldn't be rocket science here, open the "Apache" folder and look for the Tomcat v7.0 Server entry.  You can optionally use the filter box to find the entry.  If at some point in your life, you are going to be working with a sever that just doesn't come with Eclipse, there is a link on that dialog that says, Download additional server adapters.  Adapters, basically tell Eclipse how to publish to a server, how to start/stop the server, and what not.  Basically, it's just a bundle of magic that allows you to seamlessly connect Eclipse to your server.  You don't always need the adapter to develop for the platform, it just makes it a little easier as it saves you some "copy/paste" time.

Picking out the server type to add
So once you have the server type selected, click on the Next button.  Basically, this dialog asks where you installed the thing.  If we're talking about a remote server here, you still need physical access to the files (via either NFS, CIFS, SMB, or whatever) if you want to be able to change the configuration files from Eclipse.  Since ours is local, we don't have to really worry about much, except just pointing it at correct directory.

Telling Eclipse where the system is installed at.
You'll notice that if you hadn't downloaded Tomcat, Eclipse offers a button that would do just that for you, albeit the 7.0.12 version.  Once you have that information in, go ahead and click the Next button.  You'll be brought to the add projects dialog.  We haven't created any projects so basically you can leave this blank and click Finish.  This is a nice way to bulk import web projects that you may have already built in Eclipse for a different server.  However, like I said, we haven't done anything yet, so the panes are empty.

We have created any projects yet, but this is a nice way of quickly adding them if we did.

Ta-Da!

Eclipse now knows about your Tomcat install.  You should be able to see the server in the Servers tab in Eclipse.  It may say that for the moment, your server is currently stopped.  Go ahead and right mouse click on the server and choose Start.  After a bit of startup text that flies by you in the console, you're web server is now up and running!

There is our new server.
Now if you open a web browser and go to "http://localhost:8080", you'll get an actual reply back from Tomcat.  It'll be a 404 error, since we didn't install any applications into the system, it doesn't have anything to run, but at least you are now getting some reply back!

Go ahead and stop the server before you leave Eclipse.  I believe that Eclipse will stop the server before exit, but don't quote me on that.  Just make it a habit to not leave the server running while you're not doing anything.  There you go.  Now you have Tomcat and Eclipse working together!

Tomcat comes with some default applications and some examples you can play with.  I'll show you how to get some of those examples up and running.  However, before you get serious, you'd want to remove the examples and what-not from the server.  There's no point in having that junk on a production system.

Cheers!