caucho
 Servlet


Servlets are Java classes which service HTTP requests. The only requirement for writing a servlet is that it implements the javax.servlet.Servlet interface.

Servlets are loaded from the classpath like all Java classes. Normally, users put servlets in WEB-INF/classes so Resin will automatically reload them when they change.

JSP pages are implemented as Servlets, and tend to be more efficient for pages with lots of text.

Examples

Configuring the web.xml

The following is a complete working web.xml to run this example.

The servlet-mapping tells Resin that the URL /hello should invoke the hello-world servlet.

The servlet tells Resin that hello-world uses the test.HelloWorld class and that the value of the greeting init parameter is Hello World.

WEB-INF/web.xml
<web-app>
  <servlet-mapping url-pattern='/hello'
                   servlet-name='hello-world'/>

  <servlet servlet-name='hello-world'
           servlet-class='test.HelloWorld'>
    <init-param greeting='Hello, World'/>
</web-app>

The Java code, HelloWorld.java belongs in

$app-dir/WEB-INF/classes/test/HelloWorld.java

Or, if you're compiling the servlet yourself, the class file belongs in

$app-dir/WEB-INF/classes/test/HelloWorld.class

Following is the actual servlet code. It just prints a trivial HTML page filled with the greeting specified in the web.xml.

init() and destroy() are included mostly for illustration. Resin will call init() when it starts the servlet and destroy before Resin destroys it.

package test;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  private String greeting;

  public void init()
    throws ServletException
  {
    greeting = getInitParameter("greeting");
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
    throws ServletException, IOException
  {
    PrintWriter out = response.getWriter();

    out.println("<title>" + greeting + "</title>");
    out.println("<h1>" + greeting + "</h1>");
  }
  
  public void destroy()
  {
    // nothing to do
  }
}

Servlet Example for JSP Programmers

Because Resin compiles JSP pages into servlets, programmers familiar with JSP can start writing servlets fairly easily. The following template can be used to see how to write a servlet for someone familiar with JSP.

package test;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void service(HttpServletRequest request,
  		      HttpServletResponse response)
    throws ServletException, IOException
  {
    PrintWriter out = response.getWriter();
    ServletContext application = getServletContext();
    HttpSession session = request.getSession();

    try {
      // code goes here

      // The equivalent of jsp:include:
      // request.getRequestDispatcher("/inc.jsp").include(request, response);
    } catch (ServletException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
}

Using Databases from a Servlet

The following is a sample design pattern for getting new database connections. The try ... finally block is very important. Without the close in the finally block, Resin's database pool can loose connections.

Configuring the database is described in the database configuration page.

TestDatabase.java
package test;

import java.io.*;

import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import javax.sql.*;

public class TestDatabase extends HttpServlet {
  DataSource pool;

  public void init()
    throws ServletException
  {
    try {
      Context env = (Context) new InitialContext().lookup("java:comp/env");

      pool = (DataSource) env.lookup("jdbc/test");

      if (pool == null)
        throw new ServletException("`jdbc/test' is an unknown DataSource");
    } catch (NamingException e) {
      throw new ServletException(e);
    }
  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
    throws IOException, ServletException
  {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Connection conn = null;
    try {
      conn = pool.getConnection();

      // code for the servlet using the database goes here

      rs.close();
      stmt.close();
    } catch (SQLException e) {
      throw new ServletException(e);
    } finally {
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException e) {
      }
    }
  }
}

Servlet Configuration

init-param

Initializes servlet variables. servlet-param defines initial values for getServletConfig().getInitParameter("foo").

The full servlet 2.2 syntax is supported and allows a simple shortcut.

<web-app id='/'>

<servlet servlet-name='test.HelloWorld'>
  <init-param foo='bar'/>

  <init-param>
    <param-name>baz</param-name>
    <param-value>value</param-value>
  </init-param>
</servlet>

</web-app>

load-on-startup

If present, starts the servlet when the server starts.

<web-app id='/'>

<servlet servlet-name='hello'
         servlet-class='test.HelloWorld'>
  <load-on-startup/>
</servlet>

</web-app>

run-at

If present, calls the servlet's service() method at the specified times. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.

The value is a list of 24-hour times when the servlet should be automatically executed. To run the servlet every 6 hours, you could use:

<servlet servlet-name='test.HelloWorld'>
  <run-at>0:00, 6:00, 12:00, 18:00</run-at>
</servlet>

If the hour is omitted, the servlet runs every hour at the specified minute. To run the server every 15 minutes, you could use:

<servlet servlet-name='test.HelloWorld'>
  <run-at>:00, :15, :30, :45</run-at>
</servlet>

servlet

Defines a servlet alias for later mapping.

AttributeDescription
servlet-nameThe servlet's name (alias)
servlet-classThe servlet's class (defaults to servlet-name)
init-paramInitialization parameters
load-on-startupInitializes the servlet when the server starts.
run-atTimes to execute the servlet automatically

The following example defines a servlet alias 'hello'

<web-app id='/'>

<servlet-mapping url-pattern='/hello.html'
                 servlet-name='hello'/>

<servlet servlet-name='hello'
         servlet-class='test.HelloWorld'>
  <init-param title='Hello, World'/>
</servlet>

<servlet servlet-name='cron'
         servlet-class='test.DailyChores'>
  <run-at>3:00</run-at>
</servlet>

</web-app>

servlet-class

Class of the servlet. The CLASSPATH for servlets includes the WEB-INF/classes directory and all jars in the WEB-INF/lib directory.

servlet-name

Alias of the servlet.

servlet-mapping

Maps from a URL to the servlet to execute. The servlet-mapping has a url-pattern to match the URL and a servlet-name to match the configured servlet.

typical servlet-mapping
<servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>test.HelloServlet</servlet-class>
</servlet>

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

Resin allows for a shortcut combining the servlet and the servlet mapping:

shortcut servlet-mapping
<servlet-mapping url-pattern="/hello/*"
                 servlet-class="test.HelloServlet"/>

url-pattern

Matches a set of URLs for servlet-mapping.

PatternDescription
/foo/bar.htmlMatches exactly the /foo/bar.html URL.
/foo/*Matches /foo and any children
*.fooMatches any URL with a .foo extension
/Replaces the default servlet.

/ defines a default handler and /* defines a prefix handler. /* will override extension handlers like *.foo. / will only be used if no other pattern matches.

No default. Either url-pattern or url-regexp is required.


Copyright © 1998-2002 Caucho Technology, Inc. All rights reserved.
Resin® is a registered trademark, and HardCoretm and Quercustm are trademarks of Caucho Technology, Inc.