Until now, we have created a new HTML page for the guest book every time a guest is added or some information is changed. This may not be the best solution, since the web server may get a request for the guest book page at the same time we are updating it, meaning that the user will get an incomplete page. Instead, we should query the database dynamically whenever the user wants to view the guest book.
In this exercise, you will write a servlet that retrieves all information from the database and dynamically writes an HTML page that is sent to the user. This HTML page is never written to disk - it is sent directly from the servlet to the web browser.
A servlet is to a server what an applet is to a client: Some Java code that executes within the ``main'' program, adding new capabilities. The Java Web Server uses servlets, and there are many other web servers that support servlets.
For those of you familiar with CGI programming, servlets are similar - but far more efficient, since they are linked into the web server, and safer to use, since they can be executed within a servlet sandbox similar to the applet sandbox in a web browser.
The following links may be useful:
Create a new class called server.GuestBookServlet (the web server is preconfigured for a servlet of that name). Since your servlet will create an HTML page, it should extend javax.servlet.HttpServlet.
Most of the code you will need is already written. In JDBCDatabase, you have all the code you need for retrieving a set of users from the database; you have also written code that creates an HTML page containing those users.
The servlet method that is normally called by the server is doGet(); you should implement this method.
Due to the way the lab environment was installed, it is unfortunately impossible for the web server to access servlet code that is not in the server package. This means you cannot reuse your UserInfo class, since it is in the common package. Instead, you can let the code that generates the HTML page access the database directly.
When you have completed your servlet, you must copy GuestBookServlet.class
(and any other classes it refers to in the servlet package) to the
c:\tddi48\javawebserver1.0.3\servlets\server directory. You can then try to load
the page http://localhost:8080/dynamic-guestbook.html.
This page is configured in the web server as an alias for the guest book servlet.
You should get the same result by loading http://localhost:8080/servlets/guestbook.
If you need to recompile your servlet, you must remember to put the new class file in
c:\tddi48\javawebserver1.0.3\servlets\server. The web server should detect
that the class file has changed and reload the servlet, but in some cases, it may fail.
In that case, you can shut down the server and restart it (from the administration
interface, http://localhost:9090).