JSP Tutorial - some Examples of Java Servlet Pages

Introduction

JSP stands for Java Servlet Pages, a shorthand way of writing simple Servlets, more akin to other web scripting languages like PHP and ASP. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them.

To be active, JSP files have to be placed in a servlet context directory. Here in this page, we'll use the Personal Tomcat system to develop a series of JSP examples, and we'll assume that we've already set up a personal tomcat context directory called example-context for all our examples to go inside. That is, we've already done the following:

mktomcat6 ~/example-context
cd ~/example-context

A Simple Example JSP file - eg1.jsp

Here is eg1.jsp, a very simple (and completely pointless) JSP File:

 <html>
 <body bgcolor="#ffffff">
 <h1>Hello world!</h1>
 <%
  out.println("<p> This web page is produced by JSP");
 %>
 </body>
 </html>

As you can see, most of this is pure HTML, but within the <%..%> section, we abruptly switch to writing pure Java code which prints out some more HTML code. When you access this file via a web browser and Tomcat, Tomcat translates the JSP file into a servlet class, adding various standard declarations (including the mysterious class instance out, an open file handle to which you print HTML output), compiles it, loads the class into memory, and then invokes a particular auto-generated class method - which runs your JSP code. Sounds complex? Yes, it is, especially when you realise that it is quite possible to write a JSP which compiles into invalid Java code! If you're interested, explore your new context directory a bit more thoroughly - after invoking a jsp URL - you should be able to find the auto-generated Java servlet source file!

Ok, let's put eg1.jsp into our Personal Tomcat servlet context, alongside index.jsp:

A Slightly Better Example JSP file - eg2.jsp

The above example was pretty pointless, because all the Java code we called did was to print out static HTML which we could have done without all the JSP/Java Servlet overhead. Now, let's make a modified version - eg2.jsp which (while still being pointless) at least requires a programming language to be pointless in:

       <html>
       <body bgcolor="#ffffff">
       <h1>Hello world!</h1>
       <ul>
       <%
        int i;
        for( i = 0; i < 20; i++ )
        {
          out.println( "<br><li>Testing testing... "+i );
        }
       %>
       </ul>
       </body>
       </html>

An Example with remembered state - eg3.jsp

Even a simple JSP page, once translated into a servlet and loaded into memory by Tomcat, becomes a long-lived servlet instance which can store state information as instance variables. Here, we present a very simple example which adds a single instance variable:

static int n = 0;

In pure Java terms, all we need to do is to declare the appropriate variable inside the class before the methods start. But how do we do this in JSP when we're not writing the whole class? Using the <%! .. %> syntax.

      <%!
        public static int n = 0;
      %>
      <h1>Example With State</h1>
      <%
        out.println("<p><b>I remember, n="+n+"</b>");
        n++;
      %>

Importing Modules into JSP

Often, in JSP code, you want to be able to import some java module namespaces, just like you do in ordinary Java code. The only issue in JSP is how you mark the import declaration so that the Java servlet that is generated from the JSP file places the import declaration into a syntactically valid place.

Suppose, for example, that your code needs to do:

import java.sql.*;

To do this in JSP, add the following as the first line in the .jsp file:

<%@ page language="java" import="java.sql.*"%>

Using JDBC in JSP

See our separate JDBC with DoC Supported Databases document for a single worked example (Films and directors) shown in multiple different forms - including a pair of JSP versions, one connecting to Postgres and the other to Microsoft SQL Server. Specifically, Postgres.jsp and MSSQL.jsp

Let's try to get them both working in Personal Tomcat, it's simple. Proceed as follows:

Creating Java Beans - and using them from JSP

A Java Bean is basically a reusable Java component - a precompiled Java class - typically offering get/set methods to manipulate instance variables and/or external connections, which can be used from a Java Servlet or JSP page. Java Bean classes must be compiled and are usually packaged into a .jar file with an accompanying manifest file, and then the .jar file is placed in the WEB-INF/lib directory in a servlet context in order for Tomcat to find it.

Let's look at a very simple example of a Bean class, how to package it, and how to use it from a JSP page. It's good practice to put Java source code (for the bean itself, or indeed servlets) in a logically separate src subdirectory, so let's create one and create the bean:

      package dcwbeans;

      public class bean1
      {
          private String name = "wibble";
          public void   setName( String n ) { name = n; }
          public String getName()           { return name; }
          public String stars( int n )
          {
              String s = "";
              while( n-- > 0 )
              { 
                  s += "*";
              }
              return s;
          }
      }

      CONTEXT   =       ../webapps/ROOT
      DIR     =       $(CONTEXT)/WEB-INF/lib
      JARS    =       bean1.jar

      all:    $(JARS)

      clean:
              /bin/rm -f $(JARS) */*.class

      install:        $(JARS)
              install -m644 $(JARS) $(DIR)

      bean1.jar:      dcwbeans/bean1.class bean1.mf
              jar cfm bean1.jar bean1.mf dcwbeans/bean1.class

      dcwbeans/bean1.class:   bean1.java
              javac -d . bean1.java

      Name: dcwbeans/bean1.class
      Java-Bean: True

      <html>
      <body>
      <%-- Create an instance of the bean --%>
      <jsp:useBean id="b" class="dcwbeans.bean1"/>

      <table>

      <tr>
        <th>b.name is </th>
        <td><jsp:getProperty name="b" property="name"/> </td>
      </tr>

      <tr>
        <th>modifying b.name</th>
        <td><jsp:setProperty name="b" property="name" value="wobble"/> value changed</td>
      </tr>

      <tr>
        <th>b.name is now</th>
        <td><jsp:getProperty name="b" property="name"/> </td>
      </tr>

      </table>

      </body>
      </html>

        <jsp:getProperty name="b" property="name"/>

More about Beans

        <%= b.stars(20) %>

      CONTEXT   =       ../webapps/ROOT
      DIR     =       $(CONTEXT)/WEB-INF/lib
      JARS    =       bean1.jar
      MKBEAN  =       /homes/dcw/bin/mkbean

      all:    $(JARS)

      clean:
              /bin/rm -f $(JARS) */*.class

      install:        $(JARS)
              install -m644 $(JARS) $(DIR)

      bean1.jar:      bean1.java
              $(MKBEAN) bean1

      JARS    =       bean1.jar bean2.jar

      bean2.jar:      bean2.java
              $(MKBEAN) bean2

Locating the Servlets auto-generated from JSP

guides/java/servlets/jsp (last edited 2010-05-24 16:12:59 by dcw)