An outline of a resource-serving servlet.

Component Java
The road to reusable Servlet components
by Attila Szegedi
Listing 2. An outline of a resource-serving servlet.


package com.foo.myapp;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ResourceServlet
extends
  HttpServlet
{
  private static final long lastModified =
    System.currentTimeMillis();

  protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
  throws
    ServletException,
    IOException
  {
    InputStream in =
      getClass().getResourceAsStream(
        request.getPathInfo());
    if(in == null)
    {
      response.sendError(
        HttpServletResponse.SC_NOT_FOUND);
      return;
    }
    try
 {
      OutputStream out =
         response.getOutputStream();
      byte[] buf = new byte[1024];
      for(;;)
      {
         int len = in.read(buf);
         if(len == -1) break;
         out.write(buf, 0, len);
      }
 }
    finally
    {
      in.close();
    }
  }

  protected long getLastModified(
    HttpServletRequest request)
  {
     return lastModified;
  }
}

About the Author

Attila Szegedi is the lead developer at Scriptum, a company located in Szeged, Hungary, specializing in information retrieval and data cleansing technologies. Attila may be contacted at szegedia@freemail.hu.

Featured

Most   Popular
Upcoming Events

AppTrends

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.