Você está na página 1de 39

Tracking Users

with
Sessions and Cookies
Tracking Users with Sessions and
Cookies
There are several ways of tracking users, including the following:
 Hidden text—Using hidden controls in a Web page is the easiest way of
associating some information with the user that's not directly accessible to
him. However, the hidden text can be seen if the user looks at the HTML for
the Web page directly.
 Cookies—This is probably the most common way of tracking users on the
Internet. You can store information in a user's computer using cookies, and
retrieve it when you need it. You can also specify how long the cookie
should exist before being deleted by the browser.
 Sessions—Sessions are something the server offers us to support user
tracking, and they're great, although they can take up a lot of resources on
the server. Sessions let you preserve data between accesses to a Web page
by the same user.
 Applications—Applications are much like sessions, as you'll see, but they're
more general—you can share data between all the JSP pages in a site using
applications. In other words, unlike sessions, applications can be used to
track multiple users at the same time.
 Sessions, applications, and JavaBeans—You can also set JavaBeans so
they'll be included in a session or application. Normally, the data in a
JavaBean is reset each time the user accesses a page and creates an object
from that bean, but you can include the bean in a session or application so
its data is preserved between accesses by the same user.
Hidden Controls
Using Hidden Controls
 Using HTML hidden controls is an easy way to
store data in a Web page.
 For example, in this JSP page, the code will
let the user set the text to store in a hidden
control in a text field:
Example Setting/Reading Hidden Text

<HTML> <HEAD>
<TITLE>Reading Hidden Controls</TITLE>
</HEAD>
<BODY>
<H1>Reading Hidden Controls</H1>
<%
String text = "";
if(request.getParameter("TEXT1") != null) {
out.println("The hidden text is:" + request.getParameter("TEXT1"));
text = request.getParameter("TEXT1");
}
%>
<FORM ACTION="ch07_01.jsp" METHOD="POST">
<INPUT TYPE="TEXT" NAME="TEXT1">
<INPUT TYPE="HIDDEN" NAME="HIDDEN"
VALUE="<%= text%>">
<INPUT TYPE="SUBMIT" VALUE="Set Hidden Text">
</FORM>
</BODY> </HTML>
Cookies
What are Cookies ?
 Cookies are short pieces of data sent by web servers
to the client browser.
 The cookies are saved to clients hard disk in the
form of small text file.
 Cookies helps the web servers to identify web users,
by this way server tracks the user.
 Cookies pay very important role in the session
tracking.
Cookie Class
 In JSP cookie are the object of the class
javax.servlet.http.Cookie.
 This class is used to creates a cookie, a small amount of
information sent by a servlet to a Web browser, saved by the
browser, and later sent back to the server.
 A cookie's value can uniquely identify a client, so cookies are
commonly used for session management.
 A cookie has a name, a single value, and optional attributes
such as a comment, path and domain qualifiers, a maximum
age, and a version number.
 The getCookies() method of the request object returns an
array of Cookie objects.
 Cookies can be constructed using the following code:

Cookie(java.lang.String name,java.lang.String value)


Cookie Methods
Method Description
Returns the comment describing the purpose of this cookie, or null if no such
getComment()
comment has been defined.
getMaxAge() Returns the maximum specified age of the cookie.
getName() Returns the name of the cookie.
getPath() Returns the prefix of all URLs for which this cookie is targeted.
getValue() Returns the value of the cookie.
setComment(Stri If a web browser presents this cookie to a user, the cookie's purpose will be
ng) described using this comment.
Sets the maximum age of the cookie. The cookie will expire after that many
seconds have passed. Negative values indicate the default behavior: the
setMaxAge(int)
cookie is not stored persistently, and will be deleted when the user web
browser exits. A zero value causes the cookie to be deleted
setPath(String) This cookie should be presented only with requests beginning with this URL.
Sets the value of the cookie. Values with various special characters (white
space, brackets and parentheses, the equals sign, comma, double quote,
setValue(String)
slashes, question marks, the "at" sign, colon, and semicolon) should be
avoided. Empty values may not behave the same way on all browsers.
Creating a Cookie
 Here, the code will create a cookie and place some
text in it, and another page will read the cookie and
display that text.
 To create the cookie, you use the Cookie class's
constructor, passing it the name of the cookie
(which will be message here) and the text in the
cookie (which will just be "Hello!" in this case).
 You can also set the length of time the cookie will
exist on the user's computer with the setMaxAge
method, which you pass a value in seconds to—to
make the cookie last for a day, you can pass a value
of 24 * 60 * 60 this way:
Setting a Cookie – Example1
<HTML>
<HEAD>
<TITLE>Setting a Cookie</TITLE>
</HEAD>

<BODY>
<H1>Setting a Cookie</H1>

<%
Cookie cookie1 = new Cookie("message", "Hello!");
cookie1.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
%>

<A HREF="ch07_03.jsp"/>Read the cookie</A>


</BODY>
</HTML>
cookieform.jsp
This example uses a form to accept the Value and sets it as a cookie value
in the cookie.

<%@ page language="java" %>


<html>
<head>
<title>Cookie Input Form</title>
</head>
<body>
<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text"
name="username"><br>
<input type="submit" value="Submit">

</form>
</body> </html>
setcookie.jsp
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
If (username==null) username="";

Date now = new Date();


String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
%>

<html> <head> <title>Cookie Saved</title> </head>


<body>
<p><a href="showcookievalue.jsp">Next Page to view the cookie
value</a><p>
</body>
showCookieValue.jsp
<%@ page language="java" %>
<% String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
} } }
%> <html> <head> <title>Show Saved Cookie</title> </head> <body>
<%
if (myCookie == null) {
%>
No Cookie found with the name <%=cookieName%>
<%
} else {
%>
<p>Welcome: <%=myCookie.getValue()%>.
<% } %> </body>
Reading a Cookie
 To read a cookie in the user's computer, you use the request
object's getCookies method.
 This method returns an array of Cookie objects (or null if there
are no cookies) So how do you read the cookie named message?
 Are you passed all the cookies on the computer?
 No, you're only passed the cookies that came from the same
domain as the page you're using the getCookies method in.
 In the Next Example
 Inside the body of the loop, you can get the name of each
cookie with the Cookie class's getName method, and its value
with the getValue method.
 If the code finds the message cookie, it displays that cookie's
value.
Reading a Cookie - Example
<HTML>
<HEAD>
<TITLE>Reading a Cookie</TITLE>
</HEAD>
<BODY>
<H1>Reading a Cookie</H1>

<%
Cookie[] cookies = request.getCookies();

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


if (cookies[loopIndex].getName().equals("message")) {
out.println("The cookie says " + cookies[loopIndex].getValue());
}
}
%>
</BODY>
</HTML>
Setting and Reading a Cookie
in the Same Page
Setting and Reading a Cookie in the Same Page - Example

<HTML> <HEAD>
<TITLE>Setting and Reading Cookies</TITLE>
</HEAD> <BODY
<%
Cookie[] cookies = request.getCookies();
boolean foundCookie = false;

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


Cookie cookie1 = cookies[loopIndex];
if (cookie1.getName().equals("color")) {
out.println("bgcolor = " + cookie1.getValue());
foundCookie = true;
}
} When you load this page the first
time, it sets the color cookie, and
if (!foundCookie) { the page background will be
Cookie cookie1 = new Cookie("color", "cyan"); white. When you load the page
cookie1.setMaxAge(24*60*60);
from then on, until the cookie
response.addCookie(cookie1);
} expires, the page reads that
%> cookie and uses it to turn the
> page background cyan
<H1>Setting and Reading Cookies</H1>
This page will set its background color using a cookie.
</BODY> </HTML>
Setting/Reading Cookie Properties
<%
// Setting a cookie with default properties
out.println("<b>Cookie with default properties:</b><br>") ;
Cookie c = new Cookie("MyDate","30-Mar-2003") ;
response.addCookie(c);
out.println("Name: "+c.getName()+"<br>");
out.println("Value: "+c.getValue()+"<br>");
out.println("Domain: "+c.getDomain()+"<br>");
out.println("Path: "+c.getPath()+"<br>");
out.println("MaxAge: "+c.getMaxAge()+"<br>");
out.println("Version: "+c.getVersion()+"<br>");

// Setting a cookie with specified properties


out.println("<b>Cookie with specified properties:</b><br>");
c = new Cookie("User","RituKamal Aggarwal");
c.setMaxAge(3*24*60*60);
response.addCookie(c) ;
out.println("Name: "+c.getName()+"<br>");
out.println("Value: "+c.getValue()+"<br>");
out.println("Domain: "+c.getDomain()+"<br>");
out.println("Path: "+c.getPath()+"<br>");
out.println("MaxAge: "+c.getMaxAge()+"<br>");
out.println("Version: "+c.getVersion()+"<br>");
Setting/Reading Cookie Properties contd…

// Checking properties of the received cookies


out.println("<b>Properties of the received cookies:</b><br>");
Cookie[] cookies = request.getCookies();
int n = 0;
if (cookies!=null) {
n = cookies.length ;
for (int i=0; i<cookies.length; i++) {
out.println("==================================<br>") ;
out.println("Name: "+cookies[i].getName()+"<br>") ;
out.println("Value: "+cookies[i].getValue()+"<br>") ;
out.println("Domain: "+cookies[i].getDomain()+"<br>") ;
out.println("Path: "+cookies[i].getPath()+"<br>") ;
out.println("MaxAge: "+cookies[i].getMaxAge()+"<br>") ;
out.println("Version: "+cookies[i].getVersion()+"<br>") ;
}
}
%>
Output
Sessions
Creating a Session
 Using sessions such as this is great for storing and
recovering data—it provides you with an environment much
like a standard program, where you interact with the user
without having to worry about having your data reset.

 This next example will show how to store the number of


times the user has accessed the page in the current session,
as well as how to get the session ID, when the session was
created, and the last time the page was accessed in the
current session.
 This example starts with the page directiv
 With the directive's session attribute set to true.

<%@page import = "java.util.*" session="true"%>


javax.servlet.http.HttpSession Methods
Method Does This
void addCookie(Cookie cookie) Adds the specified cookie to the response object.
java.lang.Object getAttribute Returns the object of the given name in this session.
(java.lang.String name)
java.util.Enumeration getAttributeNames() Returns a Java Enumeration of String objects containing the names of all the objects in this session.
long getCreationTime() Returns the time when this session was created (measured in milliseconds since midnight January 1, 1970
GMT).
java.lang.String getId() Returns a string containing the identifier for this session.
long getLastAccessedTime() Returns the last time the client sent a request in with this session, as the number of milliseconds since
midnight January 1, 1970 GMT.
int getMaxInactiveInterval() Returns the maximum time, in seconds, which the server will keep this session open between client
accesses.
ServletContext getServletContext() Returns the ServletContext to which this session belongs.
HttpSessionContext getSessionContext() As of servlet specification version 2.1, this method is deprecated.
java.lang.Object getValue(java.lang.String Deprecated. As of servlet specification version 2.2, this method is replaced by getAttribute(java.lang.String).
name)
java.lang.String[] getValueNames() Deprecated. As of servlet specification version 2.2, this method is replaced by getAttributeNames().
void invalidate() Invalidates this session.
boolean isNew() Returns true if the client does not yet know about the session.
void putValue(java.lang.String name, Deprecated. As of servlet specification version 2.2, this method is replaced by setAttribute(java.lang.String,
java.lang.Object value) java.lang.Object).
void removeAttribute(java.lang.String Removes the object with the specified name from this session.
name)
void removeValue(java.lang.String name) As of servlet specification version 2.2, this method is replaced by removeAttribute(java.lang.String).
void setAttribute(java.lang.String name, Connects an object to this session, using the given name.
java.lang.Object value)
Creating a Session - Example
<%@page import = "java.util.*" session="true"%>
<HTML> <HEAD>
<TITLE>Using Sessions to Track Users</TITLE>
</HEAD>
<BODY>
<%
Integer counter =
(Integer)session.getAttribute("counter");
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}

session.setAttribute("counter", counter);
%>
<H1>Using Sessions to Track Users</H1>
Session ID: <%=session.getId()%>
<BR>
Session creation time: <%=new Date(session.getCreationTime())%>
<BR>
Last accessed time: <%=new Date(session.getLastAccessedTime())%>
<BR>
Number of times you've been here: <%=counter%>
</BODY> </HTML>
Session Example
<%@ page import="java.util.*" %>
<%-- Comment session.setAttribute("tuserid" , request.getParameter("txtuserid")); --%>
<%
session.setAttribute("tuserid", "aggrk_mhl") ;
out.println("Session(tuserid) :" + session.getAttribute("tuserid") ) ;
out.println("Testing Session : " + "<H2>Information on Your Session:</H2>");
out.println( "<TABLE BORDER=1 ALIGN=CENTER>" );
out.println( "<TR>" + "<TH>Info Type<TH>Value" );
out.println( "<TR>" );
out.println( " <TD>ID" );
out.println( " <TD>" + session.getId() + "" );
out.println( "<TR>" );
out.println( " <TD>Creation Time" );
out.println( " <TD>" + new Date(session.getCreationTime()) + "" );
out.println( "<TR>" );
out.println( " <TD>Creation Time" );
out.println( " <TD>" + session.getCreationTime() + "" );
out.println( "<TR>" );
out.println( " <TD>Time of Last Access" ) ;
out.println( " <TD>" + new Date(session.getLastAccessedTime()) + " " ) ;
out.println( "<TR>" ) ;
out.println( "</TABLE>" );
out.println( "</BODY>" ); %>
Setting Session Timeouts
 You can use methods of the session object to set the maximum
time between page accesses before the server ends the
session:
 getMaxInactiveInterval()—Returns the maximum time
interval, in seconds, for which the server will keep this
session open between accesses.
 setMaxInactiveInterval(int interval)—Specifies the time, in
seconds, between user requests before the servlet container
will invalidate this session.
 If you set the lifetime of a session to -1, the session will never
expire.
 The default timeout between user accesses for sessions in
Tomcat is 30 minutes.
 You can change this in Tomcat's web.xml file (stored as jakarta-
tomcat-4.0.3\conf\web.xml). All you have to do is change the
time stored in the <session-timeout> element:
Setting Session Timeouts - Example

<!-- ==================== Default Session Configuration =================


-->

<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->

<session-config>
<session-timeout>30</session-timeout>
</session-config>
Application Object
Using Applications
 A session enables you to track one user at a time—an
application enables you to track all JSPs in the same site, no
matter how many users are using them.
 To access the current application, you can use the built-in
JSP application object.
 Like the session object, the application object is based on the
javax.servlet.http.HttpSession interface.
 In the previous example, you saw how to create a session
attribute named counter, which stores the number of times
the user has visited the page in the current session.
 In the same way, you can create an application attribute
named applicationCounter that holds the total number of
times anyone in the same application has viewed a JSP page.
Using Applications - Example
<HTML> <HEAD> <TITLE>Using the Application Object</TITLE> </HEAD> <BODY>
<H1>Using the Application Object</H1>
<%
Integer counter = (Integer)session.getAttribute("counter");
String heading = null;
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}
session.setAttribute("counter", counter);

Integer applicationCounter = (Integer)application.getAttribute("applicationCounter");


if (applicationCounter == null) {
applicationCounter = new Integer(1);
} else {
applicationCounter = new Integer(applicationCounter.intValue() + 1);
}

application.setAttribute("applicationCounter", applicationCounter);
%>

You have visited this page <%=counter%> times. <BR>


This page has been visited by all users <%=applicationCounter%> times.
</BODY> </HTML>
Sessions, Applications, and
JavaBeans
Using Sessions, Applications, and JavaBeans

 It turns out that you can instruct Tomcat to save JavaBeans


in a session object as well as in attributes.
 In fact, you can store JavaBeans in applications as well.
 You do this with the <jsp:useBean> element's scope
attribute, which you can set to one of these values:
scope="page |request|session|application".
 The term scope indicates where a data item is "visible"
(meaning it may be referred to by name) in your code.
 The default scope for a bean is page scope, which means the
bean exists only for the page scope.
 However, if you set the scope of a bean to session, it is
stored with the rest of the session's data.
Bean
A Bean That Maintains a Usage Counter (ch07_07.jsp)

package beans;
public class ch07_07
{
private int counter = 0;

public void setCounter(int value)


{
this.counter = value;
}

public int getCounter()


{
return this.counter;
}
public ch07_07()
{
}
}
Using Page Scope for Beans (ch07_08.jsp)
<HTML>
<HEAD>
<TITLE>Using Beans and Page Scope</TITLE>
</HEAD>

<BODY>
<H1>Using Beans and Page Scope</H1>

<jsp:useBean id="bean1" class="beans.ch07_07" scope="page" />

<%
bean1.setCounter(bean1.getCounter() + 1);
%>
The counter value is: <jsp:getProperty name="bean1"
property="counter" />
</BODY>
</HTML>
Using Session Scope for Beans (ch07_09.jsp)
<HTML>
<HEAD>
<TITLE>Using Beans and Session Scope</TITLE>
</HEAD>

<BODY>
<H1>Using Beans and Session Scope</H1>

<jsp:useBean id="bean1" class="beans.ch07_07" scope="session" />

<%
bean1.setCounter(bean1.getCounter() + 1);
%>
The counter value is: <jsp:getProperty name="bean1"
property="counter" />
</BODY>
</HTML>
Q&A
Q. Are there any drawbacks to using sessions?
Ans. Yes, they put a considerable strain on the resources of the
server if there are many sessions running at the same
time. They can also be broken unexpectedly if the user's
connection fails. All in all, in professional JSP applications,
you must be prepared for cases when using a session with
the user doesn't work.
Q. Can I store other data in cookies besides the cookie's
name, maximum age, and value?
ANS. Yes, you can also use the Cookie object's setComment
and getComment methods to store a comment—a String
object—in the cookie. This comment can explain the
purpose of the cookie, for example.

Você também pode gostar