Escolar Documentos
Profissional Documentos
Cultura Documentos
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:
<BODY>
<H1>Setting a Cookie</H1>
<%
Cookie cookie1 = new Cookie("message", "Hello!");
cookie1.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
%>
</form>
</body> </html>
setcookie.jsp
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
If (username==null) username="";
<%
Cookie[] cookies = request.getCookies();
<HTML> <HEAD>
<TITLE>Setting and Reading Cookies</TITLE>
</HEAD> <BODY
<%
Cookie[] cookies = request.getCookies();
boolean foundCookie = false;
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
<!-- 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);
application.setAttribute("applicationCounter", applicationCounter);
%>
package beans;
public class ch07_07
{
private int counter = 0;
<BODY>
<H1>Using Beans and Page Scope</H1>
<%
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>
<%
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.