Java Reference
In-Depth Information
Outputting HTML Code from a Servlet
In addition to forwarding or redirecting a request to another servlet, a JSP,
or an HTML page, a servlet can write the HTML code directly back to the server,
which then sends it to the client browser. This approach embeds the HTML code
for a Web page in the Java servlet. As a result, the HTML code is written by a Java
programmer, not a Web page designer. HTML tools cannot be used to create the
Web page. Therefore, unlike a JSP, the page is not visible until the servlet executes
and creates it, which makes designing the page more difficult. Finally, this
approach subtracts from the goal of the MVC approach to separate the user inter-
face from the controller code; it is presented here for illustrative purposes only.
The WebStocks servlet includes code that outputs a simple HTML Web page
with an error message when an invalid action or null action is requested or when
an error, such as an SQL Exception, occurs. As discussed earlier, writing HTML
code to the client browser is similar to writing output to the console using the
System.out object. Because a PrintWriter object was obtained and the MIME
type was set in lines 84 and 85, all that remains is to use the println() method
just as you would with System.out. Figure 12-30 displays lines 200 through 276
of the WebStocks servlet code.
(continued)
FIGURE 12-30
Search WWH ::




Custom Search