Client Request Guru JSP

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:

  1. Cookie[] getCookies() – returns an array containing cookie objects that the client has sent
  2. Enumeration getAttributeNames() – contains enumeration of names of attributes for request
  3. Enumeration getHeaderNames() – contains enumeration of names of header .
  4. Enumeration getParameterNames() – contains enumeration of getting parameter names in the request.
  5. HttpSessiongetSession() – returns the current session associated with the request or if does not have a session then it will create a new one.
  6. 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.
  7. Object getAttribute(String name) – returns the value of named attribute as an object.
  8. ServletInputStreamgetInputStream() – retrievesbody of request as binary data.
  9. String getAuthType() – returns the name of authentication scheme to protect servlet
  10. String getCharacterEncoding() – returns name of the character encoding used in the body of the request.
  11. String getContentType() – returns the MIME type of body of the request.
  12. String getContextPath() – returns the part of request URI indicates context path of URI
  13. String getHeader(String name) – returns the request header as a string
  14. String getMethod() – returns the name of the HTTP method like GET, POST
  15. String getParameter(String name) – returns the parameter of the request as a string.
  16. String getPathInfo() – returns the path information associated with the URL
  17. String getQueryString() – returns the query string that is associated with the request URL
  18. String getServletPath() – returns the part of URLs of the request that calls the JSP
  19. String[] getParameterValues(String name) – returns the array of string objects containing the values that request parameter has
Читайте также:  Javascript как использовать api

In the example below, we are using different methods using request object

        

Client Request Guru JSP

guru headerguru header Value(s) Session Name is " +gurusession+ ""); Locale gurulocale = request.getLocale (); out.print("Locale Name is" +gurulocale + ""); String path = request.getPathInfo(); out.print("Path Name is" +path+ ""); String lpath = request.get(); out.print("Context path is" +lipath + ""); String servername = request.getServerName(); out.print("Server Name is " +servername+ ""); int portname = request.getServerPort(); out.print("Server Port is " +portname+ ""); Enumeration hnames = request.getHeaderNames(); while(hnames.hasMoreElements()) < String paramName = (String)hnames.nextElement(); out.print ("" + paramName + "" ); String paramValue = request.getHeader(paramName); out.println(" " + paramValue + ""); > %>

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:

JSP Client Request

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:

  1. String encodeRedirectURL(String URL) – encodes the URL in redirectURL method.
  2. String encodeURL(String URL) – encodes the URL by including session ID.
  3. Boolean containsHeader(String name) – it contains a header in the JSP or not.
  4. Boolean isCommited() – response has been committed or not.
  5. Void addCookie(Cookie cookie) – adds cookie to the response
  6. Void addDateHeader(String name, String value) – adds response header date name and value
  7. Void addHeader(String name, String value) – adds response header with name and value
  8. Void addIntHeader(String name,int value) – adds response header with name and integer value
  9. Void flushBuffer() – forces content in the buffer to the output to the client.
  10. Void reset() – clears data in the buffer.
  11. Void resetBuffer – clears the content buffer in the response without clearing status codes.
  12. Void sendError(intsc,Stringmsg) – sends an error response to the client using status code.
  13. Void sendRedirect(String location) – sends a temporary redirect response to the client.
  14. Void setBufferSize(int size) – sets buffer size of the body
  15. Void setCharacterEncoding(String charset) – sets character encoding
  16. Void setContentType(String type) – sets the content type of the response
  17. Void setContentLength(intlen) – sets the content length of the response
  18. Void setLocale(Locale lcl) – sets the locale type of the response
  19. Void setStatus(intsc) – sets the status code of the response

In this example, we are covering different methods getLocale,flushbuffer, getWriter, get ContentType, setIntHeader.

         

Guru Response

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:

JSP Server Response

  • 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:

  1. 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
  2. Public void sendRedirect(String URL): It generates 302 response along with the location header giving URL of the new document
  3. Public void sendError(intcode,Stringmsg): It sends the status code along with the short message and it is formatted inside HTML document.

In this example, we are sending error to JSP page explicitly.

Explanation of the code:

Code Line 10: Using response object we are sending the error to a page with two parameters.

  1. Status code – It can be any of the above. In this case, we have described as 404
  2. 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:

JSP HTTP Status Codes

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.

Источник

Оцените статью