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 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. | Header | Information |
1. | Accept | This 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-charset | This 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-Encoding | This 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-language | If 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. | Authorization | When the web pages are password protected, the clients can use this header to authorize and identify themselves. |
6. | Connection | This 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-length | This header tells about the content length for POST methods. This header returns the length of the post method in bytes. |
8. | Cookie | This header will return cookies to the server that they sent to the browser previously. |
9. | Host | This header will give the knowledge of hosts and ports of the original URL of the page. |
10. | If-Modified since | This header shows that if the page has been modified since the specified date, then only the client wants that page. |
11. | If-Unmodified since | This 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. | Referrer | This 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-Agent | This 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. | Method | Description |
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. |
13 | String 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 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. | Header | Description |
1. | Allow | This 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. | Connection | This 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-Type | This header specifies Multipurpose Internet Mail Extension (MIME) type of the document received in response. |
9. | Expires | This 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. | Location | This header gets the location of the document and notifies the browser. The browser connects to the location given and retrieves the document. |
12. | Refresh | This 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-After | This response tells the user that service is unavailable and after how much time it can retry its request. |
14. | Set-Cookie | This 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:
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:
Code | Message | Description |
100 | Continue | Server received only a portion of the request but the client should continue until the server rejects the request. |
101 | Switching Protocols | The server may intend to switch protocol. |
200 | OK | The request is fine. |
201 | Created | A new source has been created as the request was complete. |
202 | Accepted | Request is accepted for processing |
203 | Non-authoritative Information | Information in the requested page is non-authoritative |
204 | No Content | No content available. |
205 | Reset Content | Content has been reseted |
206 | Partial Content | Content is partial. |
300 | Multiple Choices | The user gets a link list of 5 addresses (maximum). A user can have multiple choices for the locations they wish. |
301 | Moved Permanently | This code implies that a new location (URL) is present for the requested page. Simply saying that the page has moved permanently. |
302 | Found | This works as status code moves temporarily. This implies that the page has been temporarily moved to a new URL. |
303 | See Other | See or go to a different URL to find the page for which request was made. |
304 | Not Modified | The page has not been modified. |
305 | Use Proxy | Use proxy before accessing the requested page. |
306 | Unused | no longer used. |
307 | Temporary Redirect | The page that has been requested is redirected to a new location temporarily. |
400 | Bad Request | Request was not understood by the server. |
401 | Unauthorized | The page that has been requested needs authorization using a username and password. |
402 | Payment Required | The client should pay to access the requested page. |
403 | Forbidden | Forbidden access to the page requested. |
404 | Not Found | Requested page could not be found by the server. |
405 | Method Not Allowed | Unallowed method specified in the request. |
406 | Not Acceptable | Unacceptable response by the client. |
407 | Proxy Authentication Required | authentication must be done using a proxy server before serving the request. |
408 | Request Timeout | The request took a longer time to process compared to the time the server was prepared for waiting. |
409 | Conflict | Due to the conflict, the request was unable to complete. |
410 | Gone | Requested page is unavailable now. |
411 | Length Required | The undefined content length causes the rejection of the request. |
412 | Precondition Failed | The server evaluates the precondition mentioned in the request as false and rejects the request. |
413 | Request Entity Too Large | The entity requested is too large and thus the server doesn’t accept the request. |
414 | Request-url Too Long | The requested URL path is too long and thus the server doesn’t accept requests. For example, conversion of a post request to get request. |
415 | Unsupported Media Type | The media type is not supported so the request is not accepted by the server. |
417 | Expectation Failed | This implies that the server was unable to fulfil the needs of Expect header field. |
500 | Internal Server Error | The request was not complete as the server met an unexpected condition. |
501 | Not Implemented | The request was not complete as the server did not support the functionality required. |
502 | Bad Gateway | Upstream server sent a response that was not valid so this request was unable to complete. |
503 | Service Unavailable | The request was not completed. The server is temporarily overloading or down. |
504 | Gateway Timeout | The gateway has timed out. |
505 | HTTP Version Not Supported | This 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:
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