Friday, August 15, 2008

A Simple JSP

Okay, playing with the examples can be fun (spoiler: the two colours you're looking for are Black and Cyan), but the real test is to set up a JSP of your own and make it run.


Open NotePad or your favourite text editor, and type in the following:


This example brought to you by JSP and SitePoint.com!


Save the file as theEnd.html in a new subdirectory of Tomcat's webapps directory called sitepoint. Create a second new file in NotePad and type in the following:


<%@ page language="Java" %>

<html>

<head>

<title>A Simple JSP</title>

</head>

<body>

<p>

 <% String num = request.getParameter("num");

    if (num == null) { // No number specified

      // Display the form

 %>

      <form action="<%= HttpUtils.getRequestURL(request) %>">

      What should I count to? <input type="text" size="2" name="num" />

      <input type="submit" />

      </form>

 <%

    } else for (int i=1; i<=Integer.parseInt(num); i++) {

 %>

      Counting: <%= i %><br />

 <% }

 %>

</p>



<%@ include file="theEnd.html" %>



</body>

</html>


Save this as count.jsp in your new sitepoint directory alongside theEnd.html.


Now, to make these two files visible, you need to create a Java Web application to contain them. Doing this is nice and simple. Create a subdirectory of your new sitepoint directory called WEB-INF. In that subdirectory, create a text file called web.xml and type the following into it:


<?xml version="1.0" encoding="ISO-8859-1"?>



<!DOCTYPE web-app

   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

   "http://java.sun.com/dtd/web-app_2_3.dtd">



<web-app>

</web-app>


Save the file and then restart Tomcat or reboot your system to allow Tomcat to become aware of the new Web application. You can then view the page through Tomcat with the URL http://localhost:8080/sitepoint/count.jsp.


To make your new Web application visible through Apache, simply restart Apache. When you restarted Tomcat, it created a new automatic configuration file for Apache; restarting Apache will read in this new config file and add your new Web application to the lineup. Whenever you add a new Web application to Tomcat you need to perform this "Restart Tomcat, Restart Apache" process; fortunately, this doesn't happen often.


Once Apache is back up and running, open http://localhost/sitepoint/count.jsp. There you have it: your first working JSP in Apache!

No comments: