0% found this document useful (0 votes)
91 views13 pages

What Are Cookies

This document discusses cookies and session tracking in Java web applications. Cookies are text files stored in the browser that can be used to track user information across requests. There are several methods for handling cookies in Java like setting domain, max age, name, and value. Session tracking maintains state about a user's requests using mechanisms like cookies, URL rewriting, hidden form fields, and the HTTPSession interface. The document provides an example of creating cookies in JSP to store a username and email, then retrieving them on another page.

Uploaded by

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

What Are Cookies

This document discusses cookies and session tracking in Java web applications. Cookies are text files stored in the browser that can be used to track user information across requests. There are several methods for handling cookies in Java like setting domain, max age, name, and value. Session tracking maintains state about a user's requests using mechanisms like cookies, URL rewriting, hidden form fields, and the HTTPSession interface. The document provides an example of creating cookies in JSP to store a username and email, then retrieving them on another page.

Uploaded by

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

What are Cookies?

 Cookies are the text files which are stored on


the client machine.
 They are used to track the information for
various purposes.
 It supports HTTP cookies using servlet
technology
 The cookies are set in the HTTP Header.
 If the browser is configured to store cookies, it
will keep information until expiry date.
Following are the cookies methods:

 Public void setDomain(String domain)


It is used to set the domain to which the cookie
applies

 Public String getDomain()


It is used to get the domain to which cookie
applies

 Public void setMaxAge(int expiry)


It sets the maximum time which should apply
till the cookie expires

 Public intgetMaxAge()
It returns the maximum age of cookie
 Public String getName()
It returns the name of the cookie

 Public void setValue(String value)


Sets the value associated with the cookie

 Public String getValue()


Get the value associated with the cookie

 Public void setPath(String path)


It sets the path to which cookie applies

 Public String getPath()


It gets the path to which the cookie applies

 Public void setSecure(Boolean flag)


It should be sent over encrypted connections
or not.

 Public void setComment(String cmt)


It describes the cookie purpose

 Public String getComment()


It the returns the cookie comments which has
been described.
How to Handle Cookies in JSP
1.Creating the cookie object
2.Setting the maximum age
3.Sending the cookie in HTTP response headers
Example:
In this example, we are creating cookies of
username and email and add age to the cookie for
10 hours and trying to get the variable names in
the action_cookie.jsp
Action_cookie.jsp.

1. <%@ page language="java"


contentType="text/html; charset=ISO-8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML
4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
7. <title>Guru Cookie</title>
8. </head>
9. <body>
10. <form action="action_cookie_main.jsp"
method="GET">
11. Username: <input type="text"
name="username">
12. <br />
13. Email: <input type="text" name="email" />
14. <input type="submit" value="Submit" />
15. </form>
16. </body>
17. </html>

Action_cookie_main.jsp

1. <%@ page language="java"


contentType="text/html; charset=ISO-8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML
4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <%
5.
6. Cookie username = new Cookie("username",
7.
request.getParameter("username"));
8. Cookie email = new Cookie("email",
9. request.getParameter("email"));
10.  
11.
12. username.setMaxAge(60*60*10);
13. email.setMaxAge(60*60*10);
14.  
15. // Add both the cookies in the response
header.
16. response.addCookie( username );
17. response.addCookie( email );
18. %>
19.  
20.  
21. <html>
22. <head>
23. <meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
24. <title>Guru Cookie JSP</title>
25. </head>
26. <body>
27.  
28. <b>Username:</b>
29. <%= request.getParameter("username")%>
30. <b>Email:</b>
31. <%= request.getParameter("email")%>
32.  
33. </body>
34. </html>

Explanation of the code:


Action_cookie.jsp
Code Line 10-15: Here we are taking a form
which has to be processed in
action_cookie_main.jsp. Also, we are taking two
fields "username" and "email" which has to be
taken input from the user with a submit button.
Action_cookie_main.jsp
Code Line 6-9: Creating two cookie objects of
"username" and "email" using
request.getParameter.
Code Line 12-13: Here we are adding age to both
the cookies, which have been created of 10 hours
i.e. cookies will expire in that age.
Code Line 16-17: Adding cookies to the session of
username and email and these two cookies can
fetched when requested by getParameter().
Output:
When you execute the above code you get the
following output:

Session Tracking :
 HTTP is a "stateless" protocol which means each time
a client retrieves a Web page, the client opens a new
connection to the Web server and the server does not
keep any record of previous client request.
 Session tracking is a mechanism that is used to
maintain state about a series of requests from the
same user(requests originating from the same
browser) across some period of time.
 A session id is a unique token number assigned to a
specific user for the duration of that user's session.

Need Of Session Tracking :


HTTP is a stateless protocol so When there is a series of
continuous request and response from a same client to a
server, the server cannot identify which client is sending
request.
If we want to maintain the conversational state,session
tracking is needed. For example, in a shopping cart
application a client keeps on adding items into his cart
using multiple requests.When every request is made,the
server should identify in which client's cart the item is to be
added. So in this scenario, there is a certain need for
session tracking.
Solution is, when a client makes a request it should
introduce itself by providing unique identifier every
time.There are four ways to maintain session between
web client and web server.
When we are writing java code inside the Jsp, we may get
exception inside that.In order to handle the exception we
need to write try/catch blocks many times in all the Jsp
pages.
To avoid the try ,catch block and to centralize the
exception handling
use errorPage and IsErrorPage attribute inside the JSP
where you want to handle all the exceptions.
Methods to track session :
 Cookies
 URL Rewriting
 Hidden Fields
 Session API

Cookies :
Cookies mostly used for session tracking. Cookie is a key
value pair of information, sent by the server to the
browser. This should be saved by the browser in its space
in the client computer. Whenever the browser sends a
request to that server it sends the cookie along with it.
Then the server can identify the client using the cookie.
This is not an effective way because many time browser
does not support a cookie or users can opt to disable
cookies using their browser preferences. In such case, the
browser will not save the cookie at client computer and
session tracking fails.
URL Rewriting :
Here is a simple URL which will pass two values using
GET method.You can append some extra data on the end
of each URL that identifies the session, and the server can
associate that session identifier with data it has stored
about that session.For Example Original
URL:http://javwebtutor.com/jsp/name Rewritten
URL: http://javawebtutor.com/jsp/name?sessionid=12345 .
When a request is made an additional parameter is
appended with the url.sessionid=12345, the session
identifier is attached as sessionid=12345 which can be
accessed at the web server to identify the client.

Hidden Form Fields :


HTML forms have an entry that looks like  <INPUT
TYPE="HIDDEN" NAME="session"
VALUE="...">.  This means that, when the form is
submitted, the specified name and value are included in
the GET or POST data. This can be used to store
information about the session. However, it has the major
disadvantage that it only works if every page is
dynamically generated, since the whole point is that each
session has a unique identifier.

The session Object :


Servlets provided HttpSession Interface will provides a
way to identify a user across multiple request to a Web
site and to store information about that user.
For JSPs, by default a session is automatically created for
the request if one does not exist. So if your starting page
is a JSP, a session would have already been created
when you get the first request.
1. Setting Session :
Before we validate or check the existing session it is
important to know that how we can set session in JSP. We
need to use session.setAttribute("ATTRIBUTE
NAME","ATTRIBUTE VALUE") method for setting value in
session.you can set as many attribute as you want.
2. Retrieving values from session attribute :
To retrieve value from session attribute we need to use
following method. session.getAttribute("attribute name");
The information can be stored in the session for the
current session by setAttribute() and then retrieve by
getAttribute() method, whenever needed.
Setting Session : session.setAttribute("username",
name);
Getting Session : session.getAttribute("username")
To understand a session let us create a very simple
example of getting the name from the user and saving it in
the session, we will retrieve this name from session on
next page and display on the page.
index.jsp
?
1 <%@ page isErrorPage="true" %>
2 <html>
3 <head>
4 <title>Session Management Example</title>
5 </head>
6 <body>
7 <form method="post" action="firstpage.jsp">
8 <font size=5>Enter your name<input type="text"
name="name"></font><br><br>
<font size=5>Enter your password<input
9
type="password" name="password">
10 </font><br><br>
11 <input type="submit" name="submit"
12 value="submit">
13 </form>
14 </body>
</html>
firstpage.jsp
?
<%
1 String name = request.getParameter("name");
2 String password =
3 request.getParameter("password");
4 if (name.equals("mukesh") &&
5 password.equals("kumar")) {
6 session.setAttribute("username", name);
7 response.sendRedirect("secondpage.jsp");
8 }
9 else {
10         response.sendRedirect("index.jsp");
11     }
%>
secondpage.jsp
?
1 <html>
2 <head>
3 <title>Welcome in the program of session</title>
4 </head>
<body>
5 <font size = 5>Hello <%=
6 session.getAttribute("username") %></font>
7 </body>
8 </html>

Output in Browser :

When entered value is wrong you will be redirected to


index.jsp page

You might also like