Monday, 27 June 2016

How to acquire a binary stream for the response ?


Method of ServletResponse interface
  • ServletOutputStream getOutputStream()
    Returns ServletOutputStream for writing binary data in the response.


    Calling flush() on the ServletOutputStream commits the response.

How to acquire a text stream for the response ?


Method of ServletResponse interface
  • PrintWriter getWriter()
    Returns a PrintWriter object that can send character text to the client


    Calling flush() on the PrintWriter commits the response.

How to set the content type of the response ?


Method of ServletResponse interface
  • setContentType(String) 
    • Sets the content type of the response being sent to the client 
    • It may include character encoding as well. 
    • Example : text/html; charset=ISO-8859-4

What will happen if headers are set after the response is committed ?


Headers must be set before the response is committed.

If headers are set after the response is committed, that will be ignored by the servlet container

How to set a HTTP response header ?


Methods of the HttpServletResponse interface
  • setHeader : sets a header with a given name and value
    If header name already exists, it will replace all the n existing values with 1 new value
  • addHeader : adds a header value to a given name
  • setIntHeader : sets a int type header
  • setDateHeader : sets a Date type header
  • addIntHeader : adds a int type header
  • addDateHeader : adds a Date type header

* Headers must be set before the response is committed.

How to retrieve HTTP request header information ?


Methods of HttpServletRequest interface
  • getHeader : returns a header value by given header name
    If there are multiple headers with the same name, it returns the first head in the request.
  • getHeaders : returns all the header values associated with the given header name (Enumeration of Strings)
  • getHeaderNames : returns names of all the headers
  • getIntHeader : returns header value (String) into int format
    If it cannot translate the header value to an int, a NumberFormatException is thrown.
  • getDateHeader : returns header value (String) into Date format
    If it cannot translate the header to a Date object, an IllegalArgumentException is thrown.

Sunday, 26 June 2016

How to retrieve a servlet initialization parameter ?


Methods of ServletConfig interface
  • public String getInitParameter(String)returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.
     
  • public Enumeration getInitParameterNames()returns the names of the servlet’s initialization parameters as an Enumeration of String objects.