First Servlet: Generating an HTML Page
Problem
You want a servlet to present some information to the user.
Solution
Override the HttpServlet
method service( )
, or doGet( )
/doPost( )
.
Discussion
The abstract class
javax.servlet.Servlet
is designed for those who wish to
structure an entire web server around the servlet notion. For
example, in Sun’s Java Web Server, there is a servlet subclass
for handling plain HTML pages, another for processing CGI programs,
and so on. Unless you are writing your own web server, you will probably not
extend from this class, but rather its subclass
HttpServlet
, in the package
javax.servlet.http
. This class has a method:
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
The service method is passed two arguments,
request
and response
. The
request contains all the information about the request from the
browser, including its input stream should you need to read data. The
response argument contains information to get the response back to
the browser, including the output stream to write your response back
to the user.
But the web has several HTTP methods for passing data into a web page. Unimportant for plain HTML pages, this distinction becomes of interest when processing forms, i.e., web pages with fill-in-the-blank or choice items. Briefly, the GET method of HTTP is used to pass all the form data appended to the URL. GET URLs look like this, for example:
http://www.acmewidgets.com/cgi-bin/ordercgi?productId=123456 ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.