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.

404Chapter 18Servlets: Java Pressed into Service18.2SERVLETS: PROGRAM-CENTRIC SERVER-SIDE DOCUMENTSServlets are Java programs that are run by a Web server. At its simplest, a servletis a Java class that is invoked by a Web server (referred to in some c<strong>on</strong>texts asthe servlet’s c<strong>on</strong>tainer). A servlet is run not from the command line as a regularJava program, but by visiting its URL. Point a Web browser at a servlet’s addressand the Web server (the <strong>on</strong>e which serves up that address) will run theservlet and send its output back to the browser (see Figure 18.1). So you cansee that typical output for a servlet is HTML—what better thing to send toa browser?Now, more and more servlets are using XML as their output and thenc<strong>on</strong>verting it to HTML via XSLT stylesheets, but we’re trying to keep thingssimple here.In their most generic form, servlets are classes which implement theServlet interface. That means that they provide three methods:• init(ServletC<strong>on</strong>fig c<strong>on</strong>fig)• service(ServletRequest request, ServletResp<strong>on</strong>se resp<strong>on</strong>se)• destroy()The init() method gets called when the Web server starts up the class.(Think of the init() method as a c<strong>on</strong>structor; Java doesn’t allow c<strong>on</strong>structorsto be defined for interfaces, so init() plays that role.)The destroy() method gets called whenever the Web server takes theservlet out of service. This might happen when a system administrator wantsto shut down the system, or shut down just that particular Web service.Naturally, the service() method is the method that gets called wheneverrequests for this servlet arrive at the Web server. The server knows that the requestedservice is provided by this servlet, so it packages up certain data andsends it al<strong>on</strong>g as a request to the servlet. Thus, servlets can provide data in thisgeneric request/resp<strong>on</strong>se kind of protocol. Simple, but vague, right now.Servlets get a bit more interesting when we look at the HttpServlet class.This class extends Servlet and adds two more methods that must beimplemented:• doGet(HttpServletRequest request, HttpServletResp<strong>on</strong>seresp<strong>on</strong>se)

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

Saved successfully!

Ooh no, something went wrong!