20.3 Another Simple Servlet
You may recall Example 11-18, an error handler utility
class that displays Java exceptions to the user in a dialog box and
allows them to be reported to a server through a URL. The servlet
shown in Example 20-2 is the server-side portion of
that example: it handles an HTTP POST request from the
ErrorHandler class, deserializes the exception,
and returns a response. (The response claims that the exception has
been recorded, when in fact it is simply discarded. Saving the
exception to a database is left as an exercise;
we'll see an example later in the chapter of a
servlet that does communicate with a database.)The code for this example is simple. It demonstrates the use of
ServletRequest.getInputStream( ) to read the body
of an HTTP POST request and the use of
HttpServletResponse.sendError( ) to send an HTTP
error.
Example 20-2. ErrorHandlerServlet.java
package je3.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
* This servlet is the server-side companion to the
* ErrorHandler.reportThrowable( )
utility method developed elsewhere in this
* this book; it responds to the HTTP POST
request initiated by that method.
**/
public class ErrorHandlerServlet extends HttpServlet {
// This servlet only supports HTTP POST requests
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
ObjectInputStream in =
new ObjectInputStream(request.getInputStream( ));
try {
Throwable throwable = (Throwable) in.readObject( );
// Exercise: save the throwable to a database, along with
// the current time, and the IP address from which it was reported.
// Our response will be displayed within an HTML document, but
// it is not a complete document itself. Declare it plain text,
// but it is okay to include HTML tags in it.
response.setContentType("text/plain");
PrintWriter out = response.getWriter( );
out.println("Thanks for reporting your <tt>" +
throwable.getClass( ).getName( ) + "</tt>.<br>" +
"It has been filed and will be investigated.");
}
catch(Exception e) {
// Something went wrong deserializing the object; most likely
// someone tried to invoke the servlet manually and didn't provide
// correct data. We send an HTTP error because that is the
// easiest thing to do. Note, however that none of the HTTP error
// codes really describes this situation adequately.
response.sendError(HttpServletResponse.SC_GONE,
"Unable to deserialize throwable object");
}
}
}
20.3.1 Testing the Error Handler
If you use the je3.war file, the
ErrorHandlerServlet
will be at this URL:
http://localhost:8080/je3/ErrorHandler
To test it, you can't just enter that URL into a web
browser. Doing so would issue an HTTP GET request, which the servlet
does not support. Instead, run the
ErrorHandler$Test program shown in Example 11-18, and submit a report that way. You should see
the servlet's response in the dialog box.