Response Implicit Object in JSP with examples

In this post we are going to discuss about response implicit object in JSP. It is an instance of javax.servlet.http.HttpServletRequest and mainly used for modifying the response which is being sent to the browser after processing the client’s request.

void setContentType(String type) – This method tells browser, the type of response data by setting up the MIME type and character encoding. The information sets by this method helps browser to interpret the response. Example –

void sendRedirect(String address) – It redirects the control to a new JSP page. For e.g. When the browser would detect the below statement, it would be redirected to the beginnersbook.com from the current JSP page.

response.sendRedirect("http://beginnersbook.com");

void addHeader(String name, String value) – addHeader method adds a header to the response, basically it includes a header name and it’s value. For example – The below statement will include a header “Site” in the response with value “BeginnersBook.com”.

response.addHeader("Site", "BeginnersBook.com");

void setHeader(String name, String value) – It sets the header value. This method overrides the current value of header with the new value. Let’s say I’m modifying the value of Header “Site“. The below statement would modify the current value BeginnersBook.com to a new value BB.com

response.setHeader("Site", "BB.com");

boolean containsHeader(String name) – It returns a Boolean value true/false. It basically checks the whether the header is present in the response or not. For example – Above, in the addHeader method example we have added a Site Header in response so the below statement would return true.

response.containsHeader("Site");

void addCookie(Cookie cookie) – This method adds a cookie to the response. The below statements would add 2 Cookies Author and Siteinfo to the response.

void setStatus(int statuscode) – This method is used to set the HTTP status to a given value. For e.g. the below statement would set HTTP response code to 404 (Page not found).

response.setStatus(404);

Response Implicit Object Example

In the below example we are receiving id and password from login page and then we are matching them with hardcoded correct id/pass. If the credentials are correct the sign-in page redirects to success page else it redirects to sign-in fail JSP page.