Java Reference
In-Depth Information
Example 18−2: Counter.java (continued)
}
finally {
try { in.close(); }
catch (Exception e) {}
}
}
}
Running the Counter Servlet
Our web.xml file assigns the name counter to the Counter servlet. The servlet
reads a request parameter also named counter to find the name of the counter
variable to increment and display. Thus, you can test the servlet by pointing your
browser to a URL like the following:
http://localhost:8080/javaexamples2/servlet/counter?counter=numhits
The web.xml file also specifies that the Counter servlet should be invoked when-
ever a file ending with the suffix .count (and beginning with the web application
name) is requested from the web server. (You'll learn how the web.xml file speci-
fies this later in the chapter.) In this case, Counter uses the URL itself as the name
of the counter variable. Test this feature by entering a URL like the following:
http://localhost:8080/javaexamples2/index.html.count
By now, you've probably noticed that the Counter servlet doesn't produce very
interesting output: it just displays a number. This servlet is not very useful when
used on its own; it is intended, instead, to have its output included within the out-
put of other servlets. (We'll explore a couple of ways to do this later in the chap-
ter.) If your web server supports server-side includes (SSI) and the <servlet> tag,
though, you can use this feature to include the output of the Counter servlet in
web pages. (Tomcat does not support the SSI feature, probably because JSP tech-
nology makes SSI largely redundant and unnecessary.) To do so, you might create
a test.shtml file that contains text like the following:
<p>This page has been accessed
<servlet name='/servlet/counter'>
<param name='counter' value='test.shtml'>
</servlet>
times.
Database Access with Servlets
One common use of servlets (and web applications in general) is to provide a
middle-tier of software that sits between the client and backend database servers.
Thus, servlets often use the JDBC API to communicate with database servers.
Example 18-3 is a listing of Query.java , a servlet that accepts a user-entered SQL
query (using an HTML form), executes that query (using JDBC), and then displays
the results of the query (using an HTML table). Figure 18-2 shows sample output
from the servlet.
Search WWH ::




Custom Search