Wednesday, June 18, 2008

Java Servlets

Servlets are modules of Java code that run in a server application, similar to "Applets" on the client side. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP.
Servlets make use of the Java classes in "javax.servlet" and "javax.servlet.http" extensions of the Servlet framework for Servlets that answer HTTP requests.

HTTP Servlets are used for:
1) Processing and/or storing data submitted by an HTML form.
2) Providing dynamic content, e.g. returning database query results to the client.
3) Managing state information on top of the stateless HTTP.

Servlets have several advantages over CGI:

1) A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
2) A Servlet stays in memory between requests. A CGI program needs to be loaded and started for each CGI request.
3) There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
4) A Servlet can be run by a Servlet Engine in a restrictive Sandbox.

The Basic Servlet Architecture
A Servlet is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

Servlets run on the web server platform as part of the same process as the web server itself. The web server is responsible for initializing, invoking, and destroying each servlet instance.

The init() method

When a servlet is first loaded, its init() method is invoked. This allows the servlet to per form any setup processing such as opening files or establishing connections to their servers. If a servlet has been permanently installed in a server, it loads when the server starts to run. Otherwise, the server activates a servlet when it receives the first client request for the services provided by the servlet.
The init() method takes one argument, a reference to a ServletConfig object which provides initialization arguments for the servlet. This object has a method getServletContext() that returns a ServletContext object containing information about the servlet's environment.

The service() Method

The service() method is the heart of the servlet. Each request message from a client results in a single call to the servlet's service() method. The method is called concurrently and should be implemented in a thread-safe manner. The service() method reads the request and produces the response message from its two parameters:

A ServletRequest object with data from the client. The data consists of name/value pairs of parameters and an InputStream. Several methods are provided that return the client's parameter information. The InputStream from the client can be obtained via the getInputStream() method. This method returns a ServletInputStream, which can be used to get additional data from the client.

A ServletResponse represents the servlet's reply back to the client. When preparing a response, the method setContentType() is called first to set the MIME type of the reply. Next, the method getOutputStream() or getWriter() can be used to obtain a ServletOutputStream or PrintWriter, respectively, to send data back to the client.

The destroy() Method

The destroy() method is called to allow your servlet to clean up any resources before the servlet is unloaded. There may still be threads that execute the service method when destroy is called, so destroy has to be thread-safe.

In an HTTP Servlet the seervice method analyses the request and calls appropriate doGet, doPost, doHead etc function calls.


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

public class HelloClientServlet extends HttpServlet
{
private ServletConfig config;
public void init (ServletConfig config) throws ServletException
{
this.config = config;
}
public void destroy() {} // do nothing

public ServletConfig getServletConfig()
{
return config;
}

public void service (ServletRequest req,
ServletResponse res
) throws ServletException, IOException {
res.setContentType( "text/html" );
PrintWriter out = res.getWriter();
out.println(" < HTML > < HEAD > < TITLE > Hello Client! < / TITLE >"+
"< / HEAD > < BODY > Hello Client! < / BODY > < / HTML >");
out.close();
}

protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println(" < HTML > < HEAD > < TITLE > Hello Client! < / TITLE >"+
"< / HEAD > < BODY > Hello Client! < / BODY > < / HTML >");
out.close();
}
}

The doGet method replies to GET requests
The doPost method replies to POST requests

No comments: