13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

18.4 How to Write a Servlet407formatting to be changed (e.g., to apply a new corporate look to the pages)without changing the c<strong>on</strong>tent or the programs that generate the c<strong>on</strong>tent.Since a Web server (e.g., Apache Tomcat) is typically c<strong>on</strong>figured to runc<strong>on</strong>stantly, that is, to always be around, then a servlet is also always around.(The Web server keeps a reference to the class, so the class is not garbage collected—henceits persistence.) Well, “always” here means “as l<strong>on</strong>g as the Webserver and the operating system are up and running.”An aside: Not all servlets are for Web browsing. Sometimes servlets canbe used as daem<strong>on</strong>s that hang around in the background doing other tasks(e.g., background processing of some database records). The browser interface,if any, may <strong>on</strong>ly be for the purpose of providing an administrative interface tothe daem<strong>on</strong>. The administrator would then have a Web page to which to go,in order to see how many records have been processed. This page may also havebutt<strong>on</strong>s to reset, restart, or shut down the process. While we typically think ofservlets being for the producti<strong>on</strong> of dynamic Web pages, here the Web pageswould <strong>on</strong>ly be an aside to the real purpose, that of processing database records.18.4HOW TO WRITE A SERVLETSo how do you write a servlet? You may already have figured it out, from whatwe’ve described so far. You need to:• Write a Java class that extends HttpServlet• In that class, write the following methods:• init()• destroy()• doGet() and/or doPost()That’s the basic idea. There are lots of details about what arguments aresupplied, what other resources are available, what methods can be used to getat parameters, and so <strong>on</strong>. We’ll discuss some of those in our example servlet.Let’s start with a simplistic servlet, <strong>on</strong>e that will dynamically generate the“Hello, world” string as a Web page (Example 18.1).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!