DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Java Servlet

02.10.2007
| 6897 views |
  • submit to reddit
        // Simple Servlet Skeleton

package net.tvs.servlet;

import java.io.IOException;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyServlet extends HttpServlet
{
  private static Log _logger = LogFactory.getLog( MyServlet.class );

  public void init(ServletConfig config) throws ServletException
  {
    super.init( config );
    try
      {
        // Initialization
      }
    catch ( Exception e )
      {
        _logger.fatal( e.getMessage() );
      }
    _logger.info( "MyServlet initialized" );
  }
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    processRequest( request, response );
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    processRequest( request, response );
  }

  protected void processRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException
  {
    response.setContentType( "text/html;charset=UTF-8" );
    String param = request.getParameter( "param" );
    _logger.debug( "Received param: " + param );

    // Implementation...

    PrintWriter out = response.getWriter();
    response.setContentType( "text/xml" );
    response.setHeader( "Cache-Control", "no-cache" );

    out.println( "<response>" );
    out.println( "<param>" + param + "</param>" );
    out.println( "</response>" );
    out.close();
  }

}