Table of contents
1.
Introduction
2.
JSP Server Response
2.1.
Response Headers in JSP
3.
JSP Response Implicit Object
3.1.
JSP Response Implicit Object Example
3.2.
Methods of Response Implicit Object
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

JSP Server Response

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java Server Pages is a scripting-side language that combines several technologies into one powerful, highly scalable technology and helps develop reliable, platform-independent dynamic web applications.

When a browser requests a web page, it sends a lot of information to the webserver. This information can’t be accessed directly as it travels as a part of the header of the HTTP request. . When a web page is requested, it sends information to the server within the HTTP header. This information sent by the browser is stored in the HTTP request header and can be utilized using the HTTPServletRequest. 

This article will focus mainly on JSP Server Response and its role in developing a reliable, scalable, and cost-effective web page. Before jumping to the concept of Server Response, you should first know about JSP Client Requests.

JSP Server Response

 

 

JSP response is created by the server whenever a client makes a request. When this request is processed, the web server generates a response that typically consists of response headers, a status line (a version of HTML), a blank line, and a document. The web server HTTP response to the web browser can be accessed using JSP.

The JSP Server Response is a response object of HTTPServletResponse class which is an instance of javax.servlet.http.HttpServletResponse object.

Response Headers in JSP

Response Headers in JSP are as follows:

  1. Allow: It specifies the request methods that the server supports. It includes methods such as GET, PUT, POST.
     
  2. Cache-Control: It is used to specify the circumstances in which the response document can be cached safely. It can have public, private, or no-cache values. 

    Public: Document is cacheable.
    Private: Document can be used by a single user and can only be stored in private caches.
    No-cache: Document should never be cached.
     
  3. Connection: It instructs the web browser to use persistent HTTP connections or not. 

    Close: It instructs the browser not to use persistent HTTP connections.
    Keep-alive: It instructs the browser to use persistent connections.
     
  4. Content-Disposition: It lets the browser ask the user to save the response to the disk in a file of the given name.
     
  5. Content-Encoding: It specifies how the page is encoded during transmission.
     
  6. Content-Language: It signifies the language in which the document is written. E.g., en, ru, en-us, etc.

     
  7. Content-Length: This header tells about the length of the response and also indicates the number of bytes in the response.
     
  8. Content-Type: It gives the Multipurpose Internet Mail Extension (MIME) type in the received response document.
     
  9. Expires: It specifies when the content should be considered out of date. This data should not be cached.
     
  10. Last-Modified: It indicates when the document was last changed.
     
  11. Location: This header gets the document’s location and notifies the web browser. It should be included with all the responses with a status code in the 300s. 
     
  12. Refresh: It specifies how soon the browser should ask for an updated page. The page will refresh, and the auto-loads the user has specified a time limit.
     
  13. Retry-After: It tells the client how soon they can repeat their request. It can also be used with a 503 (Service Unavailable) response.
     
  14. Set-Cookie: It specifies a cookie associated with the page.

JSP Response Implicit Object

The response can also be defined as an implicit object, an instance of a javax.servlet.http.HttpServletResponse is formed for each JSP request created by the JSP container. As the server creates the request object, it also creates an object that represents the response to the client. The response object defines the interfaces that deal with creating new HTTP headers. A response object is implemented to modify or deal with the reply sent to the client after processing the request, such as redirecting to another resource, sending an error to a client, adding new cookies, HTTP status codes, date stamps, etc.

JSP Response Implicit Object Example

Given an example for JSP Response implicit object where a user submits their login information that is further received by another page for processing:

Example 1: 

HTML File

<!DOCTYPE html>
<html>
    <head>
        <title>Login Form</title>
    </head>
    <body>
        <form action="login.jsp">
            Please enter Username: <input type="text" name="u_name" /> <br />
            <input type="submit" value="Submit Details" />
        </form>
    </body>
</html>

 

JSP File: (login.jsp)

<%@ page import = " java.util.* " %>
<% 
String username = request.getParameter("u_name"); 
if(username.equals("admin")){
    response.sendRedirect("home.jsp");  
}else{
    out.print("Invalid Username");  
}
%>

 

Home.jsp

<%
String session_u_name = (String)session.getAttribute("u_name");
out.print("Hi "+ session_u_name);
%>

 

In the above example, the user submits login information (HTML page) that is processed by a JSP page(login.jsp). We are using the sendRedirect() response method to manipulate the output.

 

Example 2: 

HTML File:

<form action="welcome.jsp">  
<input type="text" name="uname">  
<input type="submit" value="go"><br/>  
</form>  


JSP File:

<%   
response.sendRedirect("http://www.google.com");  
%>  

 

Output:

 

In the given example, we are redirecting the response to google.

Methods of Response Implicit Object

  1. string encodeRedirectURL(string URL): This method encodes the specified URL used in the sendRedirect method. It returns the unchanged URL only if the encoding is not required.
     
  2. string encodeURL(String URL): This method can encode the mentioned URL to include the session ID. It will return the unchanged URL only if the encoding is not required.
     
  3. boolean containsHeader(string name): It returns a boolean value (True or False) indicating whether the named response header is set or not.
     
  4. boolean isCommitted(): It returns a boolean value (True or False) indicating if the response has been committed or not.
     
  5. void addCookie(): It adds a specified cookie to the response.
     
  6. void addDateHeader(string name, long date): Add a response header with the given name and date value.
     
  7. void addHeader(string name, string value): Add a response header with the specified string name and value.
     
  8. void addIntHeader(string name, int value): Add a response header with the given name and integer value.
     
  9. void flushBuffer(): It flushes the buffer, but the buffer’s content is written to the client before flushing.
     
  10. void reset(): It is used to clear the data that exists in the buffer along with the status code and headers.
     
  11. void resetBuffer(): It is used to clear the underlying buffer’s content in the response without clearing headers or status codes.
     
  12. void sendError(int sc): It sends an error response to the client using a specified status code to flush the buffer.
     
  13. void sendError(int sc, String msg): It sends an error response to the client using the specified status.
     
  14. void sendRedirect(string location): It sends a temporary redirect response to the client using the specified redirect location URL.
     
  15. void setBufferSize(int size): Set the buffer size as the preferred one for the response’s body.
     
  16. void setCharacterEncoding(String charset): This method is used to set the response’s character.E.g., UTF-8, etc.
     
  17.  void setContentType(int len): This method is used to set the content body length on the response.
     
  18. void setContentType(String type): It is used to set only the response’s content type if it is not committed.
     
  19. void setDateHeader(string name, long date): Set a response header with the given name and date value.
     
  20. void setHeader(string name, string value): Set the browser manipulates these responses, a response header with the given name and value.
     
  21. void setIntHeader(string name, int value): It is used to set the specified name and integer value as the name and value of the response header.
     
  22. void setLocale(Locale loc): It is used to set the locale of the response if the response is not committed.
     
  23. void setStatus(int sc): It is used to set the status code for the response.
     

You can also read about the JSP Architecture and Lifecycle.

FAQs

  1. What is Expression Language in JSP?
    The Expression Language in JSP  is used to simplify the accessibility of objects. It provides various objects that can be used directly like sessionScope, application scope, request, param, requestScope, session, etc. 
     
  2. What is J2EE?
    J2EE is a compilation of different Java APIs offered as separate packages. J2EE blueprints describe how they can all be combined. J2EE vendors can use a test suite to test their products for compatibility. J2EE comprises the following APIs:
    - Java Server Pages ( JSP)
    - Java Servlets
    - Enterprise JavaBeans (EJB)
    - Java Database Connection ( JDBC)
    - Java Transaction API ( JTA) 
    - Java Transaction Service ( JTS)
    - Java Naming and Directory Interface ( JNDI)
    - Java Message Service ( JMS)
    - Remote Method Invocation (RMI) and Java IDL
    - Java XML
     
  3. What is JSTL?
    JSTL stands for Java Server Pages Standard Tag Library. It is a collection of JSP tag libraries that provide common web development functionality.
    Some of the properties of JSTL are given below:
    - The code is easy to debug.
    - It provides a rich layer of portable functionality for JSP pages.
    - It has Automatic Javabeans Introspection Support. The Expression language of JSTL  can handle JavaBean code very easily. 
    - It provides easy readability.

Key Takeaways

This blog taught us about Server Response and how the browser manipulates these responses. When a web page is requested, it sends information to the server in the HTTP header. When a request is processed, the response is generated from the webserver. This response consists of a status line, a blank line, response headers, and a document. The response status line consists of an HTTP version, a status code, and an associated message.

If you are a beginner and interested in learning other fields related to computer subjects, web development, or competitive programming, you can follow our guided path to get a good grip on such concepts. 

Live masterclass