Getting Started with Java Servlets using Apache JServ (
Page 1 of 5 )
In the quest for more dynamic content, web server technologies have flourished. One particular solution to provide this dynamic content is Java Servlet technology. As a
replacement to the traditional CGI script approach, servlets give developers a powerful tool to create web enabled applications. Not only does the servlet solution give developers
the ease of using the Java language, it is also offers a more efficient solution in terms of CPU power.In the quest for more dynamic content, web server technologies have
flourished. One particular solution to provide this dynamic content is Java
Servlet technology. As a replacement to the traditional CGI script approach,
servlets give developers a powerful tool to create web enabled applications. Not
only does the servlet solution give developers the ease of using the Java
language, it is also offers a more effecient solution in terms of CPU power.
A variety of servlet engines have been implemented to take advantage of this
rapidly maturing technology. However, in the majority of these products, the
sheer price of the commercial servlet engines puts this technology out of the
hands of developers without the cash to front for these products.
Enter Apache, the internet's most popular web server. The Apache group has
already proven the ability of open source to produce high quality, mission
critical software. The Apache-Jserv project is an open-source implementation of
Suns' servlet specification. For those of you that want to hack on this stuff at
home on your linux box, to those that want to deploy servlet technology for
business critical applications, Apache Jserv delivers an easily accessible,
robust solution.
Some of the benefits of servlets over CGI include:
- Faster than CGI scripts. Since the servlets are kept in memory, each request
handled by a servlet doesn't have to fork a new process as is the case with
traditional CGI scripts.
- The ability to leverage all of the advantages of the Java programming
language, including platform independence.
- The ability to use a variety of API's available to the Java platform.
- Session Management (Persistence)
This introductory article to servlets will review how a servlet works, and
also go into detail explaining an example servlet demonstrating how one might
leverage JDBC and sessions with servlets.
{mospagebreak title=How the
servlet class works}
Because servlets are kept loaded in the servlet engine's JVM, each incoming
request does not need to instantiate a new servlet class. Once the servlet
environment is initialized, the servlet is then loaded and the servlet's
service() method handles requests. However, you should be aware that more than
one instance of your servlet can be loaded in the JVM, depending on the server
load and the configuration of your servlet engine.
Each servlet must either directly or indirectly implement the
javax.servlet.Servlet interface. Typically, it is most convenient to
extend the javax.servlet.http.HttpServlet class and override the
doGet() and/or doPost() methods. The servlet API also allows
for handling other types of HTTP 1.1 requests, like DELETE,
PUT, TRACE, and OPTIONS. Since these types of HTTP
1.1 requests are uncommonly used, most developers will be interested in the
doGet() and doPost() methods.
Two important classes your should know about are HttpServletRequest
and HttpServletResponse.
The HttpServletRequest object contains methods which let you inspect
it and find information on the request type. In PERL CGI's, a lot of these
variables are found in the %ENV associative array; things like
METHOD (getMethod()), REMOTE_ADDR
(getRemoteAddr), CONTENT_LENGTH (getContentLength()),
etc. Data passed to the servlet in forms is automatically parsed from the
QUERY_STRING or what's received from a POST request. These
form variables are accessed by the getParameter(String name) method,
where the name is the name of the variable set in the HTML form.
The HttpServletResponse's most popular method would probably be its
getWriter() method. This returns a PrintWriter to which you can
println() output. If you servlet is going to be returning binary data,
like a dynamically created gif or jpg, you would then need to use
getOutputStrem() instead.
Servlet Lifecycle
- init()
When the servlet is first requested, it is loaded by the servlet
implementation's classloader and the servlet's init() is called. This
is where you initialize expensive resources, like database connections, for
example.
- service()
Once the servlet's init() method is finished executing, the servlet
is now in a 'ready' state, waiting to handle requests. Once a request comes in
to which the servlet is mapped to service, the service() method is
executed.
Depending on the HTTP 1.1 request type (typically GET or
POST), the service() method then passes the request on to the
doGet() method if it is a GET request, or the
doPost() method if it is a POST request. Usually POST
requests are used for submitting data, while GET requests are for
retrieving data.
- destroy()
Servlet engines are not required to keep the servlets in memory. If they
should decide to unload a servlet to conserve resources or for what ever other
reason, the servlet's destroy() method will be called. This allows the
servlet to do things like save its current state and release resources before
being unloaded.
Quick Example
Here's a quick example of how a simple servlet works (Hello.java).
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Hello extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get an PrintWriter from the response object
PrintWriter out = response.getWriter();
// prepare the response's content type
response.setContentType("text/html");
// get the IP address of the client
String remoteAddress = request.getRemoteAddr();
// print to the output stream!
out.println("Hello there, web surfer from <b>" + remoteAddress + "</b>");
}
}
The servlet is invoked when a URL mapped to the servlet ( like
http://[domain]/servlet/Hello ) is requested. If it is not already loaded
in the JVM, the servlet engine loads the servlet and calls the init()
method. Now the servlet is 'ready' to handle requests, and the service(
HttpServletRequest, HttpServletResponse ) method is now called. The
service() method inspects the request object, and passes the
HttpServletRequest and HttpServletResponse objects to the
appropriate handler method. In this case, this servlet is only equipped to
handle GET requests. If a POST or some other HTTP 1.1 request
was handled by the servlet, the client browser would get a "<METHOD>
not supported by this URL" error message. The servlet finishes executing
the doGet() method and then waits for another request to service.