0% found this document useful (0 votes)
8 views

Unit 2

swbdjhej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 2

swbdjhej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit II

Server Response, HTTP Status Codes, HTTP Response


Headers, Handling Cookies and Session Tracking
Specifying Status Codes
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to
redirect response to another resource, it may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another
request. So, it can work inside and outside the server.

Difference between forward() and sendRedirect()


method
There are many differences between the forward() method of RequestDispatcher and
sendRedirect() method of HttpServletResponse interface. They are given below:
Syntax of sendRedirect() method

public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method

response.sendRedirect("http://www.javatpoint.com");
Creating custom google search using sendRedirect
In this example, we are using sendRedirect method to send request to google server with the request data.

index.html

<html>

<head>

<meta charset="ISO-8859-1">

<title>sendRedirect example</title>

</head>

<body>

<form action="MySearcher">

<input type="text" name="name">

<input type="submit" value="Google Search">

</form>

</body> </html>
MySearcher.java

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class MySearcher extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String name=request.getParameter("name");

response.sendRedirect("https://www.google.co.in/#q="+name);

}
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content
of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet,
JSP file, or HTML file) on the server.
2. public void include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML
file) in the response.
Go through this link

https://www.javatpoint.com/requestdispatcher-in-servlet
HTTP Response Headers: Setting Response Headers from Servlets
As discussed in the previous section, a response from a Web server normally consists of a status line, one or more
response headers (one of which must be Content-Type), a blank line, and the document. To get the most out of
your servlets, you need to know how to use the status line and response headers effectively, not just how to
generate the document.

Setting the HTTP response headers often goes hand in hand with setting the status codes in the status line, as
discussed in the previous section. For example, all the "document moved" status codes (300 through 307) have an
accompanying Loca_tion header, and a 401 (Unauthorized) code always includes an accompanying
WWW-Authenticate header. However, specifying headers can also play a useful role even when no unusual
status code is set. Response headers can be used to specify cookies, to supply the page modification date (for
client-side caching), to instruct the browser to reload the page after a designated interval, to give the file size so
that persistent HTTP connections can be used, to designate the type of document being generated, and to perform
many other tasks. This section gives a brief summary of the handling of response headers. See Chapter 7 of Core
Servlets and JavaServer Pages (available in PDF at http://www.moreservlets.com) for more details and examples.
Setting Response Headers from Servlets
The most general way to specify headers is to use the setHeader method of HttpServletResponse. This method takes
two strings: the header name and the header value. As with setting status codes, you must specify headers before
returning the actual document.

In addition to the general-purpose setHeader method, HttpServletResponse also has two specialized methods to set
headers that contain dates and integers:

● setDateHeader(String header, long milliseconds) This method saves you the trouble of translating a Java
date in milliseconds since 1970 (as returned by System.currentTimeMillis, Date.getTime, or
Calendar.getTimeInMillis) into a GMT time string.
● setIntHeader(String header, int headerValue) This method spares you the minor inconvenience of
converting an int to a String before inserting it into a header.
Understanding HTTP / 1.1 Response Headers

6 Response
6.1 Status-Line

The first line of a Response message is the Status-Line, consisting of the protocol version
followed by a numeric status code and its associated textual phrase, with each element
separated by SP characters. No CR or LF is allowed except in the final CRLF sequence.

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF


6.1.1 Status Code and Reason Phrase

The Status-Code element is a 3-digit integer result code of the attempt to understand and satisfy the request. These
codes are fully defined in section 10. The Reason-Phrase is intended to give a short textual description of the
Status-Code. The Status-Code is intended for use by automata and the Reason-Phrase is intended for the human user.
The client is not required to examine or display the Reason- Phrase.

The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role.
There are 5 values for the first digit:

- 1xx: Informational - Request received, continuing process

- 2xx: Success - The action was successfully received,


understood, and accepted

- 3xx: Redirection - Further action must be taken in order to


complete the request

- 4xx: Client Error - The request contains bad syntax or cannot


be fulfilled

- 5xx: Server Error - The server failed to fulfill an apparently


valid request
Status-Code =
"100" ; Section 10.1.1: Continue
| "101" ; Section 10.1.2: Switching Protocols
| "200" ; Section 10.2.1: OK
| "201" ; Section 10.2.2: Created
| "202" ; Section 10.2.3: Accepted
| "203" ; Section 10.2.4: Non-Authoritative Information
| "204" ; Section 10.2.5: No Content
| "205" ; Section 10.2.6: Reset Content
| "206" ; Section 10.2.7: Partial Content
| "300" ; Section 10.3.1: Multiple Choices
| "301" ; Section 10.3.2: Moved Permanently
| "302" ; Section 10.3.3: Found
| "303" ; Section 10.3.4: See Other
| "304" ; Section 10.3.5: Not Modified
| "305" ; Section 10.3.6: Use Proxy
| "307" ; Section 10.3.8: Temporary Redirect
| "400" ; Section 10.4.1: Bad Request
| "401" ; Section 10.4.2: Unauthorized
| "402" ; Section 10.4.3: Payment Required
| "403" ; Section 10.4.4: Forbidden
| "404" ; Section 10.4.5: Not Found
| "405" ; Section 10.4.6: Method Not Allowed
| "406" ; Section 10.4.7: Not Acceptable
| "407" ; Section 10.4.8: Proxy Authentication Required
| "408" ; Section 10.4.9: Request Time-out
| "409" ; Section 10.4.10: Conflict
| "410" ; Section 10.4.11: Gone
| "411" ; Section 10.4.12: Length Required
| "412" ; Section 10.4.13: Precondition Failed
| "413" ; Section 10.4.14: Request Entity Too Large
| "414" ; Section 10.4.15: Request-URI Too Large
| "415" ; Section 10.4.16: Unsupported Media Type
| "416" ; Section 10.4.17: Requested range not satisfiable
| "417" ; Section 10.4.18: Expectation Failed
| "500" ; Section 10.5.1: Internal Server Error
| "501" ; Section 10.5.2: Not Implemented
| "502" ; Section 10.5.3: Bad Gateway
| "503" ; Section 10.5.4: Service Unavailable
| "504" ; Section 10.5.5: Gateway Time-out
| "505" ; Section 10.5.6: HTTP Version not supported
| extension-code
6.2 Response Header Fields

The response-header fields allow the server to pass additional information about the response which cannot
be placed in the Status- Line. These header fields give information about the server and about further access
to the resource identified by the Request-URI.

response-header = Accept-Ranges ; Section 14.5


| Age ; Section 14.6
| ETag ; Section 14.19
| Location ; Section 14.30
| Proxy-Authenticate ; Section 14.33

| Retry-After ; Section 14.37


| Server ; Section 14.38
| Vary ; Section 14.44
| WWW-Authenticate ; Section 14.47
Using Servlets to Generate JPEG Images

1. Send the output in the appropriate format. This format varies among document types, of course, but
in most cases you send binary data, not strings as you do with HTML documents. Consequently,
servlets will usually get the raw output stream by using the getOutputStream method, rather than
getting a PrintWriter by using getWriter .

Putting these two steps together, servlets that generate non-HTML content usually have a section of their
doGet or doPost method that looks like this:

response.setContentType(" type / subtype "); OutputStream out =


response.getOutputStream();

1. Create a BufferedImage .

You create a java.awt.image.BufferedImage object by calling the BufferedImage constructor with a width, a
height, and an image representation type as defined by one of the constants in the BufferedImage class.
The representation type is not important, since we do not manipulate the bits of the BufferedImage directly
and since most types yield identical results when converted to JPEG. We use TYPE_INT_RGB . Putting this
all together, here is the normal process:

int width = ...; int height = ...; BufferedImage image = new


BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
3. Draw into the BufferedImage .
You accomplish this task by calling the image's getGraphics method, casting the resultant Graphics object to
Graphics2D , then making use of Java 2D's rich set of drawing operations, coordinate transformations, font settings,
and fill patterns to perform the drawing. Here is a simple example.

Graphics2D g2d = (Graphics2D)image.getGraphics(); g2d.set Xxx (...); g2d.fill( someShape


); g2d.draw( someShape );

4. Set the Content-Type response header.

As already discussed, you use the setContentType method of HttpServletResponse for this task. The MIME type for
JPEG images is image/jpeg . Thus, the code is as follows .

response.setContentType("image/jpeg");

5. Get an output stream.


As discussed previously, if you are sending binary data, you should call the getOutputStream method of
HttpServletResponse rather than the getWriter method. For instance:

OutputStream out = response.getOutputStream();


Handling Cookies: Remembering Usernames and Passwords
Cookies are a piece of textual information that is stored in key-value pair format in the client’s
browser during multiple requests.

Why do we use cookies?

● We use Cookies as one of the techniques of Session Tracking / State Management.


● Session Tracking is a way to maintain state (data) of a user. It is also known as State
Management.
● We use session tracking because HTTP is a stateless protocol. In stateless, the server treats
each request as a new request because it will not remember that the requests are being sent by
the same client.
● Hence, using cookies we can create a login/logout module and the server can store our data.
Working of a Cookie

● The client sends a request “req1” to the server. After processing the request “req1”, the
server sends “response+cookies”.
● These cookies are saved on the client’s browser.
● Now, if the client sends another request “req2+cookies” to the server, then first the
server will check the cookie and it will know that this is an already logged-in user and
will not treat this request “req2+cookies” as a new request. Then further processing will
be done by the server.
● That’s how a state will be established.
How to use cookies in java?

● To create cookies, use the Cookies class in javax.servlet.http package.


● To make a cookie, create an object of the cookie class and pass a name-value pair.

How to attach a cookie to a response?

● To attach a cookie to a response, use addCookie(cookie) method of response interface.

How to fetch a cookie when a client sends another request (i.e., req2+cookie) ?

● Cookie will come through a request so we will take help from the request object.
● request.getCookies() method will return an array of cookies.
● getName() and getValue() methods of Cookie class are used to fetch the key and its corresponding value
from the array of cookies.
● If no cookies are found, then it will return null means the client is a new user and the request is also new.
How to delete a cookie?

● A cookie is deleted to log out the user.


● In the key-value pair, pass an empty string.
● Also, use setMaxAge() method of Cookie class to indicate after how long the cookie
should expire.
public void invalidateSession() {

// Request object to fetch the cookies


HttpServletRequest request = this.getThreadLocalRequest();

// Response object to delete the cookies


HttpServletResponse response = this.getThreadLocalResponse();
response.setContentType("text/html");

Cookie[] cookies = request.getCookies();

// Delete all the cookies


if (cookies != null) {

for (int i = 0; i < cookies.length; i++) {

Cookie cookie = cookies[i];


cookies[i].setValue(null);
cookies[i].setMaxAge(0);
response.addCookie(cookie);
}
}
What are session cookies?

Session cookies are temporary data files that websites place on a device while it’s actively being used. These
cookies are designed to enhance the browsing experience within a specific session. Here’s what you should know
about session cookies:

● Short lifespan: They exist only as long as the browser remains open and are automatically deleted upon

closure.

● Remember user actions and preferences: Session cookies help websites remember choices and actions

taken during a browsing session, such as items added to a shopping cart or login status.

● Improve website performance: By locally storing specific information on your device, session cookies reduce

the need for repeated server requests, leading to a faster browsing experience.

● Potential user tracking: Although session cookies are typically harmless, they can be utilized to track user

behavior within a website, potentially giving rise to privacy concerns.


Pros of session cookies:

● Enhanced user experience: Improve browsing within a single session.

● Temporary: Automatically deleted when the browser is closed.

● Security: Helps authenticate users during a session.

Cons of session cookies:

● Limited persistence: Can’t remember preferences across sessions.

● Privacy concerns: May track user behavior within a website.

● Session loss: Data loss if the session ends unexpectedly.

● Cross-device incompatibility: Tied to a specific device and browser.


What are persistent cookies?

Persistent cookies, on the other hand, are like the digital equivalent of a long-lasting bookmark. They stick around on your device even

after you close your browser and can last for a predetermined duration or until you manually delete them. Here’s what you need to know

about persistent cookies:

● Remains on the user’s device until they expire or are manually deleted: Persistent cookies have a longer lifespan and persist

across multiple browsing sessions. They remain on your device until they reach their expiration date or until you decide to

remove them.

● Remembers user preferences and login info across browsing sessions: Persistent cookies are often used to remember login

credentials, language preferences, or custom settings, providing convenience to users when they return to a website.

● Used for targeted ads and tracking: Marketers and advertisers often employ persistent cookies to track your online behavior over

time. This information is then used for targeted advertising, which can be unsettling for privacy-conscious individuals.
Pros of persistent cookies:

● User convenience: They remember login info and preferences, making the user experience more convenient.

● Personalization: Enable personalized content and targeted ads, enhancing engagement.

● Consistency: Maintain settings across sessions for a seamless experience.

● Efficiency: Reduce server requests for faster page loading.

Cons of persistent cookies:

● Privacy concerns: Potential for invasive tracking without consent.

● Targeted advertising: Can feel intrusive as they track user behavior for ads.

● Security risks: If compromised, login data can be accessed.

● Data accumulation: May occupy storage space over time.

● Cross-device incompatibility: Tied to a specific device and browser, not transferable.


Session Tracking in Servlets
Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the
server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
The Session Tracking API
The Session Tracking API Fortunately for us servlet developers, it's not always necessary for a servlet
to manage its own sessions using the techniques we have just discussed. The Servlet API provides
several methods and classes specifically designed to handle session tracking on behalf of servlets. In
other words, servlets have built in session tracking.[2] [2] Yes, we do feel a little like the third grade
teacher who taught you all the steps of long division, only to reveal later how you could use a
calculator to do the same thing. But we believe, as your teacher probably did, that you better
understand the concepts after first learning the traditional approach. The Session Tracking API, as we
call the portion of the Servlet API devoted to session tracking, should be supported in any web server
that supports servlets. The level of support, however, depends on the server. The minimal
implementation provided by the servlet classes in JSDK 2.0 manages sessions through the use of
persistent cookies. A server can build on this base to provide additional features and capabilities. For
example, the Java Web Server has the ability to revert to using URL rewriting when cookies fail, and it
allows session objects to be written to the server's disk as memory fills up or when the server shuts
down. (The items you place in the session need to implement the Serializable interface to take
advantage of this option.) See your server's documentation for details pertaining to your server. The
rest of this section describe the lowest-common-denominator functionality provided by Version 2.0 of
the Servlet API. docstore.mik.ua/orelly/java-ent/servlet/ch07_05.htm
Session-Tracking Basics

Session tracking is wonderfully elegant. Every user of a site is associated with a javax.servlet.http.HttpSession object
that servlets can use to store or retrieve information about that user. You can save any set of arbitrary Java objects in a
session object. For example, a user's session object provides a convenient location for a servlet to store the user's
shopping cart contents or, as you'll see in Chapter 9, "Database Connectivity", the user's database connection. A
servlet uses its request object's getSession() method to retrieve the current HttpSession object: public HttpSession
HttpServletRequest.getSession(boolean create) This method returns the current session associated with the user
making the request. If the user has no current valid session, this method creates one if create is true or returns null if
create is false. To ensure the session is properly maintained, this method must be called at least once before any
output is written to the response. You can add data to an HttpSession object with the putValue() method: public void
HttpSession.putValue(String name, Object value) This method binds the specified object value under the specified
name. Any existing binding with the same name is replaced. To retrieve an object from a session, use getValue():
public Object HttpSession.getValue(String name) This methods returns the object bound under the specified name or
null if there is no binding. You can also get the names of all of the objects bound to a session with getValueNames():
public String[] HttpSession.getValueNames() This method returns an array that contains the names of all objects bound
to this session or an empty (zero length) array if there are no bindings. Finally, you can remove an object from a
session with removeValue(): public void HttpSession.removeValue(String name) This method removes the object
bound to the specified name or does nothing if there is no binding. Each of these methods can throw a
java.lang.IllegalStateException if the session being accessed is invalid (we'll discuss invalid sessions in an upcoming
section). docstore.mik.ua/orelly/java-ent/servlet/ch07_05.htm

You might also like