Chapter 19. Odds and Ends
Every house has a junk drawerâa drawer loaded to the brim with odds and ends that donât exactly fit into any organized drawer and yet canât be thrown away because when theyâre needed theyâre really needed. This chapter is like that drawer. It holds a whole slew of useful servlet examples and tips that donât really fit anywhere else. Included are servlets that parse parameters, send email, execute programs, use regular expression engines, use native methods, and act as RMI clients. Thereâs also a demonstration of basic debugging techniques, along with some suggestions for servlet performance tuning.
Parsing Parameters
If youâve tried your hand
at
writing your own servlets as you have been reading through this book,
youâve probably noticed how awkward it can be to get and parse
request parameters, especially when the parameters have to be
converted to some non-String
format. For example,
letâs assume you want to fetch the count
parameter and get its value as an int
.
Furthermore, letâs also assume that you want to handle error
conditions by calling handleNoCount( )
if
count
isnât given and
handleMalformedCount( )
if
count
cannot be parsed as an integer. To do this
using the standard Servlet API requires the following code:
int count; String param = req.getParameter("count"); if (param == null || param.length() == 0) { handleNoCount(); } else { try { count = Integer.parseInt(param); } catch (NumberFormatException e) { handleMalformedCount(); ...
Get Java Servlet Programming, 2nd Edition 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.