Recipe 9.4 Sending an Error from a JSP


You want to use a JSP to manually send a response error to a client.


Use the response implicit object and the sendError method inside a JSP scriptlet.


If you want to send a response error from a JSP, then simply grab the response implicit object inside a scriptlet and call sendError( ) on it. Make sure not to call sendError( ) after already flushing or committing the response to the client, or the method will throw a java.lang.IllegalStateException . The JSP code in Example 9-4, which could be a standalone JSP or a fragment of a larger page, results in the display of Figure 9-3 when requested with the following query string: "?client-unauthorized=true".

Example 9-4. Using the response implicit object to send a response error from a JSP
 <%@ taglib uri=   "" prefix="c" %> <c:if test="${param.client-unauthorized}" >  <% response.sendError(401,      "You are not authorized to view the requested component");      %>  </c:if> 

See Also

Recipe 9.1 on declaring exception handlers in the deployment descriptor; Recipe 9.2 on developing a servlet error handler; Recipe 9.3 on sending an error from a servlet; Recipe 9.5 on using JSPs to handle errors; Recipe 9.6 on declaring in a JSP that another JSP will handle its exceptions; Chapter 1 on the deployment descriptor; the Java servlet specification, which covers error handling in Chapter SRV.9.9:

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: