JSP & Coookies
- Information can be shared between web pages in serveral ways
- directly with parameters that are passed between the pages
- indirectly via objects stored in the session memory of the web
server
- this goes away when the user exits the browser
- indirectly via objects stored in "cookies" on the client machine
- this can stay for up to 3 years on the client mache
- What a cookie is:
- a cookie is a name/value pair that is stored by the browser on
the client machine
- a web application (jsp) on the server creates the cookie and
sends it to the browser, the browser saves the cookie and returns it
whenever the web application asks for it.
- cookies can be given an expiration date (up to three years)
- users must enable cookies in their browser in order for them to
work.
- browsers usually accept 20-50 cookies per site
- names and values are limited to 4095 bytes (therefore you
could use one cookie to hold muplitple pieces of information with a
delimiter character in between)
- To create a Cookie
- first, create an instance of the Cookie class
- then set its maximum age (in seconds)
- set its domain/path
- optionally set it as a "secure" cookie, one that is sent over
an encrypted connection (note for this to work your project must be setup to use secure connections)
- then ask the response object to tell the browser to add the
cookie
- Example:
//
// cookie
stuff
//
static final
int COOKIELIFE = 60*60*24*30; // 30 days
static final
String COOKIEPATH =
"/RegistrarDatabaseDemo/";
// make availabe to the entire project
static final
String IDCOOKIE =
"studentIDCookie";
// id name
...
Cookie
idCookie = new Cookie(IDCOOKIE,id); // name, value, both strings
idCookie.setMaxAge(COOKIELIFE); // 30 days
idCookie.setPath(COOKIEPATH);
idCookie.setSecure(false); // no secure communication
response.addCookie(idCookie); // tell browser to add the cookie
- To retrieve cookie values
- ask the request object to obtain a list of cookies (array)
- this will return the cookies for your domain only
- check the value to be sure it is not null (null indicates there
were no cookies)
- Example:
Cookie[] cookies =
request.getCookies();
if(cookies != null) // were there
any cookies?
{
// process cookies
}
else
{
// no cookies
}
- cookies[i].getName() returns the cookie name
- cookies[i].getValue() returns the cookie value
- To delete the cookies,
- first get all the cookies
- set the max age to 0
- then tell the browser to store the cookies
- they will then immediately expire and be delete by the broweser
Cookie[] cookies = request.getCookies();
for(int i = 0; i < cookies.length;
i++)
{
cookies[i].setMaxAge(0); //
set the age to zero
cookies[i].setPath(COOKIEPATH);
cookies[i].setSecure(false);
response.addCookie(cookies[i]); //
re-add the cookie with a zero age
}
- Common uses for cookies
- store login information, this allows the user to login once
then not have to login again
- customize pages,
- focus advertising.
- Cookies can also be accessed in JavaScript, see
Example: Use cookies to store names and user ids
loginFormWithCookies.jsp (replaces
login.html)
<%@page contentType="text/html"
pageEncoding="UTF-8"%>
<jsp:useBean
id="student" class="registrarbeans.Student" scope="session" />
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP
Page</title>
</head>
<body>
<body>
<%
String idvalue = "";
if(student.isLoggedIn()) //
already logged in?
{
out.println("Hello "+student.getFirstName()+"
"+student.getLastName()+"<br/>");
return;
}
else
{
student.loadCookieData(request); // no, but try to load the user
data from the cookies
idvalue=student.getId();
}
%>
<form name="login"
action="loginWithCookies.jsp" method="post" ><br/>
ID <input
type="text" name="id" size="15" value ="<%= idvalue %>"/><br/>
Password <input
type="password" name="password" size="15" /><br/>
<input type
="submit" value="login" /><input type="reset" value="clear"
/><br/>
</form>
</body>
</html>
loginWithCookies.jsp (replaces
login.jsp)
<%@page contentType="text/html"
pageEncoding="UTF-8"%>
<%@page errorPage = "errorPage.jsp" %>
<jsp:useBean id="student" class="registrarbeans.Student"
scope="session" />
<jsp:setProperty name="student" property="*" />
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<%
session.setMaxInactiveInterval(1800); // 30 minute time out
student.login("jdbc:sqlserver://rubble.student.ad.fgcu.edu:1433;databaseName=sp12ism3232x;user=s12ISM3232;password=s12ISM3232;");
if(student.isLoggedIn())
{
out.println("Hello "+student.getFirstName()+"
"+student.getLastName()+"<br/>");
student.addCookies(response); //
add cookies for this student
}
else
out.println("Invalid login<br />");
out.println("<a
href='checkLogin.jsp'>check</A>");
%>
<%@include file="footer.jsp" %>
</body>
</html>
Cookie code from Student.java
//
// cookie stuff
//
static final
int COOKIELIFE = 60*60*24*30; // 30 days
static final
String COOKIEPATH = "/RegistrarDatabaseDemo"; // make availabe to the entire project
static final
String IDCOOKIE = "studentIDCookie";
static final
String FIRSTNAMECOOKIE = "studentFirstNameCookie";
static final
String LASTNAMECOOKIE = "studentLastNameCookie";
public void
addCookies(HttpServletResponse response)
{
//
//
create and add cookies for the id, first, and last names
// each
cookie is to expire in 30 days
//
Cookie idCookie = new Cookie(IDCOOKIE,id);
idCookie.setMaxAge(COOKIELIFE); // 30 days
idCookie.setPath(COOKIEPATH);
idCookie.setSecure(false);
response.addCookie(idCookie);
Cookie firstNameCookie = new Cookie(FIRSTNAMECOOKIE,firstName);
firstNameCookie.setMaxAge(COOKIELIFE); // 30 days
firstNameCookie.setPath(COOKIEPATH);
firstNameCookie.setSecure(false);
response.addCookie(firstNameCookie);
Cookie lastNameCookie = new Cookie(LASTNAMECOOKIE,lastName);
lastNameCookie.setMaxAge(COOKIELIFE); // 30 days
lastNameCookie.setPath(COOKIEPATH);
lastNameCookie.setSecure(false);
response.addCookie(lastNameCookie);
}
public void
deleteCookies(HttpServletRequest request,HttpServletResponse response)
{
Cookie[] cookies = request.getCookies();
for(int i = 0; i < cookies.length; i++)
{
cookies[i].setMaxAge(0); // set the age to zero
cookies[i].setPath(COOKIEPATH);
cookies[i].setSecure(false);
response.addCookie(cookies[i]); // re-add the cookie with a zero age
}
}
public void
loadCookieData(HttpServletRequest request)
{
Cookie[] cookies = request.getCookies();
if(cookies == null) // no cookies
return;
for(int i = 0; i < cookies.length; i++)
{
if(cookies[i].getName().equals(IDCOOKIE))
id = cookies[i].getValue();
if(cookies[i].getName().equals(FIRSTNAMECOOKIE))
firstName = cookies[i].getValue();
if(cookies[i].getName().equals(LASTNAMECOOKIE))
lastName = cookies[i].getValue();
}
}