CC292 Labs: Java Server Pages (JSP)

Introduction

The purpose of this lab is to gain some experience of using Java Server Pages (JSP) to generate dynamic web pages.  Before working through this lab you should have studied the JSP Introductory lecture notes (or at least understand the idea of mixing HTML tags with Java code (scriptlets) and Java expressions), and have worked through the previous lab exercises.

JSP: Embedding Java in HTML to produce dynamic server-side content.

The first part of the lab works through some examples.  This involves either copying a file or typing in some code and then running it by doing a  make from within Intellij, then loading or reloading the page in a web browser to check its operation. 

JSP is executed solely on the server.  Therefore, providing the dynamically produced content is reasonably standard, it should work in any web browser (compare this with some of the JavaScript examples we studied last week, which failed to work in Internet Explorer).

The lab includes some exercises, and the JSP temperature conversion table will form part of assignment 1.

Note that the Intellij instructions were written for version 6.  For hints about setting up version 7, see here.

Tomcat

For this course, we shall use Tomcat as our web application server.  When properly configured, it should run smoothly.  Tomcat configuration varies between different versions of Tomcat.  For this course, we shall use Tomcat 5.5.20. 

The lab machines should have Tomcat pre-installed in the Program Files directory of the C: drive.

Alternatively (and for installation on your own machine), the zip file can be downloaded from one of the following locations; cscourse server is easiest as this only contains the correct version:

Extract the zip file to the root directory of your M: drive.  I like to keep pathnames simple, so after extraction, I rename the root to \tomcat (i.e. rename apache... to tomcat).

You should now have a folder tree like the following one:

Note the following important directories (folders):

  • webapps: tomcat expects each of your web applications to have a directory within webapps; the existing directories within webapps provide some sample web applications
  • bin: bin contains the startup.bat and shutdown.bat batch files for starting and stopping tomcat.
  • common/lib: place any third-party .jar files here.  For example, when we use webapps that talk to relational databases, you'll put the database .jar file here.
  • work:  this is a directory where tomcat places the Java Servlets that it compiles your JSP pages into; it is interesting to observe the relationship between a JSP page and the Java Servlet that gets generated from it.

Check the operation of the server.  Execute the startup.bat file, then click this link:

If all went well, you will see something like this:

If not, possible problems are to do with your environment variables.  For example, on one machine I tried, the default JDK was 1.4.  In this case, manually inserting the correct JDK path into the file tomcat\bin\setclasspath.bat (line 7) fixed it (where \jdk5 was the root directory of the correct JDK).

set JAVA_HOME=c:\jdk5

If you have some problem that you cannot fix, consult a GTA.

Hello Web App

As a first web application, we'll use the Hello World example from the lecture notes:

Create a directory called hello within webapps, then within that create a file called Hello.jsp.  Copy the following text into it:

<html>
<head> <title> Hello JSP </title> </head>
<body> 
  <p> Hello World: <%= new java.util.Date() %>
  </p>
</body>
</html>

Now click on this URL: http://localhost:8080/hello/Hello.jsp, and you should see a page like this one:

Hit refresh a few times, and note how the date is updated.  That's because the code is re-executed on the server each time the page is requested. 

So now you know how to create a simple web application with a dynamic JSP page.  The next example will include some Java helper classes.

Helper Classes

A helper class is a Java class used by a JSP page to assist in doing some task.  Recall from the lecture that it is generally bad style to include complex Java code within a JSP page.  It is usually much better to farm such tasks out to helper classes.  If these classes are specific to a particular application, then the class files should go in a directory called WEB-INF\classes within your web application (e.g. tomcat\webapps\hello\WEB-INF\classes.

The next example introduces a trivial helper class (hello.Greeting); the point of this is to check that we can call on user-defined classes when required.  The JSP and Java files are shown below (it should be obvious which is which!):

<%@ page import="java.util.Date" %>
<%@ page import="hello.Greeting" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Webby</title></head>
<body>
<p>Date is <%= new Date() %> </p>
<h2>Greeting <%= Greeting.hello() %> </h2>
</body>
</html>
package hello;

import java.util.Date;

public class Greeting {
  public static String hello() {
    return "Hello at : " + new Date();
  }
}

To work correctly, it is important that Tomcat can find the .class files that you call on from within your JSP code.  The root directory for these is WEB-INF\classes within your web application directory.

In fact, there are other files that also need to go in the right place.  One of these is the file Context.xml.  A typical file structure can be seen below:

By default, Tomcat will not reload your Java classes when you recompile them.  For development, it's more convenient (though slightly less efficient) to have them reloaded after each change.  To do this, edit the Context.xml file (location shown above) to be the following:

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true" path="/">
</Context>

Also note from the above directory structure that there are two packages defined for this web app: beans and hello.

At this point, we now how several different file types to keep track of.  A working sample is provided here. This zip file is from the deployed directory within webapps.  This includes examples from the JSP Introduction lecture notes, including the Hotel Booking example (beans version).  A deployed directory like this is what you are aiming to produce.

Extract the above zip file to a directory called webby within tomcat\webapps.  Then you should be able to run the helper class example from above ( http://localhost:8080/webby/Hello.jsp ) and the hotel beans booking example http://localhost:8080/webby/HotelForm.jsp :

JSP and Intellij

Now try working through the above example with Intellij.  The best practice is to keep your development directories (where you write the code) separate from the deployment directory (i.e. the webapps directory where Tomcat will look for the compiled code). 

Set up a development directory by following most of the defaults for an Intellij Web Application.  Some key points in the process are:

  • choose a web module
  • select Add Application Server Specific Descriptor
  • select to have an exploded directory, and set the path of it to be the name of your web application within tomcat e.g. /tomcat/webapps/webby/
  • create an src directory
  • do not enable struts or JSF support

Some of these points are illustrated below:

Now get the greeting helper class working from yourself.

  • Create the JSP file in the resources directory
  • Create the hello package within the src directory
  • Create the Greeting class within the hello package

This is how the structure should look within Intellij (note that some other files are also present):

Note: this is a different directory structure to the deployment one!

Exercises

JSP Temp. Conversion Table

Repeat the JavaScript Fahrenheit / Celsius conversion table exercise, except creating the table dynamically using JSP (see lecture notes).

Hotel Beans

Work through the form examples from the JSP Introduction lecture notes.  Implement the bean class to capture the submitted form data.  Note how setProperty automatically extracts all the submitted form data and sets the corresponding fields in the bean object.

Path info

In a web application, it is often useful to know the path to the current web application.

Within a JSP page, you can access this as follows:

getServletConfig().getServletContext().getRealPath("")

This will be necessary later on when working with database files.

Summary

In this lab we studied how to:

  • set up Tomcat
  • deploy a simple Hello World JSP page
  • call methods of a helper class from a JSP page
  • set up Intellij to create web applications
  • specify that class files should be automatically reloaded after recompilation

The details of configuring Intellij to work with JSP, Tomcat, and Java helper classes may have seemed a bit painful.  When you get used to it, however, setting up a new properly configured web project should only take a minute or so, and then you can focus on the more interesting aspects of how to design the JSP and the Java classes for you application.

 

Intellij 7

When creating a new project, select 'java module', then on this dialogue tick the 'web application' box as shown below, then click finish.

The main difference when running Tomcat web applications in version 7 is that the Tomcat configuration is a property of the run configuration, rather than a property of the project.  This is presumably done to be more flexible.  In this way, the same project can be deployed to different web application servers just by adding different run configurations.

If you explore the run menu you should be able to get a run dialog window like the following.  You can configure the startup page to be the current page you want to open in the browser.  If you have Tomcat installed on your system, then it should add this to the Application Server drop-down menu pictured below.  Under Deployment you may need to select a web facet to deploy.  If you get stuck with any of this just ask for help.

 

end of page