Unit 2
Unit 2
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.
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">
</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;
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.
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.
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:
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.
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:
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:
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");
● 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?
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?
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
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
● 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.
● Targeted advertising: Can feel intrusive as they track user behavior for ads.
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
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