wiki:WebApplication

Servlet Programming

What is Tomcat?

Tomcat is a pure Java web server that runs Java codes as an web application program. Since tomcat runs on top of the Java Virtual Machine (JVM), porting your web applications to several OSs, including Windows, Mac OS, Linux, etc., becomes quite easy as long as you can install Java to the targetted OS. And also, you can pack your application into a single file called WAR (web application archive). Deployment of your application is simply to tell Tomcat the location of the war file.

How do I install Tomcat?

Visit http://tomcat.apache.org, and download the Tomcat 6.x (or higher). If you are an Windows user, you'll find a Windows service installer, that installs Tomcat as an Windows service. In the installation phase, you should choose full installation for easy setup and better performance:

How do I create a web application?

  • Create an eclipse project (e.g. c:/eclipse/workspace/myapp) with the following folders:
    myapp/src		source codes
    myapp/test    test codes
    myapp/webapp  web application folder
    myapp/webapp/WEB-INF/classes	     compiled java classes
    myapp/webapp/WEB-INF/web.xml     web application configuration file
    myapp/webapp/WEB-INF/lib		     jar library foldres
    myapp/webapp/(other web pages)
    
    • Set the output folder of the eclipse project to myapp/webapp/WEB-INF/classes instead of myapp/bin.
  • myapp/WEB-INF/web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
      version="2.4">
        
      <display-name>My Web Application</display-name>
    
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
      </welcome-file-list>
    
    </web-app>
    
  • Suppose that your web application is placed at c:/eclipse/workspace/myapp/webapp. An example of the organization of the webapp folder:
    webapp/WEB-INF                (web application information folder)
    webapp/WEB-INF/web.xml   (configuration file)
    webapp/WEB-INF/classes     (java class files)
    webapp/WEB-INF/lib            (jar libraries)
    webapp/						     (document root of your web application)
    webapp/index.html				 (top page)
    webapp/META-INF/context.xml  (optional: loaded at the startup of your web application)
    
  • Open http://localhost:8080/manager, then input your webapp folder path (c:/eclipse/workspace/myapp/webapp)and an arbitrary web path to access your web application (say /myapp):

How do I create somthing like a CGI program?

Create a servlet class that extends HTTPServlet. To compile servlet classes, you need servlet-api.jar file contained in the Tomcat installation. Rather than add the absolute path to the servelt-api.jar file, it is convenient to use an eclipse variable that can be shared multiple project. First, add a class path variable named TOMCAT_HOME from the preference panel:

Then, in a project setting, extend this variable, and add TOMCAT_HOME/lib/servlet-api.jar to your project's classpath:

Here is a simple servlet program that displays "Hello Servlet!""

//--------------------------------------
// webapp-blanc 
//
// HelloServlet.java
// Since: 2007/11/29
//
// $Author: leo $
//--------------------------------------

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        PrintWriter writer = resp.getWriter();
        writer.append("Hello Servlet!");
    }

}

Add the following XML fragment to your web.xml:

  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/Hello</url-pattern>
  </servlet-mapping>

Access http://localhost:8080/myapp/Hello

How do I create a war file?

  • First, add a web application description file, webapp/META-INF/context.xml:
    <Context docBase="myapp.war"
             path="/myapp2">
    </Context>
    
  • A WAR file is merely a JAR file that can be created by the following command:
     > jar -cvf myapp.war c:/eclipse/workspace/myapp/webapp
    
  • Then, copy this myapp.war file into (TOMCAT_HOME)/webapp folder. The war file will be automatically extracted and your application can be seen from http://localhost:8080/myapp2. Or, you can use tomcat manager to deploy the war file.

How do I generate graphics ?

Here is an example that draws a circle PNG image with user-specified size and color:

//--------------------------------------
// webapp-blanc Project
//
// RoundCircle.java
// Since: 2007/11/29
//
// $URL$ 
// $Author$
//--------------------------------------

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Circle extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        // recieves URL query parameter values
        int size = Integer.parseInt(req.getParameter("size"));
        String color = req.getParameter("color");
        
        if(size <= 0)
            size = 1;
        
        int colorCode = 0x666666;
        colorCode = Integer.parseInt(color, 16);
        
        int canvasSize = size * 2;
        
        BufferedImage circleImage = new BufferedImage(canvasSize, canvasSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) circleImage.createGraphics();
        
        // make the canvas transparent
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
        g.fill(new Rectangle2D.Double(0, 0, canvasSize, canvasSize));
        g.setComposite(AlphaComposite.SrcOver);
        
        // draw a circle 
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Ellipse2D circle = new Ellipse2D.Double(0, 0, canvasSize, canvasSize);
        g.setColor(new Color((colorCode >> 16) & 0xFF, (colorCode >> 8) & 0xFF, (colorCode) & 0xFF)); 
        g.fill(circle);
        
        final String imageType = "png";
        resp.setContentType("image/" + imageType);
        ImageIO.write(circleImage, imageType, resp.getOutputStream());
        
    }
}

Reload the web application from the TomcatManager?, then access to the http://localhost:8080/myapp/rc?size=100&color=CCCCFF , which will display a circle with a radius 100 and a color &CCCCFF

I have no time to create an web application from scratch.

Checkout the following source codes via Subversion: http://www.xerial.org/svn/project/sandbox/trunk/webapp-blanc

 > svn co http://www.xerial.org/svn/project/sandbox/trunk/webapp-blanc myapp

How do I debug my web application?

Create context.xml file, then specify the path to the context.xml in the deployiment menu.

<Context docBase="c:/eclipse/workspace/myapp/webapp"
         path="/myapp" reloadable="true">
</Context>

Homework

Create a servlet that displays gene region with a gene name as a graphic (e.g. gene track). It is okay to use imaginary (synthetic) gene data.

References

Attachments