JSP Client Request and Server Response

Placement-ready Online Courses: Your Passport to Excellence - Start Now

Welcome to DataFlair JSP Client Request and Server Response Tutorial. This article is the detailed study of Client Request and Server Response in JSP along with their headers. It also discusses the methods available to use these headers to retrieve the required information. So without wasting time, let’s proceed.

JSP Client Request and se

JSP Client Request and Server Response

When a browser requests for a web page, it sends a lot of information to the webserver. This information sent by the browser gets stored in the header of this HTTP request. This information can be used using HttpServletRequest implementation. We can use different headers that store the information in the request object. Various methods can retrieve information about these Http Headers.

Different headers are:

S.No.HeaderInformation
1.AcceptThis header gives the information about MIME types a browser can handle. The most common example can be Image/png or Image/jpeg, depending on what the browser supports. 
2.Accept-charsetThis header gives the information regarding the character sets the browser can use while displaying the information. For example, the browser can use ISO-8599-1 and give this information as a header.
3.Accept-EncodingThis header will give the information about the encoding used by the browser. For example, the header can show gzip or compress as the encoding that the browser uses. 
4.Accept-languageIf the servlet is capable of producing output in more than one language, then this header will show the language used. For example, en, ru, en_us.
5.AuthorizationWhen the web pages are password protected, the clients can use this header to authorize and identify themselves. 
6.ConnectionThis header will give the information about the connection a client can handle. A client can support either persistent or non-persistent connections. Persistent connection supports multiple files in one request, whereas non-persistent connection will require setting up again and again.
7.Content-lengthThis header tells about the content length for POST methods. This header returns the length of the post method in bytes.
8.CookieThis header will return cookies to the server that they sent to the browser previously.
9.HostThis header will give the knowledge of hosts and ports of the original URL of the page.
10.If-Modified sinceThis header shows that if the page has been modified since the specified date, then only the client wants that page.
11.If-Unmodified sinceThis header, unlike the above header, will show the page to the client if the page hasn’t been modified i.e., the page is older than the specified date.
12.ReferrerThis header will contain the information of the page that referred to another page i.e., if webpage 1 referred to webpage 2 then the referrer of the header will contain the information of web page 1.
13.User-AgentThis header will give the information of the client or browser that has made the particular request.

Request – Object of HttpServletRequest Implementation

This is an in-built implicit object of javax.servlet.http.HttpServletRequest. It is passed as a parameter to jspService method. This instance is created each time a request is generated. Using this object we can request a parameter session, cookies, header information, server name, server port, contentType, character encoding, etc. The syntax to use request is:

request.methodname(“value”);

Methods used to retrieve information of HTTP headers :

S.No.MethodDescription
1.Cookie getCookies()This method will return the array that has all cookie objects that the client sent along with this request.
2.Enumeration getAttributeNames()This method will return the name of all the attributes in an enumeration related to this request. 
3.Enumeration getHeaderNames()This method will return an enumeration of names of all the headers concerned. 
4.Enumeration getParameterNames()This method will return an enumeration of parameter names related to the request.
5.HttpSession getSession()This method returns the session that  relates to the request. If the request doesn’t possess a session, then it will create a session.
6.HttpSession getSession( boolean create)This method will return the HttpSession currently associated with the request. If the request doesn’t have a session and the value of create is true then it will create a new session.
7.Locale getLocale()This method will return the Locale value preferred by the client. It is the content language that the client accepts on the basis of header Accept Language. 
8.Object getAttribute(String name)This method will return the value of the attribute mentioned. If it doesn’t find one then it will return null.
9.ServletInputStream getInputStream()This method will return the converted binary data of the body of the request using ServletInputStream.
10.String getAuthType()This method will return the authentication type used to protect the servlet. It can be ‘SSL’, ‘BASIC’ or null if the page is not protected.
11.String getCharacterEncoding()This method will return the character encoding that was used in the body of the concerned request.
12.String getContentType()This method will return the content type of the request body. It returns null if the content type is unknown.
13String getContextPath()This method returns the part of the URI that represents the context of the page.
14.String getHeader(String name)This method will return the string type of value of the requested header.
15.String getMethod()This method will return the HTTP method that the request used. It can be GET, POST, etc.
16.String getParameter(String name)The method will return the value of the parameter requested. It returns null if it doesn’t find one. 
17.String getPathInfo()It returns any extra information related to the path that the client might have sent along with the request.
18.String getProtocol()This method will return the version and name of the protocol used by the request.
19.String getQueryString()This method returns the part of the URL of the request after the question mark (?) sign called as query string. 
20.String getRemoteAddr()This method gets or says returns the IP (Internet Protocol) of the client that made the request.
21.String getRemoteHost()This method will return the name of the client that made the request.
22.String getRemoteUser()This method will return the login information of the user that made the request only if the user is authentic. It returns null otherwise.
23.String getRequestURI()This method will return the portion of URL starting from protocol to Query present in the HTTP request. 
24.String getRequestedSessionId()This method will return the session ID given by the client.
25.String getServletPath()This method will return the portion of the request URL that is called the JSP page. 
26.String getParameterValues(String name)This method will return an array of all the values that the specified or requested parameter has. This method returns null if the parameter doesn’t exist.
27.boolean isSecure()This method will return a Boolean that indicates if the request was or wasn’t made over a channel that was secure. For example, https. 
28.int getContentLength()This method will return the length of content i.e., the body of the request made available by an input stream. This length is in bytes if known, or it returns -1 if the length of the content is unknown. 
29.int getIntHeader(String name)This method returns an int value of the header requested. 
30.int getServerPort()This method will return the port to which request was made. It returns a port number.
31.String getServerName()This method gives the name of the server to which request was made.

This method gives the name of the server to which request was made.

For Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Client Request</title>
</head>
<body>
<h3>--DataFlair--</h3>
<h2>Header Information</h2>
 <table border="1">
<tr>
<th>Header</th><th>Header Values</th>
</tr>
<%
  HttpSession mysession = request.getSession(); 
  out.print("<tr><td>Session Name is </td><td>" +mysession+ "</td.></tr>");
  Locale mylocale = request.getLocale ();
  out.print("<tr><td>Locale Name is</td><td>" +mylocale + "</td></tr>");
  String path = request.getPathInfo(); 
  out.print("<tr><td>Path Name </td><td>" +path+ "</td></tr>"); 
  String method = request.getMethod();
  out.print("<tr><td>Method </td><td>" +method + "</td></tr>"); 
  String charEncoding = request.getCharacterEncoding();
  out.print("<tr><td>Character Encoding </td><td>" +charEncoding + "</td></tr>"); 
  String serverName = request.getServerName(); 
  out.print("<tr><td>Server Name  </td><td>" +serverName+ "</td></tr>");
  int portname = request.getServerPort(); 
  out.print("<tr><td>Server Port  </td><td>" +portname+ "</td></tr>");
  Enumeration headernames = request.getHeaderNames();
  while(headernames.hasMoreElements()) { 
    String parameterName = (String)headernames.nextElement();
    out.print ("<tr><td>" + parameterName + "</td>" );
    
    String parameterValue = request.getHeader(parameterName);
    out.println("<td> " + parameterValue + "</td></tr>");
  }
%>
</body>
</html>

Explanation: This example gets the header information using request. We are obtaining information like locale name, path info, server name, port number, enumeration of all the header names using various methods with the request.

Output:

jsp header

 

JSP Server Response

JSP response is created by a server whenever a client makes a request. A typical response may include a status line, response header, blank line, and document.

Response headers are:

S.No.HeaderDescription
1.AllowThis header gives the method of the request that the server can support. It can be GET, PUT, POST.
2.Cache-

Control

This header gives the information about the storage of cache data of the response document. It can have the value like private, public, no-cache. 

Private cache implies that the document is made for a single user meant to store in non-sharable caches.

Public cache means a document is cacheable.

No-cache means the document is non-cacheable.

3.ConnectionThis header tells the browser to use a persistent(keep alive) connection or a non-persistent (set up required again and again) connection.
4.Content-

Disposition

This header lets the browser ask the user regarding saving the response to the file of a given name.
5.Content-

Encoding

This header tells the page Encoding that was used at the time of transmission. 
6.Content-

Language

This header tells the language of the document. It can be en_IN, en_US, ru etc..
7.Content-

Length

This information tells about the length of response. Length is in bytes. It is possible only if the browser uses persistent connection.
8.Content-TypeThis header specifies Multipurpose Internet Mail Extension (MIME) type of the document received in response.
9.ExpiresThis header gives the expiry date of information (out of date). This information should not be cached.
10.Last-

Modified

This header gives the information about the last modified time. Using it the client can request for the last modified time.
11.LocationThis header gets the location of the document and notifies the browser. The browser connects to the location given and retrieves the document.
12.RefreshThis header implies that after what time the browser should ask for an updated page. This header refreshes and auto-loads the page after the specified time if the user has specified it.
13.Retry-AfterThis response tells the user that service is unavailable and after how much time it can retry its request.
14.Set-CookieThis header tells about the cookie object related to the page.

Response-Object of HttpServletResponse Implementation

This is an object from HttpServletResponse. This object rather gets passed as a parameter to jspService() like request. It is the response given to the user. One can redirect, get header information, add cookies, send error messages using this object. The Syntax for using response object is:

response.methodName();

Methods that use response object are:

S.No.Method Description
1.String encodeRedirectURL(String url)This method encodes the URL mentioned that will be used for the sendRedirect method. It returns the unchanged URL, only if encoding is not required.
2.String encodeURL(String url)This method has the capability to encode the mentioned URL with the inclusion of the session ID. It will return the URL unchanged only if the encoding is not a requirement.
3.boolean containsHeader(String name)This method will check if the mentioned header is set or not. Its return type is Boolean value.
4.boolean isCommitted()This method checks and returns a bool value implying that response is committed or not.
5.void addCookie(Cookie cookie)This method will add a cookie to the given response.
6.void addDateHeader(String name, long date)This method will add a header (response header) with the specified name and date as value.
7.void addHeader(String name, String value)This method will add a header (response header) with specified string name and value.
8.void addIntHeader(String name, int value)This method adds a header (response header) with the specified name and value(integer).
9.void flushBuffer()This method flushes the buffer but the content in the buffer is written to the client before flushing.
10.void reset()This method clears the buffer completely along with headers and status codes
11.void resetBuffer()This method clears and resets the buffer present in the response. It however doesn’t clear status codes and headers. 
12.void sendError(int sc)This method sends the error using the error status code and flushing the buffer.
13.void sendError(int sc, String msg)This method sends a response containing error to the client. 
14.void sendRedirect(String location)This method sends a temporary redirect to the client. This redirect can be to a redirect URL specified as the parameter.
15.void setBufferSize(int size)This method sets the buffer size as a preferred one for the response’s body.
16.void setCharacterEncoding(String charset)This method can set the response’s character. For example, UTF-8 etc.
17.void setContentLength(int len)This method sets the content length of the body of response. 
18.void setContentType(String type)This method has the ability to set the type of content of the response only if it is not committed.  
19.void setDateHeader(String name, long date)This method sets the name and date of response headers.
20.void setHeader(String name, String value)This method sets the name and value of the response header.
21.void setIntHeader(String name, int value)This method will set the specified name and integer value as the name and value of the response header.
22.void setLocale(Locale loc)If the response is not committed, then this method will set the locale of the response.
23.void setStatus(int sc)This method will set the status code of the response.

For Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Server Response</title>
</head>
<body>
<h3>--DataFlair--</h3>
<h2>Response</h2>
<%
Locale mylcl = response.getLocale();
out.println("Locale: " + mylcl + ".\n");
response.flushBuffer();
PrintWriter op = response.getWriter();
op.println("From writer object");
String cotype = response.getContentType();
out.println("The content type : " + cotype + ".\n");
out.newLine();
  response.setIntHeader("Refresh", 5);
  Date mydate = new Date();
  out.println("Today's date is : " +mydate.toString() + ".\n");
%>

</body>
</html>

Explanation: This example shows the use of a response object in order to get information like content type, locale value, using flush buffer, writing response directly to output stream, reloading the response and setting a value for the same.

Output:

jsp response server

Introduction – HTTP Status Codes

When a request is sent by the client, a response is generated by the server. This response contains a status line that shows HTTP version, status code and a message. This message describes the status code generated by the server.

200 is the default status code that tells that the request is OK. We don’t need to specify this status code.
Syntax: 

response.sendError(status code, "error!!!" )

Some status codes are as follows:

CodeMessageDescription
100ContinueServer received only a portion of the request but the client should continue until the server rejects the request.
101Switching ProtocolsThe server may intend to switch protocol.
200OKThe request is fine.
201CreatedA new source has been created as the request was complete. 
202AcceptedRequest is accepted for processing
203Non-authoritative InformationInformation in the requested page is non-authoritative
204No ContentNo content available.
205Reset ContentContent has been reseted
206Partial ContentContent is partial.
300Multiple ChoicesThe user gets a link list of 5 addresses (maximum). A user can have multiple choices for the locations they wish.
301Moved PermanentlyThis code implies that a new location (URL) is present for the requested page. Simply saying that the page has moved permanently.
302FoundThis works as status code moves temporarily. This implies that the page has been temporarily moved to a new URL.
303See OtherSee or go to a different URL to find the page for which request was made.
304Not ModifiedThe page has not been modified.
305Use ProxyUse proxy before accessing the requested page.
306Unusedno longer used.
307Temporary RedirectThe page that has been requested is redirected to a new location temporarily.
400Bad RequestRequest was not understood by the server.
401UnauthorizedThe page that has been requested needs authorization using a username and password.
402Payment RequiredThe client should pay to access the requested page.
403ForbiddenForbidden access to the page requested.
404Not FoundRequested page could not be found by the server.
405Method Not AllowedUnallowed method specified in the request.
406Not AcceptableUnacceptable response by the client.
407Proxy Authentication Requiredauthentication must be done using a proxy server before serving the request.
408Request TimeoutThe request took a longer time to process compared to the time the server was prepared for waiting.
409ConflictDue to the conflict, the request was unable to  complete.
410GoneRequested page is unavailable now.
411Length RequiredThe undefined content length causes the rejection of the request.
412Precondition FailedThe server evaluates the precondition mentioned in the request as false and rejects the request.
413Request Entity Too LargeThe entity requested is too large and thus the server doesn’t accept the request.
414Request-url Too LongThe requested URL path is too long and thus the server doesn’t accept requests. For example, conversion of a post request to get request.
415Unsupported Media TypeThe media type is not supported so the request is not accepted by the server.
417Expectation FailedThis implies that the server was unable to fulfil the needs of Expect header field.
500Internal Server ErrorThe request was not complete as the server met an unexpected condition.
501Not ImplementedThe request was not complete as the server did not support the functionality required.
502Bad GatewayUpstream server sent a response that was not valid so this request was unable to complete.
503Service UnavailableThe request was not completed. The server is temporarily overloading or down.
504Gateway TimeoutThe gateway has timed out.
505HTTP Version Not SupportedThis implies that the server doesn’t support the specified HTTP protocol version.

Some methods used to set the status codes

1. public void setStatus(int statusCode)
This method will set the arbitrary status code for the JSP Page. If we want a status code in our response or a document, then we should use the function and set int status before returning any object.

2. public void sendRedirect(String URL)
This method will generate a status code 302 response with the location header that gives the URL of the new or redirected document.

3. public void sendError(int code, String message)
This method will set the status code as integer and also an associated message as a string. This is specified inside a HTML document.

Example:

<html>
<head>
<title>HTTP Status Code2</title>
</head>
<body>
<%
response.sendError(404, "Page Not Found!!!" );
%>
</body>
</html>
<html>
<head>
<title>HTTP Status Code1</title>
</head>
<body>
<%
response.sendError(407, "Need authentication!!!" );
%>
</body>
</html>

Explanation: This example uses the sendError method to set two different types of errors with a status code and an associated message.

Output:

jsp server response

Conclusion

In reference to this article, we came to know about different JSP Client Requests as well as Server Response side. We came to know about headers present for request and response. We also learnt about different methods to retrieve the information of these headers. Further, we discussed the HTTP status codes. We learnt about errors and methods related to them.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

courses

DataFlair Team

The DataFlair Team is passionate about delivering top-notch tutorials and resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With expertise in the tech industry, we simplify complex topics to help learners excel. Stay updated with our latest insights.

Leave a Reply

Your email address will not be published. Required fields are marked *