JSP Quick-Start Guide for Linux

Tweet

JavaServer Pages (JSP) is a server-side technology that allows developers to create Web-based applications that can make use of components that are developed in the Java programming language, according to the JavaBeans specification. In some respects, it can be compared to server-side scripting languages such as ASP and PHP. JSP is similar to PHP in the C-style syntax of the Java language, but JSP was also designed to be extendable using components like ASP.

When it comes right down to it, however, JSP is a technology like no other. Extremely fast, platform independent, highly scaleable with built-in support for distributed processing, compatible with all major Web servers, and FREE for most uses, one might wonder why JSP isn’t used more than it is.

Well, as I see it, there are two main reasons for that:

  • To take full advantage of JSP, a developer must first be comfortable working in the Java programming language. Unfortunately, this can be quite an ask for Web developers who like to concentrate on design and dabble in a scripting language or two when necessary. There are lots of good online tutorials and books out there for people interested in learning Java, but the process can be time consuming and, depending on the individual, quite challenging, due to the nature of Java as a pure object-oriented language.
  • Setting up a server environment to develop and test JSPs can be a confusing task, especially since most of the documents written to guide users through the process are steeped in technical mumbo jumbo that assumes you already know JSP inside and out. If you’re just getting started with JSPs, you want a step-by-step guide to getting a server up and running in short order so that you can concentrate on learning the language, and worry about the details of server configuration later.

In this article, I’ll attempt to remedy the latter point by guiding you through the process of setting up a JSP-enabled Web server on a Linux machine. Hopefully, this will give you the head start you need to jump into the world of JSP development. I’ll take you as far as getting a basic JSP page working on your server, and then you can dive into our JSP article series, The JSP Files fully equipped!

As for the Windows users in the audience, don’t fret! Just see my JSP Quick-Start Guide for Windows!

Downloading and Installing Apache Server

While there are some great commercial servers out there for testing JSP pages (including IBM WebSphere, BEA WebLogic, and others), these can be beyond the reach of the average Web developer who just wants to add a new skill to his or her repertoire. For this reason, the server I recommend for people getting started with JSP is Apache Server. By hooking it up to the Jakarta Project’s Tomcat Server (which we’ll install in the next section), we can give it the ability to handle JSP pages, as well as related technologies like Java Servlets and Enterprise Java Beans (EJBs)!

Now, if you’ve already got Apache running (as most Linux users do), you don’t have to reinstall it. This will be good news to people who are already using Apache to run PHP scripts or whatnot, because you’ll be able to simply add JSP support to your existing server without disrupting whatever else you have set up.

If you don’t have Apache installed, now is the time to do it. Just use your distribution’s package manager to install Apache. When you’re done, you can skip ahead to the next section. If you’re not sure how to use your distribution’s package manager, or if you prefer installing software yourself to letting the package manager do it, read on.

You’ll need to go to The Apache HTTP Server Project’s Web site to download the latest stable source release of Apache Server for Unix. As of this writing, the current version is 2.0.44 (the filename is httpd-2.0.44.tar.gz), and can be downloaded from the following address: http://www.apache.org/dist/httpd/.

Once you’ve downloaded the file, extract it to your home directory (or wherever you find convenient) to create a directory called httpd-2.0.44:

[kevin@sp kevin]$ tar xfz httpd-2.0.44.tar.gz  
[kevin@sp kevin]$ cd httpd-2.0.44/  
[kevin@sp httpd-2.0.44]$

Note, the [kevin@sp kevin]$ portion of the above represents the command prompt. You only need to type the commands shown in bold.

Next, you need to configure Apache so that it will be compiled with the features you need and installed where you want it to go. The following command (which should be typed all on one line) sets up Apache to be installed in /usr/local/apache2 and enables dynamic module support (which we’ll need to interface with Tomcat) and the mod_rewrite module (which is not important for this article, but is a useful feature you’ll probably want at some point):

[kevin@sp httpd-2.0.44]$ ./configure --with-prefix=/usr/local/apache2  
--enable-so --enable-rewrite

After all the diagnostic messages have scrolled by, you should return to the command prompt. Now type the make command to compile Apache server:

[kevin@sp httpd-2.0.44]$ make

Again, pages of messages will scroll by. When they’re done, the last step is to install Apache. Unless you specified a target directory beneath your home directory above, you’ll need to log in as the root user (type su to do this) before you can proceed:

[kevin@sp httpd-2.0.44]$ su  
Password: ********  
[root@sp httpd-2.0.44]# make install

With Apache installed, you can run it by logging in as root and running the apachectl program in the /usr/local/apache2/bin directory with the start argument:

[root@sp /]# /usr/local/apache2/bin/apachectl start

Open your Web browser and type http://localhost/ in the address field and press Enter. A Web page with the Powered by Apache logo at the bottom should appear, explaining that Apache is correctly installed. Congratulations, you’ve successfully installed Apache!

Running Apache Automatically

Obviously, you don’t want to have to start Apache manually every time you start your computer. To get Linux to launch Apache at start-up, you need to place a link to the apachectl program in the start-up folder for each runlevel (or operating system mode) where you want Apache to run.

Here’s the series of commands that will set up Apache to run automatically in runlevels 2, 3, 4, and 5 (all the normal operating modes of Linux systems), and shut down when the computer shuts down:

[root@sp /]# cd /etc  
[root@sp etc]# ln -s /usr/local/apache2/bin/apachectl init.d/apache2  
[root@sp etc]# ln -s init.d/apache2 rc2.d/S91apache2  
[root@sp etc]# ln -s init.d/apache2 rc3.d/S91apache2  
[root@sp etc]# ln -s init.d/apache2 rc4.d/S91apache2  
[root@sp etc]# ln -s init.d/apache2 rc5.d/S91apache2  
[root@sp etc]# ln -s init.d/apache2 rc0.d/K20apache2

That should do it! To try it out, shut down your computer, start it back up again, and see if you can still access the Apache server at http://localhost/.

Downloading and Installing Tomcat

Since Apache doesn’t support JSP out of the box, we need to add something else to the mix to provide that support. Unfortunately, JSP is too complicated to be supported by a simple Apache module; thus, we need to install an entirely new program to provide that support, then instruct Apache to forward requests for JSP pages to that program (note: this may sound like CGI, but it isn’t; just wait and see). The program we’ll be using is called Tomcat, and is also written by the Apache Group.

Tomcat is in fact a simple Web server in its own right. It doesn’t support any of the advanced features of Apache, however; that’s not its job! By linking Tomcat and Apache together, you get a system that provides full support for JSP (thanks to Tomcat) while maintaining the performance and expandability (PHP, Perl, SSL, etc.) of Apache.

Your first step should be to download and install the Java 2 Software Development Kit (Java 2 SDK) from Sun. This is required both to run Tomcat (which is a Java program), and for Tomcat to be able to compile JSPs for use. The current version of the Java 2 SDK (also called the JDK) as of this writing is version 1.4.1_01, and is available for download here. Download the ~42MB "Linux self-extracting file" (be sure to download the SDK, not the JRE!). The filename should be j2sdk-1_4_1_01-linux-i586.bin. Extract this file into your /usr/local directory with this series of commands:

[kevin@sp kevin]$ su   
Password: ********  
[root@sp kevin]# chmod u+x j2sdk-1_4_1_01-linux-i586.bin  
[root@sp kevin]# mv j2sdk-1_4_1_01-linux-i586.bin /usr/local/  
[root@sp kevin]# cd /usr/local  
[root@sp local]# ./j2sdk-1_4_1_01-linux-i586.bin

You can delete the j2sdk-1_4_1_01-linux-i586.bin file now, or put it someplace safe for future use; you’re done with it.

Java is now installed, but you need to do a few things to settle it smoothly into your system. First, make a symbolic link so you can access the Java installation with the easier-to-type name /usr/local/java:

[root@sp local]# ln -s j2sdk1.4.1_01 java

Next, make links to the important programs that make up the Java SDK in the /usr/local/bin directory, so you can run them from anywhere:

[root@sp local]# ln -s java/bin/java /usr/local/bin/java   
[root@sp local]# ln -s java/bin/javac /usr/local/bin/java  
[root@sp local]# ln -s java/bin/jar /usr/local/bin/java

Now, we need to edit a couple of environment variables on your system. Still as root, open the /etc/profile on your system in your preferred text editor. Look for a line beginning with PATH=. When you type a program name at the command prompt, this line sets the directories that your system checks for that program. Check to make sure /usr/local/bin is in the list. If it isn’t, add the following line right after the existing PATH= line:

PATH="$PATH:/usr/local/bin"

You also need to set the JAVA_HOME environment variable to point to your Java installation. To do this, scroll right down to the bottom of the file and add these two lines to the end:

JAVA_HOME="/usr/local/java"   
export JAVA_HOME

Save the changes, log out, and then log back in. Java should now be nicely installed and integrated with your system. To test it, you can type java -version at the command prompt and make sure that it reports your Java version correctly.

Now you’re ready to install Tomcat. Download the latest release from the Jakarta Project Web site. As of this writing, the latest version was 4.1.18, and was available at http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/v4.1.18/bin/. The file should be called jakarta-tomcat-4.1.18-LE-jdk14.tar.gz, and is about 5.1MB.

Once you’ve downloaded the file, move it to your /usr/local directory and extract it:

[kevin@sp kevin]$ su   
Password: ********  
[root@sp kevin]# mv jakarta-tomcat-4.1.18-LE-jdk14.tar.gz /usr/local/  
[root@sp local]# tar xfz jakarta-tomcat-4.1.18-LE-jdk14.tar.gz

You can delete the jakarta-tomcat-4.1.18-LE-jdk14.tar.gz file now, or put it somewhere safe for future use; you’re done with it.

As with the Java SDK, create a link to the installation directory with a neater name for convenience:

[root@sp local]# ln -s jakarta-tomcat-4.1.18-LE-jdk14 tomcat

Like Java, Tomcat requires an environment variable of its own to be set for it to run properly. Open up your /etc/profile file one more time and add these two lines to the end:

CATALINA_HOME="/usr/local/tomcat"   
export CATALINA_HOME

Once again, save your changes, log out, then log back in for changes to take effect.

You’re ready to start Tomcat! Log in as root and type the following command to launch it:

[root@sp kevin]# $CATALINA_HOME/bin/startup.sh

If all goes well, the startup.sh script should display the values of a few environment variables, and then Tomcat will launch quietly in the background. Congrats — Tomcat is up and running!

As I said before, Tomcat provides its own simple Web server, and we can use this to test that it is working properly. Tomcat’s Web server is set up to use port 8080 by default, so open your Web browser and load http://localhost:8080/. You should see the Tomcat home page, with links to some examples that come preinstalled on the server.

Have a play with these examples if you’re curious, and notice how the JSP examples take considerable time to load the first time you use them, but then work very quickly upon subsequent accesses. This happens because the first time a JSP page is accessed, Tomcat needs to compile it into a Java Servlet, which is a piece of pure Java code that can be run very quickly to process requests. That Servlet is then held in memory to process subsequent requests for the same JSP at blazing speed.

When you’re done playing with Tomcat, shut it down by running the shutdown.sh script the same way you ran the startup.sh script above ($CATALINA_HOME/bin/shutdown.sh). Tomcat will shut down after a few moments.

Running Tomcat Automatically

If you’ve got Apache running automatically at system start-up, you’ll probably want to do the same for Tomcat. Start by copying (not linking) the catalina.sh script that came with Tomcat to your /etc/init.d/ directory:

[root@sp kevin]# cd /etc   
[root@sp etc]# cp /usr/local/tomcat/bin/catalina.sh init.d/

This script relies on the JAVA_HOME and CATALINA_HOME environment variables we set earlier, but these variables do not exist while the system is starting up. We must therefore edit the script a little so that it can serve as a system startup script.

Open the file in your favourite text editor, and scroll down to the first blank line following the opening comments (any line that begins with a # is a comment). Add these two lines at that point:

JAVA_HOME="/usr/local/java"   
CATALINA_HOME="/usr/local/tomcat"

This script actually makes an attempt at detecting CATALINA_HOME itself, but this attempt backfires if the script is not actually in the Tomcat directory (which in this case it isn’t). Scroll down and look for a line that begins with CATALINA_HOME=. It should look like this:

CATALINA_HOME=`cd "$PRGDIR/.." ; pwd`

Comment it out by putting a # at the start of that line:

#CATALINA_HOME=`cd "$PRGDIR/.." ; pwd`

That completes the adjustments to catalina.sh. You can now assign this as a start-up script in the various runlevels (operating modes) of your computer:

[root@sp etc]# ln -s init.d/catalina.sh rc2.d/S90tomcat   
[root@sp etc]# ln -s init.d/catalina.sh rc3.d/S90tomcat  
[root@sp etc]# ln -s init.d/catalina.sh rc4.d/S90tomcat  
[root@sp etc]# ln -s init.d/catalina.sh rc5.d/S90tomcat  
[root@sp etc]# ln -s init.d/catalina.sh rc0.d/K19tomcat

That should do it! To try it out, shut down your computer, start it back up again, and see if you can load the Tomcat home page at http://localhost:8080/.

Linking Apache and Tomcat with mod_jk

Now that you’ve got Apache and Tomcat running side by side, you need to link them together so that Apache can process JSP requests by handing them off to Tomcat. There are actually several ways to do this, and all involve installing an Apache module. The first option is to use mod_jk, which was designed specifically for Tomcat 3.x to work with various servers and uses a fairly efficient protocol for communication with Tomcat.

As of Tomcat 4.0, a new mechanism for linking Apache and Tomcat is available: mod_webapp. This Apache module provides efficient communication between Apache and Tomcat, and is exceedingly easy to configure. Unfortunately, the developer in charge of mod_webapp has some pretty strong feelings against Windows, so mod_webapp does not work reliably on that platform. Rather than use a different module for each platform, I prefer to stick with mod_jk on both Windows and Linux. That way I know I’ve got a solution that works, whatever platform I need for a particular job.

A revamped implementation of mod_jk called mod_jk2 is available as of Tomcat 4.1. It was written to be more modular, offer better performance, and improve the ease of configuration. Unfortunately, documentation on mod_jk2 is still a little sketchy; therefore, mod_jk is the module we’ll install in this article.

The Elusive mod_jk
mod_jk comes in two parts: a connector plug-in for Tomcat and an Apache module. The connector plug-in is included with every copy of Tomcat 4.1. The other half of the equation, the Apache module, is a different story.

Because Apache 2.0 is in a constant state of flux, older versions of the mod_jk module will usually not be compatible with newer versions of Apache 2.0. In general, you need a copy of mod_jk that was compiled after the Apache 2.0 release you want to use it with. The Jakarta team always tries to maintain a downloadable copy of mod_jk that is compatible with the latest Apache 2.0 release on their Web site.

At this time, the latest release of mod_jk is available from http://jakarta.apache.org/builds/jakarta-tomcat-connectors/jk/release/v1.2.2/bin/linux/i386/. The file is called mod_jk-2.0.43.so to signify that it was compiled to work with Apache 2.0.43 (it will also work with 2.0.44). Download the file, rename it to mod_jk.so, and copy it to the modules subdirectory of your Apache 2.0 installation (/usr/local/apache2/modules).

With the Apache module installed and the Tomcat plug-in built into the server, we must now configure both Apache and Tomcat to use mod_jk to communicate with each other.

Configuring Tomcat

Now we need to configure Tomcat to use mod_jk. Locate the server.xml file in the conf subdirectory of your Tomcat directory and open it in a text editor of your choice.

Immediately following the <Server port="8005" ...> tag near the top of the file, add the following:

<Listener className="org.apache.ajp.tomcat4.config.ApacheConfig"    
 modJk="/usr/local/apache2/modules/mod_jk.so" jkDebug="info"    
 workersConfig="/usr/local/tomcat/conf/jk/workers.properties"    
 jkLog="/usr/local/tomcat/logs/mod_jk.log" />

Be sure to replace the paths in bold with those on your system if they differ.

About halfway through the file, find the <Host name="localhost" ...> tag and add the following immediately after it:

<Listener className="org.apache.ajp.tomcat4.config.ApacheConfig"     
 append="true" />

Close server.xml, then create a new directory called jk in that same directory (conf). This directory is where we'll create the workers.properties file mentioned in the first <Listener> tag above. Open up your text editor again and type (or copy) in the following:

workers.tomcat_home=/usr/local/tomcat    
workers.java_home=$(JAVA_HOME)    
workers.th=$(workers.tomcat_home)    
ps=    
worker.list=ajp13, ajp14    
worker.ajp13.port=8009    
worker.ajp13.host=localhost    
worker.ajp13.type=ajp13    
worker.ajp13.lbfactor=1    
worker.ajp14.port=8010    
worker.ajp14.host=localhost    
worker.ajp14.type=ajp14    
worker.ajp14.secretkey=secret    
worker.ajp14.credentials=myveryrandomentropy    
worker.ajp14.lbfactor=1    
worker.loadbalancer.type=lb    
worker.loadbalancer.balanced_workers=ajp13    
worker.inprocess.type=jni    
worker.inprocess.class_path=$(workers.tomcat_home)$(ps)lib$(ps)tomcat.jar    
worker.inprocess.cmd_line=start    
worker.inprocess.jvm_lib=$(workers.th)$(ps)jre$(ps)bin$(ps)classic$(ps)jvm.dll    
worker.inprocess.stdout=$(workers.th)$(ps)logs$(ps)inprocess.stdout    
worker.inprocess.stderr=$(workers.th)$(ps)logs$(ps)inprocess.stderr

Be sure to adjust the tomcat_home line (shown in bold) to match your system. Save the file as workers.properties in your newly-created jk directory.

Restart Tomcat. If you haven't missed any steps, it should automatically create another directory in its conf directory called auto with a file called mod_jk.conf inside it. This file contains everything that Apache needs to know to use Tomcat to process JSPs.

Configuring Apache

Because Tomcat generates all the configuration information for Apache automatically as mod_jk.conf, all we need to do is point Apache at that file! Open your Apache 2.0 configuration file (/usr/local/apache2/conf/httpd.conf) in a text editor. Scroll down about 1/4 of the way through the file to find the section entitled Dynamic Shared Object (DSO) Support. After the LoadModule lines that appear below this heading, add the following line (adjusted to match your Tomcat directory):

Include "/usr/local/tomcat/conf/auto/mod_jk.conf"

With that line added to httpd.conf, save your changes and restart Apache (apachectl graceful). You should now get the same page whether you load http://localhost:8080/examples/jsp/ (from Tomcat), or http://localhost/examples/jsp/ (from Apache).

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:

<hr />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!

Where to from here?

If you've worked in PHP or another scripting language before, then the simple example above may have left you a little underwhelmed. "That's it?" you may ask. "I went to all that trouble just to do something I could have done in 30 seconds with PHP?" Of course not! As a simple example, the above does not make use of any of the more powerful features of JSP, most of which require a fairly thorough understanding of the Java programming language to use.

Thus, your first step should be to learn Java if you haven't already. There are plenty of good books out there (check the Related Articles below for a review of my favourite), but if you're in a hurry or on a budget, my article Getting Started with Java and its successors should get you going.

Once you're up to speed on Java (and I don't mean to trivialize that -- it will take some work), you can turn your attention to Java Servlets, and then JavaServer Pages. My article, Java Servlets, should get you going with the former; as for the latter, a 8-part tutorial series, The JSP Files, is now available on SitePoint.com to teach you all you need to know. Enjoy!

Good luck! If you hit any snags along the way, the SitePoint.com Forum members are here to help! And if all else fails, you can always contact me through the email link at the top of this article.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments