19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

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

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

public void destroy() {<br />

...<br />

}<br />

}<br />

// Other methods if necessary<br />

The servlet engine controls the servlets using init, doGet, doPost,<br />

destroy, and other methods. By default, the doGet and doPost methods do<br />

nothing. To handle a GET request, you need <strong>to</strong> override the doGet method;<br />

<strong>to</strong> handle a POST request, you need <strong>to</strong> override the doPost method.<br />

Listing 42.2 gives a simple <strong>Java</strong> servlet that generates a dynamic Web<br />

page for displaying the current time, as shown in Figure 42.15.<br />

Figure 42.15<br />

Servlet CurrentTime displays the current time.<br />

Listing 42.2 CurrentTime.java<br />

<br />

<br />

<br />

<br />

package chapter42;<br />

import javax.servlet.*;<br />

import javax.servlet.http.*;<br />

import java.io.*;<br />

public class CurrentTime extends HttpServlet {<br />

/** Process the HTTP Get request */<br />

public void doGet(HttpServletRequest request, HttpServletResponse<br />

response) throws ServletException, IOException {<br />

response.setContentType("text/html");<br />

PrintWriter out = response.getWriter();<br />

out.println("The current time is " + new java.util.Date());<br />

out.close(); // Close stream<br />

}<br />

}<br />

The HttpServlet class has a doGet method. The doGet method is invoked<br />

when the browser issues a request <strong>to</strong> the servlet using the GET method.<br />

Your servlet class should override the doGet method <strong>to</strong> respond <strong>to</strong> the<br />

GET request. In this case, you write the code <strong>to</strong> display the current<br />

time.<br />

Servlets return responses <strong>to</strong> the browser through an HttpServletResponse<br />

object. Since the setContentType("text/html") method sets the MIME type<br />

<strong>to</strong> “text/html,” the browser will display the response in HTML. The<br />

getWriter method returns a PrintWriter object for sending HTML back <strong>to</strong><br />

the client.<br />

15

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

Saved successfully!

Ooh no, something went wrong!