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
006 package fc.web.servlet;
007
008 import javax.servlet.*;
009 import javax.servlet.http.*;
010 import java.io.*;
011 import java.util.*;
012 import fc.web.servlet.*;
013 import fc.io.*;
014
015 /**
016 A convenient base class for servlets that use path info (must
017 be path mapped; extension mapped servlets (like *.mp) do not
018 have any path info associated with them.
019 <p>
020 If the request has a non-null non-empty path, then that path
021 is sent to the {@link doPathInfo doPathInfo} method, which
022 a subclass should implement. A request with an empty or null
023 path info results in sending a 404 error back to the client.
024
025 @author hursh jain
026 */
027 public abstract class PathServlet extends javax.servlet.http.HttpServlet
028 {
029 private static final boolean dbg = false;
030
031 public void init(ServletConfig conf) throws ServletException
032 {
033 super.init();
034 }
035
036 public void doPost(final HttpServletRequest req, final HttpServletResponse res)
037 throws ServletException, IOException
038 {
039 doGet(req, res);
040 }
041
042 public void doGet(final HttpServletRequest req, final HttpServletResponse res)
043 throws 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 /**
061 Sends a 404 (page not found) error to the client. Invoke
062 this method if there is missing/bad path info and return
063 from the servlet.
064 */
065 public void error(final HttpServletResponse res, final String msg)
066 throws IOException
067 {
068 res.sendError(res.SC_NOT_FOUND, msg);
069 }
070
071 /**
072 The pathinfo parameter is not <tt>intern()</tt>'ed but can be
073 if/as needed in this method.
074 */
075 public abstract void doPathInfo(final HttpServletRequest req, final HttpServletResponse res, String pathinfo)
076 throws ServletException, IOException;
077 }