JSP Client HTTP Request & Server Response with Example
JSP actions which use constructs in XML syntax to control the behavior of the servlet engine. We will learn more in detail about various JSP Action elements like client request, server response, HTTP status codes.
JSP Client Request
- When the web page is requested, it sends information to the web server in the HTTP header.
- We can use this information using HTTPServletRequest object.
- Information sent by the browser is stored in the request header of HTTP request.
- We are using different headers to send information to the request object.
Headers in JSP
Different headers in JSP are described below:
Header | Description | Example |
---|---|---|
Accept | It specifies MIME types that browser or other clients can handle | Image/png or image/jpeg |
Accept-charset | It uses the character set used by the browser to display the information | ISO-8859-1 |
Accept- Encoding | It specifies type of encoding handled by the browser | Gzip or compress |
Accept-language | It specifies clients specified language | En,en_us |
Authorization | Header used by clients when trying to access password protected web pages | |
Connection | It indicates whether client can handle persistent HTTP connections(browser can retrieve multiple files) | Keep-alive |
Content-length | Applicable to post requests. It gives size of post data of bytes | |
Cookie | Returns cookie to server(those which were previously sent to the browser) | |
Host | Specifies the host and port of the original URL | |
If modified since | It indicates that it requires only a page if it has been changed or modified | |
If unmodified since | It indicates that it requires a page only if it has not been changed or modified | |
Referrer | Indicates URL of referring URL page | |
User-agent | Identifies browser or client making request |
HTTP Header Methods in JSP
Following methods are used to read the HTTP header in JSP page:
- Cookie[] getCookies() – returns an array containing cookie objects that the client has sent
- Enumeration getAttributeNames() – contains enumeration of names of attributes for request
- Enumeration getHeaderNames() – contains enumeration of names of header .
- Enumeration getParameterNames() – contains enumeration of getting parameter names in the request.
- HttpSessiongetSession() – returns the current session associated with the request or if does not have a session then it will create a new one.
- Locale getLocale() – returns the preferred locale that client will accept content in.It has been assigned to the response. By default, the value will be default locale of the server.
- Object getAttribute(String name) – returns the value of named attribute as an object.
- ServletInputStreamgetInputStream() – retrievesbody of request as binary data.
- String getAuthType() – returns the name of authentication scheme to protect servlet
- String getCharacterEncoding() – returns name of the character encoding used in the body of the request.
- String getContentType() – returns the MIME type of body of the request.
- String getContextPath() – returns the part of request URI indicates context path of URI
- String getHeader(String name) – returns the request header as a string
- String getMethod() – returns the name of the HTTP method like GET, POST
- String getParameter(String name) – returns the parameter of the request as a string.
- String getPathInfo() – returns the path information associated with the URL
- String getQueryString() – returns the query string that is associated with the request URL
- String getServletPath() – returns the part of URLs of the request that calls the JSP
- String[] getParameterValues(String name) – returns the array of string objects containing the values that request parameter has
Example:
In the example below, we are using different methods using request object
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.io.* java.util.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Client Request Guru JSP</title> </head> <body> <h2>Client Request Guru JSP</h2> <table border="1"> <tr> <th>guru header</th><th>guru header Value(s)</th> </tr> <% HttpSession gurusession = request.getSession(); out.print("<tr><td>Session Name is </td><td>" +gurusession+ "</td.></tr>"); Locale gurulocale = request.getLocale (); out.print("<tr><td>Locale Name is</td><td>" +gurulocale + "</td></tr>"); String path = request.getPathInfo(); out.print("<tr><td>Path Name is</td><td>" +path+ "</td></tr>"); String lpath = request.get(); out.print("<tr><td>Context path is</td><td>" +lipath + "</td></tr>"); String servername = request.getServerName(); out.print("<tr><td>Server Name is </td><td>" +servername+ "</td></tr>"); int portname = request.getServerPort(); out.print("<tr><td>Server Port is </td><td>" +portname+ "</td></tr>"); Enumeration hnames = request.getHeaderNames(); while(hnames.hasMoreElements()) { String paramName = (String)hnames.nextElement(); out.print ("<tr><td>" + paramName + "</td>" ); String paramValue = request.getHeader(paramName); out.println("<td> " + paramValue + "</td></tr>"); } %>
Explanation of the code:
Code Line 17: Using request object, we are getting the session object of that particular session, and we get the object value of that session
Code Line 19: Using request object, we are getting locale of that particular session i.een_US locale for that JSP.
Code Line 21: Using request object, we are getting path info for that JSP. In this case, it is null as there is no path for URL mentioned.
Code Line 23: Using request object, we are getting context path, i.e., root path
Code Line 25: Using request object, we are getting the server name.
Code Line 27: Using request object, we are getting server port.
Code Line 29-35: Using request object, we are getting header names which come out as enumeration, and hence we get all header values in the header names.
In this, we get all header values as a Cookie, host, connection, accept language, accept encoding.
When you execute the above code, you get the following output:
Output:
We are getting the series of values like session name, locale name, path name, server name, port name, host, context path and all the header values of that JSP.
JSP Server Response
- When a request is processed and then the response is generated from the web server. It consists of a status line, response headers, a blank line and document.
- It is the object of HTTPServletResponseclass, which is a response object.
- The status line is a version of HTML.
Response Headers in JSP
Response headers in JSP are mentioned below:
Header | Description |
---|---|
Allow | It specifies the request methods like GET, POST that server is requesting |
Cache-control | The response document can be cached. It can be public, private and no cache. No cache specifies that document should not be cached |
Connection | It instructs whether the browser should use savedHTTPConnections or not. Close value represents that browser should not use persistent in HTTPConnections and “keep-alive” means using persistent connections |
Content-disposition | To ask the user whether to save the response to disk or not |
Content-encoding | Page has to be encoded during transmission |
Content-length | Number of bytes in the response |
Content type | It specifies the MIME type of response |
Expires | Specifies till when the content should be considered out of date and should not be cached |
Last modified | It indicates when the document was last modified |
Location | It should be included with all responses which have status code has 300 as status code |
Refresh | It specifies how to find the updated page. |
Retry-after | It can be used with 503 response to tell client of how soon it can repeat request |
Set-cookie | Specifies the cookie associated with the page |
HTTP Response Header Methods in JSP
Following are the methods in JSP using response object:
- String encodeRedirectURL(String URL) – encodes the URL in redirectURL method.
- String encodeURL(String URL) – encodes the URL by including session ID.
- Boolean containsHeader(String name) – it contains a header in the JSP or not.
- Boolean isCommited() – response has been committed or not.
- Void addCookie(Cookie cookie) – adds cookie to the response
- Void addDateHeader(String name, String value) – adds response header date name and value
- Void addHeader(String name, String value) – adds response header with name and value
- Void addIntHeader(String name,int value) – adds response header with name and integer value
- Void flushBuffer() – forces content in the buffer to the output to the client.
- Void reset() – clears data in the buffer.
- Void resetBuffer – clears the content buffer in the response without clearing status codes.
- Void sendError(intsc,Stringmsg) – sends an error response to the client using status code.
- Void sendRedirect(String location) – sends a temporary redirect response to the client.
- Void setBufferSize(int size) – sets buffer size of the body
- Void setCharacterEncoding(String charset) – sets character encoding
- Void setContentType(String type) – sets the content type of the response
- Void setContentLength(intlen) – sets the content length of the response
- Void setLocale(Locale lcl) – sets the locale type of the response
- Void setStatus(intsc) – sets the status code of the response
Example:
In this example, we are covering different methods getLocale,flushbuffer, getWriter, get ContentType, setIntHeader.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.io.* java.util.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Guru Action Response</title> </head> <body> <center> <h2>Guru Response</h2> <% Locale lcl = response.getLocale(); out.println("Locale is : " + lcl + "\n"); response.flushBuffer(); PrintWriter output = response.getWriter(); output.println("This is from writer object"); String type = response.getContentType(); out.println("The content type : " + type + "\n"); // Set refresh,autoload time as 5 seconds response.setIntHeader("Refresh", 5); //Get current time Date dt = new Date(); out.println("Today's date is : " +dt.toString() + "\n"); %> </center> </body> </html>
Explanation of the code:
Code Line 13: Using response object, we get locale object of this JSP session
Code Line 15: Using response object, flushbuffer is used to force the buffer content into client
Code Line 16: Using response object, we get writer object which get output in the output stream
Code Line18: Using response object, we get content type i.e. MIME type of response object
Code Line 21: Using response object, it is used to autoload in every 5 seconds as 5 is set as the second parameter
When you execute the above code, you get the following output:
Output:
- Here we get the output as this is from writer object from getWriter, which gives us object and we can output in the output stream.
- We get the locale as en_us and content type as text/html
- We get charset as ISO 8859
- Today’s date as the current date.
JSP HTTP Status Codes
- When the request is processed, the response is generated. The response status line consists of HTTP version, a status code and an associated message.
- The message is directly associated with the status code and HTTP version, and it is determined by the server.
- By default 200 is set as a status code in JSP, so we don’t need to set explicitly.
- We can set as response.setStatus() method
The codes fall in following 5 categories:
- 100-199 – Here client indicates that it should respond with some action
- 200-299 – It signifies that request is successful
- 300-399 – They are used for files that have been moved and usually include a location header indicating new address
- 400-499 – Indicates error by the client
- 500-599 – Indicates error by the server
Some of the common status codes are below:
- 200 – Indicates everything is fine
- 301 – It has moved permanently
- 304 – Not modified since last change
- 400 – Bad request
- 404 – Not found
- 405 – Method not found
- 500 – Internal Server Error
- 503 – Service unavailable
- 505 – HTTP version not supported
HTTP Status Code Methods in JSP
Some of the status code methods in JSP are listed below:
- Public void setStatus(intstatusCode): It sets the status code whichever we want to set in that JSP Page.This will give us the message of status code which has been set
- Public void sendRedirect(String URL): It generates 302 response along with the location header giving URL of the new document
- Public void sendError(intcode,Stringmsg): It sends the status code along with the short message and it is formatted inside HTML document.
Example:
In this example, we are sending error to JSP page explicitly.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Guru Status Code</title> </head> <body> <% response.sendError(404,"Guru Page Not Found"); %> </body> </html>
Explanation of the code:
Code Line 10: Using response object we are sending the error to a page with two parameters.
- Status code – It can be any of the above. In this case, we have described as 404
- Message – It can be any specific message that we want to show the error
If you execute the above code, you get the following output:
Output:
Here we get error code as 404, which was sent from the code and also displays”Guru Page not found” message seen in the output.
Summary
- In this article, we have learnt about client request and server response on how the request is intercepted and how the responses are manipulated.
- JSP actions which use constructs in XML syntax to control the behavior of the servlet engine.
- When the web page is requested, it sends information to the web server in the HTTP header.
- When a request is processed and then the response is generated from the web server. It consists of a status line, response headers, a blank line and document.
- When the request is processed, the response is generated. The response status line consists of HTTP version, a status code and an associated message.