01: /*
02: * Copyright 1999-2004 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: /*
17: * $Id: SimpleXSLTServlet.java,v 1.1 2006-06-27 14:42:52 sinisa Exp $
18: */
19: package servlet;
20:
21: import javax.servlet.*;
22: import javax.servlet.http.*;
23: import java.io.*;
24: import java.net.URL;
25:
26: import javax.xml.transform.TransformerFactory;
27: import javax.xml.transform.Transformer;
28: import javax.xml.transform.Source;
29: import javax.xml.transform.stream.StreamSource;
30: import javax.xml.transform.stream.StreamResult;
31:
32: /*
33: * This sample applies the todo.xsl stylesheet to the
34: * todo.xml XML document, and returns the transformation
35: * output (HTML) to the client browser.
36: *
37: * IMPORTANT: For this to work, you must place todo.xsl and todo.xml
38: * in the servlet root directory for documents.
39: *
40: */
41:
42: public class SimpleXSLTServlet extends HttpServlet {
43:
44: /**
45: * String representing the file separator characters for the System.
46: */
47: public final static String FS = System
48: .getProperty("file.separator");
49:
50: public void init(ServletConfig config) throws ServletException {
51: super .init(config);
52: }
53:
54: public void doGet(HttpServletRequest request,
55: HttpServletResponse response) throws ServletException,
56: IOException, java.net.MalformedURLException {
57: // The servlet returns HTML.
58: response.setContentType("text/html; charset=UTF-8");
59: // Output goes in the response stream.
60: PrintWriter out = response.getWriter();
61: try {
62: TransformerFactory tFactory = TransformerFactory
63: .newInstance();
64: //get the real path for xml and xsl files.
65: String ctx = getServletContext().getRealPath("") + FS;
66: // Get the XML input document and the stylesheet.
67: Source xmlSource = new StreamSource(new URL("file", "", ctx
68: + "birds.xml").openStream());
69: Source xslSource = new StreamSource(new URL("file", "", ctx
70: + "birds.xsl").openStream());
71: // Generate the transformer.
72: Transformer transformer = tFactory
73: .newTransformer(xslSource);
74: // Perform the transformation, sending the output to the response.
75: transformer.transform(xmlSource, new StreamResult(out));
76: } catch (Exception e) {
77: out.write(e.getMessage());
78: e.printStackTrace(out);
79: }
80: out.close();
81: }
82:
83: }
|