Leon Anavi
IT Tips && Tricks

Java

Created: 16.07.2009 00:32 Last Modified: 07.08.2009 02:26 Views: 31355
Keywords: Linux, serialVersionUID, Servlet, Tomcat

How to Create a Java Servlet Using Tomcat and Linux

Install and Configure Tomcat on Linux


Visit http://tomcat.apache.org/ and download a binary core archive of the latest stable version. To install Tomcat extract the archive at appropriate location.

Example

[leon@localhost Download]$ wget http://apache.skknet.net/tomcat/tomcat-6/v6.0.20/bin/apache-tomcat-6.0.20.tar.gz
--2009-08-07 02:25:23--  http://apache.skknet.net/tomcat/tomcat-6/v6.0.20/bin/apache-tomcat-6.0.20.tar.gz
Resolving apache.skknet.net... 85.11.160.14
Connecting to apache.skknet.net|85.11.160.14|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 5998298 (5.7M) [application/x-gzip]
Saving to: `apache-tomcat-6.0.20.tar.gz'

100%[====================================================================================>] 5,998,298   8.81M/s   in 0.6s

2009-08-07 02:25:24 (8.81 MB/s) - `apache-tomcat-6.0.20.tar.gz' saved [5998298/5998298]

[leon@localhost Download]$ tar -xzf apache-tomcat-6.0.20.tar.gz
By default the Tomcat server is using port 8080. To change this or any other setting edit the XML configuration files at conf directory. To add a user with rights for admistration of the Tomcat server open file tomcat-users.xml and modify it as it is shown:
<tomcat-users>
        <user username="admin" password="secret" roles="admin,manager"/>
</tomcat-users>

The example demostrates how to add an user with name 'admin' and password 'secret'. The Tomcat server has to be restarted in order to recognize the new user.

Creating a Servlet


The servlet is a JAVA server application which dynamically process requests and construct responses. To create a HTTP servelet follow five simple steps:

1. Create Directory Structure

Enter Tomcat's main directory and navigate to webapps. Create a new directory for your servlet using the mkdir command. After this create directoris WEB-INF and classes (subdirectory of WEB-INF). The WEB-INF directory contains configuration information about the web application. The subdirectory class should include the source code of the servlet.
[leon@localhost apache-tomcat-6.0.20]$ cd webapps/
[leon@localhost webapps]$ mkdir hello
[leon@localhost webapps]$ cd hello
[leon@localhost hello]$ mkdir WEB-INF
[leon@localhost hello]$ cd WEB-INF
[leon@localhost WEB-INF]$ mkdir classes

2. Configuration

The servlet must have a configuration XML file at directory WEB-INF. Create a text file with name web.xml. The file have to uses the XML schema. The name of the root tag have to be web-app and should contain subelements servlet (contains information about name and main class of the servlet) and servlet-mapping (URL pattern to execute the servlet). Example configration:
<web-app>
        <servlet>
                <servlet-name>HelloWorld</servlet-name>
                <servlet-class>HelloWorld</servlet-class>
        </servlet>
        <servlet-mapping>
                <servlet-name>HelloWorld</servlet-name>
                <url-pattern>/HelloWorld</url-pattern>
        </servlet-mapping>
</web-app>

By default the Tomcat uses port 8080 and this servlet can be access with URL: http://localhost:8080/HelloWorld.

3. The Code

The name of the main class must be same as described at web.xml (configured at step2 ) and should be saved as a file at directory classes (created at step 1). The class should extend the abstact class HttpServlet and to override method doGet. The packages for input/output operations, servlet exception and HTTP request/responses have to be included. Example shows how to return HTML as a response:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet
{

        static final long serialVersionUID = 42L;

        public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
                throws IOException, ServletException
        {
                response.setContentType("text/html");
                PrintWriter Printer = response.getWriter();
                Printer.println("<html>");
                Printer.println("<head>");
                Printer.println("\t<title>Leon Anavi Example</title>");
                Printer.println("</head>");
                Printer.println("<body>");
                Printer.println("<b>Hello World!</b>");
                Printer.println("</body>");
                Printer.println("</html>");
                return;
        }
}

Please note the static field serialVersionUID which should be declared because the main class is serializable and in order to avoid the warning:
----------
1. WARNING in HelloWorld.java (at line 5)
        public class HelloWorld extends HttpServlet
                     ^^^^^^^^^^
The serializable class HelloWorld does not declare a static final serialVersionUID field of type long
----------

4. Build the Servlet

Before executing a servlet it has to be build using the source code, j2ee.jar and servlet-api.jar. The Servlet API is part of the of Tomcat and can be found at lib (subdirectory of the Tomcat main directory). To build the class HelloWorld, created at the previos steps under console execute:
[leon@localhost classes]$ javac -classpath %J2EE_HOME%\lib\j2ee.jar -classpath ../../../../lib/servlet-api.jar HelloWorld.java
[leon@localhost classes]$
On success no warnings or errors will occur.

5. Run the Servlet

Start Tomcat server (if not started) and using a web browser open the URL configured at step 2 (example: http://localhost:8080/HelloWorld).
[leon@localhost bin]$ ./startup.sh
Using CATALINA_BASE:   /home/leon/apache-tomcat-6.0.20
Using CATALINA_HOME:   /home/leon/apache-tomcat-6.0.20
Using CATALINA_TMPDIR: /home/leon/apache-tomcat-6.0.20/temp
Using JRE_HOME:       /usr

External Links

Tomcat

Class Reference

HttpServlet.html
Serializable


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.