Lunanbay JSP HowTo

There are two parts to JSP, setting it up and then doing things with it.

Setting up JSP

Assuming you have set your servlet engine, say, Tomcat up and there isn't already a context for your area then you need to consider how your area is going to fit into your Cyberspace. That is to say you need to give your context a subdirectory from somewhere in your URL's domain. For example, where the contents of /my-space are now going to be served by your servlet engine. The root of the tree needn't be / but can be anywhere, eg.

Next you need to tell Tomcat it is going to be serving up this piece of Cyberspace. Inside a Host tag you need to add something like

<Context path="/my-space" docBase="/the/physical/path/to/my-space" debug="0" reloadable="true"> <Logger className="org.apache.catalina.logger.FileLogger" prefix="yourhost.example.com_my-space_log." suffix=".txt" timestamp="true"/> </Context>

Note that path="/my-space" is your Cyberspace directory and docBase="..." is your physical filesystem directory.

Next you need to tell Apache to ask Tomcat the answer when someone asks for something in my-space. You need to add to your httpd.conf something like:

<IfModule mod_webapp.c> WebAppDeploy my-space tomcat-4.0.1 /my-space </IfModule>

Finally, you need to restart both Apache and Tomcat.

Doing Things with JSP

Having setup the JSP area you need to put something into your JSP file. There are a number of examples here:

date the simplest example
HTTP headers use some embedded Java
beans use a Bean to save state
MySQL talk to your MySQL DB

Show the Date

A simple example might be to print the current date:

<html> <head> <%@ page import="java.util.Date" %> </head> <body> The current date is <%= new Date () %>

Note the two expressions in bold. The first page directive is the equivalent of a Java import statement. The second is a shorthand notation to allow the evaluation of variables as strings within the HTML.

The output of this page looks something like this.

Show the HTTP headers

Another example might be to display the values of the headers passed to the JSP:

<p>The headers passed to this script were: </p> <% java.util.Enumeration he = request.getHeaderNames (); while (he.hasMoreElements ()) { String name = (String) he.nextElement (); out.println (name + " = " + request.getHeader (name)); } %>

Note the <% and %> elements which introduce arbitrary expanses of Java. request and out are JSP built-ins.

The output of this page looks something like this.

Simple Bean

Another example might be to store information in a Bean to be retrieved later. A Bean requires a supporting Java class with a very formulaic layout.

Supposing we have a series of web pages, the first lets the user enter a number, the second lets the user select a number to add to the first, then final page displays the sum of the two. For the server to persist the value for the lifetime of the session, using a bean, we need to write a Java program to manipulate our number.

First, though, a form (/my-space/bean-form1.jsp) to read in a number:

<form action="/my-space/bean-form2.jsp" method="post"> What's your number? <input type="text" name="number" size="20"> <input type="submit">

Note that the input variable is called number which is important for the supporting Java class.

Next, we need to write the supporting Java class.

public class Bean { String number; public void setNumber (String number) { this.number = number; } public String getNumber () { return number; } }

The most important thing to note here is the get and set methods where the rest of the method name is a capitalised version of the name of the form field that the JSP files manipulate. In the JSP forms we'll be manipulating a field called number hence we have two methods: getNumber and setNumber (note the capital N).

Note also that the Bean manipulates the object as a string (presumably as the underlying HTML form only uses strings).

Having compiled the Java you need to add the class file to somewhere where the servlet engine can find it. Assuming you installed as per the instructions above you would copy the class file to the directory /the/path/to/my-space/WEB-INF/classes (ie. your docBase plus /WEB-INF/classes).

In particular, you would probably have put your Bean into the com.example package -- because that's your domain -- in which case you'd put the class file into the directory /the/path/to/my-space/WEB-INF/classes/com/example. If you do that then in the subsequent examples where you access the Bean you should set the class attribute to be class="com.example.Bean".
In particular you can do this by invoking javac -d /the/path/to/my-space/WEB-INF/classes

Next you need to write a form (/my-space/bean-form2.jsp) to, say, print out the current value then ask the user to input another value to be added to it:

<jsp:useBean id="formData" class="Bean" scope="session" /> <jsp:setProperty name="formData" property="*" /> <html> <body> <h3>Stage 2 - Display the first number</h3> <p>The value you entered was <%= formData.getNumber () %>. </p> <p>This is a simple form to read in another number. </p> <form action="/my-space/bean-form3.jsp" method="post"> What's your other number? <input type="text" name="otherNumber" size="20"> <input type="submit">

There are a few things to note:

Finally, do something similar to print out the sum of the two numbers (/my-space/bean-form3.jsp):

<jsp:useBean id="formData" class="com.lunanbay.Bean" scope="session" /> <html> <body> <h3>Stage 3 - Sum up</h3> <p>The first value you entered was <%= formData.getNumber () %>. The second value was <%= request.getParameter ("otherNumber") %>. </p> <p>The sum of the two is <%= java.lang.Integer.parseInt (formData.getNumber ()) + java.lang.Integer.parseInt (request.getParameter ("otherNumber")) %>. </p>

The only point to note is the mechanism to access the value of otherNumber, that is request.getParameter ("otherNumber").

You can invoke the whole sequence here

Talk To Your MySQL DB

Suppose you have set up your test_user identified by their test_password with access to your test_table in your test_db.

You'll want to make MM.MySQL 2.0.8, Mark Matthews JDBC Driver for MySQL, available in your CLASSPATH -- probably by putting it in the lib directory of your Tomcat distribution, thus making it available for all your JSP contexts.

Then you'll want to write code along the following lines:

<%@ page import="java.sql.*" %> <%! private String dbConnectionString = "jdbc:mysql://localhost/test_db?user=test_user&password=test_password"; %> <html> <body> <% Class.forName ("").newInstance (); Connection db = DriverManager.getConnection (dbConnectionString); Statement stmt = db.createStatement(); ResultSet rs = stmt.executeQuery("select * from test_table"); while ( ()) { out.println (rs.getString (1) + ", " + rs.getString (2)); } %>

Note the two lines for initiating a new instance of the MySQL driver and then creating a connection to the database.