KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SampleServlet


1 import java.io.*;
2 import java.net.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 import org.faceless.report.*;
6 import org.xml.sax.*;
7
8 /**
9  * A sample servlet which loads an XML file from a URL and turns
10  * it into a PDF. If you have a Servlet 2.3 container like Tomcat 4, the
11  * PDFFilter is a simpler option.
12  *
13  * Most of the work for this is encapsulated in the PDFProxyServlet class,
14  * and the only thing we absolutely have to implement is the getProxyURL()
15  * method, which returns the URL of the XML report to convert.
16  *
17  * In this simple example, we take the report from "PathInfo" field of the
18  * request - this is any part of the request URL that comes after the
19  * "/servlet/SampleServlet" prefix. An example request would be:
20  *
21  * http://www.company.com/servlet/SampleServlet/path/to/test.xml
22  *
23  * This will proxy the request to "http://www.company.com/path/to/test.xml"
24  *
25  * For more complex requirements, the PDFProxyServlet class can be replaced
26  * with a home-grown equivalent - the source is supplied with this package.
27  *
28  *
29  * Note that we really DO NOT recommend using this *exact* example in a live
30  * environment. There are many things to consider, including:
31  *
32  * * masking the URL of the final document from the customer, for security
33  *
34  * * preventing the XML report from being run unless it's called from
35  * this servlet, for security (hint: Check the "X-Proxy" headers and the IP)
36  *
37  * * enabling search engines (OK, just Google currently) to read and store
38  * the PDF documents - a search engine won't pick it up if the URL has
39  * a query string, like this example.
40  *
41  *
42  * Finally, if the servlet doesn't run because it can't find the SAX parser,
43  * add the "org.xml.sax.driver" parameter in it's initialization parameters
44  * (in "WEB-INF/web.xml"). The value should be the classname of your SAX parser.
45  *
46  * $Id: SampleServlet.java,v 1.8 2003/12/05 13:19:06 mike Exp $
47  */

48 public class SampleServlet extends PDFProxyServlet
49 {
50     public String JavaDoc getProxyURL(HttpServletRequest req, HttpServletResponse res)
51         throws ServletException, IOException
52     {
53     String JavaDoc dest = req.getPathInfo();
54     if (req.getQueryString()!=null) dest += "?"+req.getQueryString();
55     URL thisurl = new URL(HttpUtils.getRequestURL(req).toString());
56
57         try {
58             if (dest==null) throw new MalformedURLException();
59             URL url = new URL(thisurl, res.encodeURL(dest));
60             System.err.println("PDF REPORT: Proxying request to "+url);
61         return url.toString();
62         } catch (MalformedURLException e) {
63             res.sendError(404, "Illegal URL \""+dest+"\"");
64         return null;
65         }
66     }
67 }
68
Popular Tags