Java Reference
In-Depth Information
Before we look at the output from this Web page, we need to consider just what
our servlet will look like…
Servlet Structure
Servlets must import the following two packages:
As of Tomcat 7, it is also necessary to import the following annotation type:
In addition, since servlet output uses a PrintWriter stream, package is
required. Servlets that use the HTTP protocol (which means all servlets, at the
present time) must extend class HttpServlet from package java.servlet.http . The two
most common HTTP requests (as specifi ed in the HTML pages that make use of
servlets) are GET and POST . At the servlet end, method service will despatch either
method doGet or method doPost in response to these requests. The programmer
should override (at least) one of these two methods.
You should use the POST method for multiple data items and/or items that need
to be transmitted securely. If you are transmitting just single items that have no
security implications, then use GET . All three methods ( doGet , doPost and service )
have a void return type and take the following two arguments:
an HttpServletRequest object;
an HttpServletResponse object.
The former encapsulates the HTTP request from the browser and has several
methods, but none will be required by our fi rst servlet. The second argument holds
the servlet's response to the client's request. There are just two methods of this
HttpServletResponse object that are of interest to us at present and these are
shown below.
void setContentType(String <type>)
This specifi es the data type of the response. Normally, this will be “ text/HTML” .
PrintWriter getWriter()
Returns the output stream object to which the servlet can write character data to
the client (using method println ).
There are four basic steps in a servlet…
1. Execute the setContentType method with an argument of “ text/HTML ”.
2. Execute the getWriter method to generate a PrintWriter object.
3. Retrieve any parameter(s) from the initial Web page.
(Not required in our fi rst servlet.)
4. Use the println method of the above PrintWriter object to create elements of the
Web page to be 'served up' by our Web server.
Search WWH ::

Custom Search