Monday, March 28, 2011

Chapter 26: Returning an Error Code to the Client

In the previous chapter, we learnt what the error codes are and what they signify. We also saw an introduction to servlet exception handling. Before we get any further on this topic of exception handling, we need to know how to send error codes to the browser. That is exactly what we are going to learn now.

So, lets get started!!!

Returning an Error Code to the Client

The servlet is just as prone to logic errors and bugs as standalone applications. Java has a smart facility for handling them in both environments. Let's look at a very simple example of how you might handle an error in a servlet. The TestErrorServlet servlet illustrates the use of the sendError() method. It takes an error code as a parameter and an optional custom message associated with that error

Source Code:

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletException;
import java.io.PrintWriter;
import java.io.IOException;

public class TestErrorServlet extends HttpServlet {

public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.sendError(HttpServletResponse.SC_FORBIDDEN,
"Sorry, restricted to Authorized Personnel.");
}
}

Compile the TestErrorServlet file and hit the servlet with your browser.
The container will send an error message to the client. You should see a page that looks like below.


Previous Chapter: Chapter 25 - Introduction to Servlet Exception Handling

Next Chapter: Chapter 27 - sendError Method

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers