- Client-Side Versus Server-Side Transforms
- Java Servlet Transform
- JAXP and XSLT
- The XML Data Adapter
- Summary
- References
Java Servlet Transform
Java servlets are Java classes that are deployed and executed on a web server. Servlet-aware servers such as Apache Tomcat are configurable so that a browser request can be mapped to a servlet. For example, consider the following request:
http://www.zwiftbooks.com/xsltservlet/TopBooks
With server configuration, we can trigger the execution of a servlet that executes our XSLT and returns HTML to the browser. To see some of the details of how this works, let’s consider a simple servlet (shown in Listing 1) that does nothing other than deliver a web page saying "Hello Servlet World." Later we’ll look at how this same process can be used to execute our XSLT.
Listing 1 HelloWorldServlet illustrating basic servlet technology.
1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. public class HelloWorldServlet extends HttpServlet { 6. 7. public void doGet(HttpServletRequest request, 8. HttpServletResponse response) 9. throws IOException, ServletException 10. { 11. // Tell the response object what kind of content is coming 12. response.setContentType("text/html"); 13. 14. // Ask the response object for a PrintWriter stream 15. PrintWriter out = response.getWriter(); 16. 17. // Write some HTML to the output stream 18. out.println("<html>"); 19. out.println("<head><title>HelloWorldServlet</title></head>"); 20. out.println("<body><h1>Hello Servlet World</h1></body>"); 21. out.println("</html>"); 22. } 23. }
Listing 1 shows the source code for the HelloWorldServlet. Our Java class inherits from HttpServlet (line 5), which all servlets must do to run on a web server. This step sets things up so that the web server can make the call to the servlet’s doGet method (line 7) when a request arrives. When doGet is called, two parameters are passed: HttpServletRequest and HttpServletResponse. These two objects are key to dynamic web page generation. In line 15, the servlet asks the HttpServletResponse object for a handle to a stream that’s tied directly to the browser. Whatever the server writes to the output stream is sent to the browser. Here we see the servlet writing some HTML (lines 18–21). And that’s it—dynamic web page generation.