001// Copyright (c) 2001 Hursh Jain (http://www.mollypages.org) 
002// The Molly framework is freely distributable under the terms of an
003// MIT-style license. For details, see the molly pages web site at:
004// http://www.mollypages.org/. Use, modify, have fun !
005
006package fc.web.servlet;
007
008import javax.servlet.*;
009import javax.servlet.http.*;
010import java.io.*;
011import java.util.*;
012import fc.web.servlet.*;
013import fc.io.*;
014
015/**
016A convenient base class for servlets that use path info (must
017be path mapped; extension mapped servlets (like *.mp) do not
018have any path info associated with them.
019<p>
020If the request has a non-null non-empty path, then that path
021is sent to the {@link doPathInfo doPathInfo} method, which 
022a subclass should implement. A request with an empty or null
023path info results in sending a 404 error back to the client.
024
025@author hursh jain
026*/
027public abstract class PathServlet extends javax.servlet.http.HttpServlet
028{
029private static final boolean dbg = false;
030
031public void init(ServletConfig conf) throws ServletException 
032  {
033  super.init();
034  }
035  
036public void doPost(final HttpServletRequest req, final HttpServletResponse res) 
037throws ServletException, IOException
038  {
039  doGet(req, res);
040  }
041  
042public void doGet(final HttpServletRequest req, final HttpServletResponse res) 
043throws ServletException, IOException
044  {
045  res.setContentType("text/html");
046  final String pathinfo = req.getPathInfo();
047  if (dbg) {
048    final PrintWriter out = res.getWriter();
049    out.println("PathInfo: "+ pathinfo);
050    }
051    
052  if (pathinfo == null || pathinfo.length() == 0) {
053    error(res, "Page not found");
054    return;
055    }
056  
057  doPathInfo(req, res, pathinfo);
058  }
059
060/**
061Sends a 404 (page not found) error to the client. Invoke
062this method if there is missing/bad path info and return
063from the servlet.
064*/
065public void error(final HttpServletResponse res, final String msg)
066throws IOException
067  {
068  res.sendError(res.SC_NOT_FOUND, msg);
069  }
070
071/**
072The pathinfo parameter is not <tt>intern()</tt>'ed but can be
073if/as needed in this method.
074*/
075public abstract void doPathInfo(final HttpServletRequest req, final HttpServletResponse res, String pathinfo)
076throws ServletException, IOException;
077}