BBxServletResponse::sendError

Description

In BBj 21.00 and higher, this method sends an error response to the client using the specified status and clears the buffer.

The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html". The server will preserve cookies and may clear or update any headers needed to serve the error page as a valid response. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested message parameter and the message parameter will be ignored.

If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.

Syntax

Return Value Method
void sendError(int statusCode)
void sendError(int statusCode, String message)

Parameters

Parameter Description
statusCode The status code of the error.
message A descriptive error message.

Return Value

None.

HttpServletResponse Status Codes

Status Code Value Description
SC_ACCEPTED 202 Status code (202) indicating that a request was accepted for processing, but was not completed.
SC_BAD_GATEWAY 502 Status code (502) indicating that the HTTP server received an invalid response from a server it consulted when acting as a proxy or gateway.
SC_BAD_REQUEST 400 Status code (400) indicating the request sent by the client was syntactically incorrect.
SC_CONFLICT 409 Status code (409) indicating that the request could not be completed due to a conflict with the current state of the resource.
SC_CONTINUE 100 Status code (100) indicating the client can continue.
SC_CREATED 201 Status code (201) indicating the request succeeded and created a new resource on the server.
SC_EXPECTATION_FAILED 417 Status code (417) indicating that the server could not meet the expectation given in the Expect request header.
SC_FORBIDDEN 403 Status code (403) indicating the server understood the request but refused to fulfill it.
SC_FOUND 302 Status code (302) indicating that the resource reside temporarily under a different URI.
SC_GATEWAY_TIMEOUT 504 Status code (504) indicating that the server did not receive a timely response from the upstream server while acting as a gateway or proxy.
SC_GONE 410 Status code (410) indicating that the resource is no longer available at the server and no forwarding address is known.
SC_HTTP_VERSION_NOT_SUPPORTED 505 Status code (505) indicating that the server does not support or refuses to support the HTTP protocol version that was used in the request message.
SC_INTERNAL_SERVER_ERROR 500 Status code (500) indicating an error inside the HTTP server which prevented it from fulfilling the request.
SC_LENGTH_REQUIRED 411 Status code (411) indicating that the request cannot be handled without a definedContent-Length.
SC_METHOD_NOT_ALLOWED 405 Status code (405) indicating that the method specified in theRequest-Lineis not allowed for the resource identified by theRequest-URI.
SC_MOVED_PERMANENTLY 301 Status code (301) indicating that the resource has permanently moved to a new location, and that future references should use a new URI with their requests.
SC_MOVED_TEMPORARILY 302 Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource.
SC_MULTIPLE_CHOICES 300 Status code (300) indicating that the requested resource corresponds to any one of a set of representations, each with its own specific location.
SC_NO_CONTENT 204 Status code (204) indicating that the request succeeded but that there was no new information to return.
SC_NON_AUTHORITATIVE_INFORMATION 203 Status code (203) indicating that the meta information presented by the client did not originate from the server.
SC_NOT_ACCEPTABLE 406 Status code (406) indicating that the resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.
SC_NOT_FOUND 404 Status code (404) indicating that the requested resource is not available.
SC_NOT_IMPLEMENTED 501 Status code (501) indicating the HTTP server does not support the functionality needed to fulfill the request.
SC_NOT_MODIFIED 304 Status code (304) indicating that a conditional GET operation found that the resource was available and not modified.
SC_OK 200 Status code (200) indicating the request succeeded normally.
SC_PARTIAL_CONTENT 206 Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
SC_PAYMENT_REQUIRED 402 Status code (402) reserved for future use.
SC_PRECONDITION_FAILED 412 Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.
SC_PROXY_AUTHENTICATION_REQUIRED 407 Status code (407) indicating that the clientMUSTfirst authenticate itself with the proxy.
SC_REQUEST_ENTITY_TOO_LARGE 413 Status code (413) indicating that the server is refusing to process the request because the request entity is larger than the server is willing or able to process.
SC_REQUEST_TIMEOUT 408 Status code (408) indicating that the client did not produce a request within the time that the server was prepared to wait.
SC_REQUEST_URI_TOO_LONG 414 Status code (414) indicating that the server is refusing to service the request because theRequest-URIis longer than the server is willing to interpret.
SC_REQUESTED_RANGE_NOT_SATISFIABLE 416 Status code (416) indicating that the server cannot serve the requested byte range.
SC_RESET_CONTENT 205 Status code (205) indicating that the agentSHOULDreset the document view which caused the request to be sent.
SC_SEE_OTHER 303 Status code (303) indicating that the response to the request can be found under a different URI.
SC_SERVICE_UNAVAILABLE 503 Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request.
SC_SWITCHING_PROTOCOLS 101 Status code (101) indicating the server is switching protocols according to Upgrade header.
SC_TEMPORARY_REDIRECT 307 Status code (307) indicating that the requested resource resides temporarily under a different URI.
SC_UNAUTHORIZED 401 Status code (401) indicating that the request requires HTTP authentication.
SC_UNSUPPORTED_MEDIA_TYPE 415 Status code (415) indicating that the server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.
SC_USE_PROXY 305 Status code (305) indicating that the requested resource MUST be accessed through the proxy given by theLocationfield.

Remarks

This method is inherited from the Java HttpServletResponse object.

Example

REM /**
REM  * Enter the values for your username, password, and the filepath to this file
REM  */
username$ = "admin"
password$ = "admin123"
pathToThisFile$ = "/path/to/BBxServletResponseDemo.bbj"

context! = BBjAPI().getAdmin(username$, password$).getJettyServerConfig().getCustomContext("root")
context!.addBBxServlet("/BBxServletResponseDemo", pathToThisFile$, "BBxServletResponseDemo", "bbxServletResponseDemo", 1) 
BBjAPI().getAdmin(username$, password$).getJettyServer().getContext("root").restart()

CLASS PUBLIC BBxServletResponseDemo

    REM Demonstrates the various capabilities of the BBxServletResponse object
    METHOD PUBLIC VOID bbxServletResponseDemo(BBxServletContext context!)
        REM  Get the response object from the BBxServletContext
        response! = context!.getResponse()
        
        REM Get ServletOutputStream from BBxServletResponse
        out! = response!.getOutputStream()
        
        out!.write("<h2>BBxServletResponse</h2>")
        out!.write("<p>This is the response object that is used to send information back to the client when the ")
        out!.write("servlet is called. The primary method through which information is passed around is the ")
        out!.write("ServletOutputStream returned through BBxServletResponse.getOutputStream.</p>")
        
        #addCookieDemo(context!)
        out!.write("<p>See <code>addCookieDemo</code> in source code for method usage examples</p>")
        
        #statusCodesDemo(context!)
        out!.write("<p>See <code>statusCodeDemo</code> in source code for method usage examples</p>")
        
        #sendRedirectDemo(context!)
        out!.write("<p>See <code>sendRedirectDemo</code> in source code for method usage examples</p>")
        
        #responseInfoMethodsDemo(context!)
        out!.write("<p>See <code>responseInfoMethodsDemo</code> in source code for method usage examples</p>")
        
    METHODEND
    
    REM Demonstrates how to create a cookie as well as how to add it to the BBxServletResponse
    METHOD PUBLIC VOID addCookieDemo(BBxServletContext context!)
        REM  Get the request and response object from the BBxServletContext
        request! = context!.getRequest()
        response! = context!.getResponse()
        
        REM Get ServletOutputStream from BBxServletResponse
        out! = response!.getOutputStream()
        
        REM Check parameters for addCookie query
        cookies! = new BBjVector()
        cookiesToAdd! = request!.getParameterValues("addCookieName")
        cookieVals! = request!.getParameterValues("cookieVal")
        IF cookiesToAdd!.size()>0 THEN
            FOR N=0 TO cookiesToAdd!.size()-1
                name$ = cookiesToAdd!.getItem(N)
                value$ = cookieVals!.getItem(N)
            
                REM create cookie
                cookie! = response!.createCookie(name$)
                cookie!.setValue(value$)
                
                REM add cookie to response
                response!.addCookie(cookie!)
                
                cookies!.addItem(cookie!)
            NEXT N
        FI
        
        out!.write("<h3>Adding BBjCookies</h3>")
        out!.write("<p>BBjCookies can be added to a response which will set them in the client browser. This can be")
        out!.write(" done by creating a cookie with <code>response!.createCookie(name$)</code> and then adding the ")
        out!.write("cookie to the response with <code>response!.addCookie(cookie!)</code>.<p>")
        
        REM loop over cookie BBjVector to print out the cookies that will be added
        IF cookies!.size() > 0
            out!.write("<p>The following cookies will be added to this response:</p><ul>")
            FOR N=0 TO cookies!.size()-1
                cookie! = cookies!.getItem(N)
                out!.write("<li> Cookie "+String.valueOf(N)+":")
                out!.write("<ul><li>name = "+cookie!.getName()+"</li><li>value = "+cookie!.getValue()+"</li></ul>")
            NEXT N
            out!.write("</ul>")
            out!.write("To see these cookies in the request, <b>refresh the page</b>.")
        FI
        
        out!.write("<p>Try adding a cookie below!</p>")
        
        REM An HTML form to add cookies to the request
        out!.write("Enter the name and value of a cookie to add:")
        out!.write("<form method='GET' enctype='text/html' action='"+request!.getServletPath()+"'>")
        out!.write("Name: <input type='text' name='addCookieName'> Value: <input type='text' name='cookieVal'> ")
        out!.write("<input type='submit' value='Press'> to <b>add</b> a cookie to the next response!")
        out!.write("</form>")
        
    METHODEND
    REM Demonstrates the getStatus() and sendError(in code) methods in BBxServletResponse
    METHOD PUBLIC VOID statusCodesDemo(BBxServletContext context!)
        REM  Get the request and response object from the BBxServletContext
        request! = context!.getRequest()
        response! = context!.getResponse()
        
        REM Get ServletOutputStream from BBxServletResponse
        out! = response!.getOutputStream()
        
        REM Check parameters for sendError query
        errorCode! = request!.getParameter("sendError")
        errorMsg! = request!.getParameter("errorMsg")
        IF errorCode!.length() > 0 THEN
            
            REM Send the error code and message
            response!.sendError(Integer.parseInt(errorCode!), errorMsg!)
        
        FI
        
        REM Get the value of getStatus()
        status! = response!.getStatus()
        
        out!.write("<h3>Status Codes</h3>")
        out!.write("<p>Through BBxServletResponse, you have the capability to check status codes as well as send error ")
        out!.write("codes along with a message.  Below is the current return value for <code>getStatus()</code></p>")
        out!.write("<code><ul><li>getStatus() = "+String.valueOf(status!)+"</li></ul></code>")
        
        REM Form for submitting an error code
        out!.write("Try submitting an error code and message for yourself!")
        out!.write("<form method='GET' enctype='text/html' action='"+request!.getServletPath()+"'>")
        out!.write("Error Code: <input type='text' name='sendError'> Message: <input type='text' name='errorMsg'> ")
        out!.write("<input type='submit' value='Press'> to send an error.")
        out!.write("</form>")
        
    METHODEND
    
    REM Demonstration of the sendRedirect(url$) method
    METHOD PUBLIC VOID sendRedirectDemo(BBxServletContext context!)
        REM  Get the request and response objects from the BBxServletContext
        request! = context!.getRequest()
        response! = context!.getResponse()
        
        REM Get ServletOutputStream from BBxServletResponse
        out! = response!.getOutputStream()
        
        REM check parameters for sendRedirect parameter
        sendRedirect! = request!.getParameter("sendRedirect")
        
        REM Send the redirect on the response
        IF sendRedirect!.length() > 0 THEN
            response!.sendRedirect(sendRedirect!)
        FI
        
        out!.write("<h3>Send Redirect</h3>")
        out!.write("<p>With <code>sendRedirect</code>, you can redirect a page to any URL you would like.</p>")
        out!.write("<p>Enter a URL below to redirect the servlet to that page</p>")
        
        REM An HTML form to add sendRedirect parameter to URL
        out!.write("<form method='GET' enctype='text/html' action='"+request!.getServletPath()+"'>")
        out!.write("Redirect URL: <input type='text' name='sendRedirect'> ")
        out!.write("<input type='submit' value='Press'> to redirect page")
        out!.write("</form>")
        
    METHODEND    
        
    REM Demonstrates methods for getting and setting various information in the BBxServletResponse
    METHOD PUBLIC VOID responseInfoMethodsDemo(BBxServletContext context!)
        REM  Get the request and response objects from the BBxServletContext
        request! = context!.getRequest()
        response! = context!.getResponse()
        
        REM Get ServletOutputStream from BBxServletResponse
        out! = response!.getOutputStream()
        
        REM Check parameters for setCharacterEncoding and set it to the specified value
        setCharacterEncoding! = request!.getParameter("setCharacterEncoding")        
        IF setCharacterEncoding!.length() > 0 THEN
            response!.setCharacterEncoding(setCharacterEncoding!)
        FI
        
        REM Check parameters for setContentType and set it to the specified value
        setContentType! = request!.getParameter("setContentType")
        IF setContentType!.length() > 0 THEN
            response!.setContentType(setContentType!)
        FI
        
        REM Check parameters for setDateHeader values and set the date header
        setDateHeaderName! = request!.getParameter("setDateHeaderName")
        setDateHeaderValue! = request!.getParameter("setDateHeaderValue")
        IF setDateHeaderName!.length() > 0 THEN
            response!.setDateHeader(setDateHeaderName!, Long.parseLong(setDateHeaderValue!))
        FI
        
        REM Check parameters for setHeader values and set them in the response
        setHeaderName! = request!.getParameter("setHeaderName")
        setHeaderValue! = request!.getParameter("setHeaderValue")
        IF setHeaderName!.length() > 0 THEN
            response!.setHeader(setHeaderName!, setHeaderValue!)
        FI
        
        REM Check parameters for setLocale and set the locale to that value
        setLocale! = request!.getParameter("setLocale")
        IF setLocale!.length() > 0 THEN
            response!.setLocale(new java.util.Locale(setLocale!))
        FI
        
        
        REM Get BBxServletResponse info
        isCommitted! = response!.isCommitted()
        characterEncoding! = response!.getCharacterEncoding()
        contentType! = response!.getContentType()
        headerNames! = response!.getHeaderNames()
        
        getHeadersString$ = ""
        getHeaderString$ = ""
        IF headerNames!.size() > 0 THEN
            getHeadersString$ = getHeadersString$ + "<ul>"
            getHeaderString$ = getHeaderString$ + "<ul>"
            
            FOR N=0 TO headerNames!.size()-1
                name$ = headerNames!.get(N)
                
                headers! = response!.getHeaders(name$)
                getHeadersString$ = getHeadersString$ + "<li>getHeaders(<em>"+name$+"</em>) = "+String.valueOf(headers!)+"</li>"
                
                header! = response!.getHeader(name$)
                getHeaderString$ = getHeaderString$ + "<li>getHeaders(<em>"+name$+"</em>) = "+String.valueOf(header!)+"</li>"
                
            NEXT N
            
            getHeadersString$ = getHeadersString$ + "</ul>"
            getHeaderString$ = getHeaderString$ + "</ul>"
        FI
        
        locale! = response!.getLocale()
        
        out!.write("<h3>BBxServletResponse Header Info</h3>")
        out!.write("<p>BBxServletResponse has a number of methods that allow you to get as well as set values in the ")
        out!.write("response header. Below are the methods and return values along with fields that will allow you to")
        out!.write(" change their values.</p>")
        
        out!.write("<code><ul>")
        out!.write("<li>boolean isCommitted() = "+Boolean.toString(isCommitted!)+"</li>")
        out!.write("<li>String getCharacterEncoding() = "+String.valueOf(CAST(Object, characterEncoding!))+"</li>")
        out!.write("<li>String getContentType() = "+String.valueOf(CAST(Object, contentType!))+"</li>")
        out!.write("<li>Locale getLocale() = "+String.valueOf(CAST(Object, locale!))+"</li>")
        out!.write("<li>BBjVector getHeaderNames() = "+String.valueOf(headerNames!)+"</li>")
        out!.write("<li>String getHeader(String name) : "+getHeaderString$+"</li>")
        out!.write("<li>String getHeaders(String name) : "+getHeadersString$+"</li>")
        out!.write("</code></ul>")
        
        out!.write("<p>Try changing these values below.</p>")
        
        REM An HTML form to add setCharacterEncoding parameter to URL
        out!.write("<form method='GET' enctype='text/html' action='"+request!.getServletPath()+"'>")
        out!.write("Character Encoding: <input type='text' name='setCharacterEncoding'> ")
        out!.write("<input type='submit' value='Press'> to set character encoding")
        out!.write("</form>")
        
        REM An HTML form to add setContentType parameter to URL
        out!.write("<form method='GET' enctype='text/html' action='"+request!.getServletPath()+"'>")
        out!.write("Content Type: <input type='text' name='setContentType'> ")
        out!.write("<input type='submit' value='Press'> to set content type")
        out!.write("</form>")
        
        REM An HTML form to add setLocale parameter to URL
        out!.write("<form method='GET' enctype='text/html' action='"+request!.getServletPath()+"'>")
        out!.write("Locale: <input type='text' name='setLocale'> ")
        out!.write("<input type='submit' value='Press'> to set locale")
        out!.write("</form>")
        
        REM An HTML form to add setHeader parameters to URL
        out!.write("<form method='GET' enctype='text/html' action='"+request!.getServletPath()+"'>")
        out!.write("Header Name: <input type='text' name='setHeaderName'> Header Value: <input type='text' name='setHeaderValue'> ")
        out!.write("<input type='submit' value='Press'> to set header")
        out!.write("</form>")
        
    METHODEND
CLASSEND

ClosedVersion History

  • BBj 21.00: BBxServlet introduced.

See Also

BBjAPI

BBxServlet

BBxServlet Tutorial

BBxServletResponse

BBxServletRequest

See the BBj Object Diagram for an illustration of the relationship between BBj Objects.