The Servlet Basic Structure

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Created on 19th July 2008
 */
package com.kushal.servlets;
/*
 * This is a basic servlet class that shows how
 * servlet can be structured.
 */
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyFirstServlet extends HttpServlet {

/**
 * This is GET method. Request has parameters, 
 * and we write back using response.
 */	
public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
      
    PrintWriter out = response.getWriter();
    
    out.write("Hello, this is my first servlet");    
  }

/**
 * This is another kind of request with POST
 * kind of submission. We can simply reroute
 * the request to doGetmethod as below.
 */
public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
	  doGet(request, response);	  
  }
}

/**
 * In order to be able to run this servlet, you have
 * to setup a proper application server and deploy
 * the servlet. Discussing those steps is out of
 * scope in this post.
 */

How to print HttpServletRequest’s All Available Request Parameters and Request Attributes

If you ever debugged your J2EE application, you know the pain of finding out where you request parameters are on the HttpServletRequest object. I always get lost when I am inspecting the request object because it holds so much onto it. This example here shows you how to print all available request parameters and request attributes so you can easily look at what values those attribtues and parameters are holding.

If you run this servlet, you should be able to print these parameters and attributes on to you browser itself.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * www.icodejava.com
 * 
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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

import com.ibm.ws.http.HttpConnection;
import com.ibm.ws.http.HttpRequest;

public class HttpRequestParamsAndAttributesPrintServlet extends HttpRequest{

    public HttpRequestParamsAndAttributesPrintServlet(HttpConnection connection) {

        super(connection);

    }

    public void doGet(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();

        printRequestAttributes(req, out);

        printRequestParameters(req, out);

    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException {
        
        doGet(req, res);
    }

    /**
     * This method prints all the request parameters that are 
     * available on the HttpServletRequest.
     * 
     * The result will be printed back to the browser
     *
     */
    private void printRequestParameters(HttpServletRequest req, PrintWriter out) {

        out.println("Printing All Request Parameters From HttpSerlvetRequest:");

        Enumeration<String> requestParameters = req.getParameterNames();
        while (requestParameters.hasMoreElements()) {
            String paramName = (String) requestParameters.nextElement();
            out.println("Request Paramter Name: " + paramName 
                            + ", Value - " + req.getParameter(paramName));
        }
    }

    /**
     * This method prints all the request attributes that are 
     * available on the HttpServletRequest.
     * 
     * The result will be printed back to the browser.
     *
     */
    private void printRequestAttributes(HttpServletRequest req, PrintWriter out) {

        out.println("Printing All Request Parameters From HttpSerlvetRequest:");

        Enumeration<String> requestAttributes = req.getAttributeNames();
        while (requestAttributes.hasMoreElements()) {
            String attributeName = (String) requestAttributes.nextElement();
            out.println("Request Attribute Name: " + attributeName 
                            + ", Value - " + (req.getAttribute(attributeName)).toString());
        }
    }
}

Lifecycle of a Java Servlet – three basic phases of initialize, service and destroy

The total life cycle of a java Servlet lies between the beginning of the servlet loading into the application server memory and ending of the servlet by termination/reload.

Basically there are three phases in the life-cycle of a java servlet.

  • Instantiation and Initialization Phase (using init() method)
  1. Creates the instance of the servlet
  2. If successfully instantiated, the servlet is available for providing service
  3. If failed to instantiate, it will unload the servlet
  • Servicing Phase (using service() method)
  1. Gets information about the request from the request object
  2. Processes the request
  3. Uses methods of the response object to create the client response.
  4. Can invoke other methods to process the request, such as doGet(), doPost(), or other custom methods.
  • Termination Phase (using destroy() methods)
  • Stops a servlet by invoking the servlet’s destroy() method.
  • The destroy() method runs only one time during the lifetime of the servlet and signals the end of the servlet.
  • After calling destroy() method, the servlet engine unloads the servlet
  • Unloaded servlets are collected by JVM Garbage Collection