This laboratory exercise involves developing a Hello World servlet,step by step. It is a long process, but each step should be simpleenough. Take careful note of what you are doing at each step, andthe commands you need to run. It gets easier once you've workedout the process - your first servlet will be your hardest!
Level of Difficulty: 1 (easy)
Estimated time: 30 minutes
Pre-requisites:
This exercise will lead you step by step through writing and deployingyour first Java servlet without an Integrated Development Environment (IDE) such as Eclipse.
Create a directory to store your source code. This directory shouldbe completely outside the WebLogic server directory hierarchy, e.g.
cd mkdir aip mkdir aip/servlets mkdir aip/servlets/helloworld cd aip/servlets/helloworld
Create a file called HelloWorldServlet.java
with the followingcontents. If you are familiar with Unix, try the 'vi
'editor, e.g. vi HelloWorldServlet.java
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloWorldServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); out.println("Hello servlet world!"); out.close(); } }
Compile your source code using javac
.
javac HelloWorldServlet.java
If you see an error message that it cannot import the servlet packages(javax.servlet and javax.servlet.http), then your environment is notset correctly. Go back and re-run setEnv.sh
.
Congratulations, you have just written your first Java servlet.Before you can run it though, you must first package it, and deployit. These steps are described below.
Java servlets execute as part of a web server. You cannot run or testthem from the command line. The web server you will use to run yourservlet is the web server built in to the application server (WebLogic).To "run" your servlet, you will access a URL in your webbrowser. This is quite similar to running a CGI program, or runninga PHP script.
Before you can install your servlet into the application server,it needs to be packaged properly. Servlets are part of what J2EEcalls 'web applications', and web applications should be packaged ina Web Application Archive file, or WAR file.
A WAR file is basically a compressed zip file that contains all parts of your web application. The parts may include:
static web site files (HTML, GIF, JPEG, CSS, etc)
Java servlets
a deployment descriptor (described later)
Importantly, when you package your application as a WAR file, itmust follow a particular directory structure. Starting at the samedirectory where your HelloWorldServlet.java
file is, run the following commands. Note that the directory names arecase-sensitive, so be careful to type them correctly.
mkdir WEB-INF mkdir WEB-INF/classes
Your compiled Java servlet class files must be placed in the WEB-INF/classes
directory. When you compiled yourHelloWorldServlet earlier, you just put the .class file in thesame directory as the .java file. You'll need to fix that now.
rm *.class javac -d WEB-INF/classes HelloWorldServlet.java
Note the use of the '-d
' option to javac, which allows youto specify the output directory (where the .class files go).
As mentioned above, a WAR file contains static HTML (etc) files,Java servlet classes, and a deployment descriptor.The next step is for you to create a deployment descriptor.
A deployment descriptor is an XML file describing the propertiesof your 'web application'. When your web application includes servlets,the deployment descriptor file describes the name of each servlet, andwhat URL should be used to invoke the servlet.
In the case of web applications, the deployment descriptor is contained ina file called web.xml
, and it must be placed in theWEB-INF
directory.
Edit the web.xml
file now, e.g.
vi WEB-INF/web.xml
(or use the text editor of your choice). Into the web.xml
file, copy the following text:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>HWServlet</servlet-name> <servlet-class>HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HWServlet</servlet-name> <url-pattern>/HW</url-pattern> </servlet-mapping></web-app>
Points to note about the definitions in web.xml
:
servlet-name
can be any name you choose. It does nothave to be the same as the filename in which the servlet class is stored. Every servlet referenced in your web.xml
must have a unique servlet-name
within that oneweb.xml
file.
servlet-class
specifies the name of the Java class filecontaining the compiled servlet code.
url-pattern
specifies the URL by which you want users tobe able to execute your servlet. In the example shown above, theurl-pattern
is "/HW", so the URL that will beused to invoke the servlet will look likehttp://hostname:7001/HelloWorldApp/HW
Your WAR file can also include static HTML files, as well as images(GIF, JPEG), style sheets (CSS), and any other static files you wouldexpect to find on a web server.
In the WAR file, these files must be placed outside theWEB-INF
directory. Any files not in the WEB-INF
directory can be accessed through the web browser. Any files that areinside the WEB-INF
directory (including your web.xml
deployment descriptor, and your servlet class files) will be protected, and not accessible to users over the web.
Let's create a static HTML file called index.html
to goinside your WAR file. It can go in the top-level directory of yourweb application (i.e. the directory that has the WEB-INF
subdirectory in it).
Use a text editor to create index.html
with thefollowing contents:
<HTML> <BODY> <H1>My first WAR file</H1> <P> Run my <A HREF="HW">Hello World servlet</A>. </P> </BODY> </HTML>
When creating WAR files, it is very important that everything isin the correct directory. So before we actually create the WARfile, take a moment to check when you view your directory hierarchy,it looks something like the following:
$ ls -1F HelloWorldServlet.java WEB-INF/ index.html $ ls -1F WEB-INF classes/ web.xml $ ls -1F WEB-INF/classes HelloWorldServlet.class
i.e. the directory tree structure should look like:
- index.html - HelloWorldServlet.java / WEB-INF - web.xml / classes - HelloWorldServlet.class
Note that it is not essential to have your Java source code fileas part of the WAR file, but it is convenient to keep all thefiles together.
Finally, you are ready to create your WAR file. Run the followingcommand, which will create a file called HelloWorldApp.war
in the parent directory of where you execute it from.
jar cf ../HelloWorldApp.war *
In the above command, the "c" means "c"reatea WAR file.
Now view the contents of your WAR file to ensure that the file wascreated correctly. Run the following command to list the WAR filecontents:
jar tf ../HelloWorldApp.war
In the above command, the "t" means to showthe "t"able-of-contents of the WAR file.
The output from the previous command should show something like:
META-INF/ META-INF/MANIFEST.MF HelloWorldServlet.java WEB-INF/ WEB-INF/classes/ WEB-INF/classes/HelloWorldServlet.class WEB-INF/web.xml index.html
The META-INF
directory and the MANIFEST.MF
file are automatically added by the jar utility. You can ignore them.
Now that you have a WAR file, you can "deploy" it tothe web server. Deployment is the process of installing an application.
In WebLogic, there are a variety of ways you can deploy an application.The simplest is just to copy your WAR file into your WebLogic server's"autodeploy
" directory.
cp ../HelloWorldApp.war ~/weblogic/autodeploy
You can do this when the server is running. The server checks thecontents of the autodeploy
directory every few seconds,and when it sees a new WAR file, or one with an updated timestamp,it automatically deploys (or redeploys) it.
If you have followed the steps above exactly, try accessing your application through the following URL:
http://localhost:7001/HelloWorldApp/
It should show you the contents of your index.html
file. If you click on the link to your servlet, it shouldexecute your servlet and display the servlet's "Hello World"message.
Note that when you deployed your WAR file into WebLogic, it created a virtual directory under the root of your web server with the same name as your WAR file. So the name you choose for your WAR filesis important, because the WAR filename will become part of the URL.
Take note of what was required to write a single servlet, package itin a WAR file, and deploy it to the web server. Note the commands, and the directory structure used.
When you go to create your second servlet, you might find it easierto set up the directory structure first before beginning to write anyJava source code. You will also probably find it convenient to copyyour web.xml
file and simply edit the values inside.
You might even like to create yourself a Makefile, or a shell scriptwhich automates the process of compiling, packaging and deployingyour WAR file.