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 ...
Get Java Examples in a Nutshell, 3rd 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.