jump to navigation

The Response Object August 23, 2005

Posted by Coolguy in Servlets/Jsp.
Tags:
add a comment
  • The response object encapsulates all information to be returned from the server to the client. In the HTTP protocol, this information is transmitted from the server to the client either by HTTP headers or the message body of the request.
  • A servlet container is allowed, but not required, to buffer output going to the client for efficiency purposes.
  • The following methods in the ServletResponse interface allow a servlet to access and set buffering information:
    • getBufferSize
    • setBufferSize
    • isCommitted
    • reset
    • resetBuffer
    • flushBuffer
  • These methods are provided on the ServletResponse interface to allow buffering operations to be performed whether the servlet is using a ServletOutputStream or a Writer.
  • The getBufferSize method returns the size of the underlying buffer being used. If no buffering is being used, this method must return the int value of 0 (zero).
  • The servlet can request a preferred buffer size by using the setBufferSize method. The buffer assigned is not required to be the size requested by the servlet, but must be at least as large as the size requested.
  • The method must be called before any content is written using a ServletOutputStream or Writer. If any content has been written or the response object has been committed, this method must throw an IllegalStateException.
  • The isCommitted method returns a boolean value indicating whether any response bytes have been returned to the client.
  • The flushBuffer method forces content in the buffer to be written to the client.
  • The reset method clears data in the buffer when the response is not committed. Headers and status codes set by the servlet prior to the reset call must be cleared as well.
  • The resetBuffer method clears content in the buffer if the response is not committed without clearing the headers and status code.
  • If the response is committed and the reset or resetBuffer method is called, an IllegalStateException must be thrown. The response and its associated buffer will be unchanged.
  • A servlet can set headers of an HTTP response via the following methods of the HttpServletResponse interface:
    setHeader
    addHeader
  • The setHeader method sets a header with a given name and value. A previous header is replaced by the new header. Where a set of header values exist for the name, the values are cleared and replaced with the new value.It overwrites a exisiting value if the header is present.
  • The addHeader method adds a header value to the set with a given name. If there are no headers already associated with the name, a new set is created.It adds a additional value to the header if its already present.
  • Headers may contain data that represents an int or a Date object. The following convenience methods of the HttpServletResponse interface allow a servlet to set a header using the correct formatting for the appropriate data type:
    setIntHeader
    setDateHeader
    addIntHeader
    addDateHeader
  • To be successfully transmitted back to the client, headers must be set before the response is committed. Headers set after the response is committed will be ignored by the servlet container.
  • Servlet programmers are responsible for ensuring that the Content-Type header is appropriately set in the response object for the content the servlet is generating.
  • Servlet containers must not set a default content type when the servlet programmer does not set the type.
  • Containers use the X-Powered-By HTTP header to publish its implementation information. Eg: X-Powered-By: Servlet/2.4 JSP/2.0 (Tomcat/5.0 JRE/1.4.1)
  • The following convenience methods exist in the HttpServletResponse interface:
    sendRedirect
    • sendError
  • The sendRedirect method will set the appropriate headers and content body to redirect the client to a different URL.
  • It is legal to call this method with a relative URL path, however the underlying container must translate the relative path to a fully qualified URL for transmission back to the client. If a partial URL is given and, for whatever reason, cannot be converted into a valid URL, then this method must throw an IllegalArgumentException.
  • The sendError method will set the appropriate headers and content body for an error message to return to the client. An optional String argument can be provided to the sendError method which can be used in the content body of the error.
  • These methods will have the side effect of committing the response, if it has not already been committed, and terminating it. No further output to the client should be made by the servlet after these methods are called. If data is written to the response after these methods are called, the data is ignored.
  • Servlets should set the locale and the character encoding of a response.
  • The locale is set using the ServletResponse.setLocale method. The method can be called repeatedly; but calls made after the response is committed have no effect.
  • If the servlet does not set the locale before the page is committed, the container’s default locale is used to determine the response’s locale
  • If the servlet does not specify a character encoding before the getWriter method of the ServletResponse interface is called or the response is committed, the default ISO-8859-1 is used.
  • Containers must communicate the locale and the character encoding used for the servlet response’s writer to the client if the protocol in use provides a way for doing so. In the case of HTTP, the locale is communicated via the Content-Language header, the character encoding as part of the Content-Type header for text media types.
  • When a response is closed, the container must immediately flush all remaining content in the response buffer to the client.
  • The following events indicate that the servlet has satisfied the request and that the response object is to be closed:
    • The termination of the service method of the servlet.
    • The amount of content specified in the setContentLength method of the response has been written to the response.
    • The sendError method is called.
    • The sendRedirect method is called.
  • Each response object is valid only within the scope of a servlet’s service method, or within the scope of a filter’s doFilter method. Containers commonly recycle response objects in order to avoid the performance overhead of response object creation.

Gotchas

  • println() to a PrintWriter
  • PrintWriter writer = response.getWriter();
    writer.println(“text”);
  • write() to a ServletOutputStream
  • ServletOutputStream out=response.getOutputStream();
    out.write(bytearray);
  • setHeader() takes two string parameters

The Request Object August 23, 2005

Posted by Coolguy in Servlets/Jsp.
Tags:
add a comment
  • The request object encapsulates all information from the client request. In the HTTP protocol, this information is transmitted from the client to the server in the HTTP headers and the message body of the request.
  • Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request.
  • When the request is an HttpServletRequest object,the container populates the parameters from the URI query string and POST-ed data.
  • The parameters are stored as a set of name-value pairs. Multiple parameter values can exist for any given parameter name.
  • The following methods of the ServletRequest interface are available to access parameters:
    • getParameter
    • getParameterNames
    • getParameterValues
    • getParameterMap
  • The getParameterValues method returns an array of String objects containing all the parameter values associated with a parameter name.
  • The value returned from the getParameter method must be the first value in the array ofS tring objects returned by getParameterValues.
  • The getParameterMap method returns a java.util.Map of the parameter of the request, which contains names as keys and parameter values as map values.
  • Query string data is presented before post body data.
  • For example, if a request is made with a query string of a=hello and a post body of a=goodbye&a=world, the resulting parameter set would be ordered a=(hello,goodbye, world).
  • The following are the conditions that must be met before post form data will be populated to the parameter set:
    1. The request is an HTTP or HTTPS request.
    2. The HTTP method is POST.
    3. The content type is application/x-www-form-urlencoded.
    4. The servlet has made an initial call of any of the getParameter family of methods on the request object.
  • Attributes are objects associated with a request.
  • Attributes may be set by the container to express information that otherwise could not be expressed via the API, or may be set by a servlet to communicate information to another servlet (via theRequestDispatcher).
  • Attributes are accessed with the following methods of the ServletRequest interface:
    • getAttribute
    • getAttributeNames
    • setAttribute
  • Only one attribute value may be associated with an attribute name.
  • Attribute names beginning with the prefixes of “java.” and “javax.” are reserved.Similarly, attribute names beginning with the prefixes of “sun.”, and “com.sun.” are reserved for definition by Sun Microsystems.
  • A servlet can access the headers of an HTTP request through the following methodsof the HttpServletRequest interface:
    • getHeader
    • getHeaders
    • getHeaderNames
  • The getHeader method returns a header given the name of the header. There can be multiple headers with the same name, e.g. Cache-Control headers, in an HTTP request. If there are multiple headers with the same name, the getHeader method returns the first header in the request.
  • The getHeaders method allows access to all the header values associated with a particular header name, returning an Enumeration of String objects.
  • Headers may contain String representations of int or Date data. The following convenience methods of the HttpServletRequest interface provide access to header data in a one of these formats:
    • getIntHeader
    • getDateHeader
  • If the getIntHeader method cannot translate the header value to an int, a NumberFormatException is thrown.
  • If the getDateHeader method cannot translate the header to a Date object, an IllegalArgumentException is thrown.
  • The request path that leads to a servlet servicing a request is composed of manyimportant sections.
  • Context Path: The path prefix associated with the ServletContext that this servlet is a part of.
  • Servlet Path: The path section that directly corresponds to the mapping which activated this request.
  • PathInfo: The part of the request path that is not part of the Context Path or the Servlet Path.
  • If the context is not rooted at the root of the server’s name space, the context path starts with a’/’ character but does not end with a’/’ character.
  • Servlet Path starts with a’/’ character except in the case where the request is matched with the ‘/*’ pattern, in which case it is an empty string.
  • PathInfo is either null if there is no extra path, or is a string with a leading ‘/’.
  • The following methods exist in the HttpServletRequest interface to access this information:
    • getContextPath
    • getServletPath
    • getPathInfo
  • requestURI = contextPath + servletPath + pathInfo
  • E.g: SetupContext Path /catalogServlet Mapping Pattern: /lawn/*Servlet: LawnServletServlet Mapping Pattern: /garden/*Servlet: GardenServletServlet Mapping Pattern: *.jspServlet: JSPServletRequest Path : /catalog/lawn/index.html ContextPath: /catalogServletPath: /lawnPathInfo: /index.htmlRequest Path :/catalog/garden/implements/ ContextPath: /catalogServletPath: /gardenPathInfo: /implements/Request Path /catalog/help/feedback.jsp ContextPath: /catalogServletPath: /help/feedback.jspPathInfo: null
  • There are two convenience methods in the API which allow the Developer to obtain the file system path equivalent to a particular path. These methods are:
    • ServletContext.getRealPath
    • HttpServletRequest.getPathTranslated
  • The getRealPath method takes a String argument and returns a String representation of a file on the local file system to which a path corresponds.
  • The getPathTranslated method computes the real path of the pathInfo of the request.
  • The HttpServletRequest interface provides the getCookies method to obtain an array of cookies that are present in the request.
  • Typically, the only information that the client sends back as part of a cookie is the cookie name and thecookie value. Other cookie attributes that can be set when the cookie is sent to the browser, such as comments, are not typically returned.
  • If a request has been transmitted over a secure protocol, such as HTTPS, this information must be exposed via the isSecure method of the ServletRequest interface.
  • If there is an SSL certificate associated with the request, it must be exposed by the servlet container to the servlet programmer as an array of objects of type java.security.cert.X509Certificate and accessible via a ServletRequest attribute of javax.servlet.request.X509Certificate.
  • Clients may optionally indicate to aWeb server what language they would prefer the response be given in. This information can be communicated from the client using the Accept-Language header along with other mechanisms described in the HTTP/1.1 specification.
  • The following methods are provided in the ServletRequest interface to determine the preferred locale of the sender:
    • getLocale
    • getLocales
  • The getLocale method will return the preferred locale for which the client wants to accept content.
  • The getLocales method will return an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client.
  • If no preferred locale is specified by the client, the locale returned by the getLocale method must be the default locale for the servlet container
  • The default encoding of a request the container uses to create the request reader and parse POST data must be “ISO-8859-1” if none has been specified by the client request.
  • If the client hasn’t set character encoding and the request data is encoded with a different encoding than the default as described above, breakage can occur. To remedy this situation, a new method setCharacterEncoding(String enc) has been added to the ServletRequest interface.
  • Developers can override the character encoding supplied by the container by calling this method. It must be called prior to parsing any post data or reading any input from the request. Calling this method once data has been read will not affect the encoding.
  • Each request object is valid only within the scope of a servlet’s service method, or within the scope of a filter’s doFilter method.
  • Containers commonly recycle request objects in order to avoid the performance overhead of request object creation.
  • getInputStream() could be used to get the raw bytes of everything that comes with a request
  • getRemotePort() gets the clients port
  • getServerPort() tells the port to which the request was originally sent
  • getLocalPort() tells on which port the request finally ended up.
  • Although all the requests are sent to a single port where the server is listening, server turns around and finds a different local port for each thread so that the app can handle multiple clients at the same time.