Chapter 13. 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’ve read 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 assume 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(); } }
Does this look like any code you’ve ...
Get Java Servlet Programming 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.