Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Overview of Servlet Cookies

Cookies are small bits of textual information that a Web server sends to a browser and that
the browser returns unchanged when visiting the same Web site or domain later. By having
the server read information it sent the client previously, the site can provide visitors with a
number of conveniences:

 Identifying a user during an e-commerce session. Many on-line stores use a


"shopping cart" metaphor in which the user selects an item, adds it to his shopping
cart, then continues shopping. Since the HTTP connection is closed after each page is
sent, when the user selects a new item for his cart, how does the store know that he is
the same user that put the previous item in his cart? Cookies are a good way of
accomplishing this. In fact, this is so useful that servlets have an API specifically for
this, and servlet authors don't need to manipulate cookies directly to make use of it.
 Avoiding username and password. Many large sites require you to register in order
to use their services, but it is inconvenient to remember the username and password.
Cookies are a good alternative for low-security sites. When a user registers, a cookie
is sent with a unique user ID. When the client reconnects at a later date, the user ID is
returned, the server looks it up, determines it belongs to a registered user, and doesn't
require an explicit username and password.
 Customizing a site. Many "portal" sites let you customize the look of the main page.
They use cookies to remember what you wanted, so that you get that result initially
next time.

The Servlet Cookie API


To send cookies to the client, a servlet would create one or more cookies with the appropriate
names and values via new Cookie(name, value) (section 2.1), set any desired optional
attributes via cookie.setXxx (section 2.2), and add the cookies to the response headers via
response.addCookie(cookie) (section 2.3). To read incoming cookies, call
request.getCookies(), which returns an array of Cookie objects. In most cases, you loop down
this array until you find the one whose name (getName) matches the name you have in mind,
then call getValue on that Cookie to see the value associated with that name.

Creating Cookies

A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie
name and the cookie value. Neither the name nor the value should contain whitespace or any
of:
[]()=,"/?@:;

Reading and Specifying Cookie Attributes


Before adding the cookie to the outgoing headers, you can look up or set attributes of the
cookie. Here's a summary:
getComment/setComment
Gets/sets a comment associated with this cookie.
getName/setName
Gets/sets the name of the cookie. The name and the value are the two pieces you virtually
always care about. Since the getCookies method of HttpServletRequest returns an array of
Cookie objects, it is common to loop down this array until you have a particular name, then
check the value with getValue.
getValue/setValue
Gets/sets the value associated with the cookie. Again, the name and the value are the two
parts of a cookie that you almost always care about, although in a few cases a name is used as
a boolean flag, and its value is ignored (i.e the existence of the name means true).

Placing Cookies in the Response Headers


The cookie is added to the Set-Cookie response header by means of the addCookie method of
HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);

Reading Cookies from the Client


To send cookies to the client, you created a Cookie then used addCookie to send a Set-
Cookie HTTP response header. To read the cookies that come back from the client, you call
getCookies on the HttpServletRequest. This returns an array of Cookie objects corresponding
to the values that came in on the Cookie HTTP request header. Once you have this array, you
typically loop down it, calling getName on each Cookie until you find one matching the name
you have in mind. You then call getValue on the matching Cookie, doing some processing
specific to the resultant value.

How cookie is used in Servlet


The cookie class provides an easy way  for servlet to read, create, and manipulate HTTP-
style cookies, which allows  servlets to store small amount of data. Cookies are small bits of
textual information that a Web server sends to a browser and that the browser returns
unchanged when visiting the same Web site.
A servlet uses the getCookies() method of HTTPServletRequest to retrieve cookies as
request. The addCookie() method of HTTPServletResponse sends a new cookie to the
browser. You can set the age of cookie by setMaxAge() method.
Here is the code which  defines cookie and shows how to set the maximum age of
cookie.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UseCookies extends HttpServlet 

 public void doGet ( HttpServletRequest request,HttpServletResponse response )
throws ServletException, IOException 
{
  PrintWriter out;
  response.setContentType("text/html");
  out = response.getWriter();
  Cookie cookie = new Cookie("CName","Cookie Value");
  cookie.setMaxAge(100);
  response.addCookie(cookie);
  out.println("<HTML><HEAD><TITLE>");
  out.println(" Use of cookie in servlet");
  out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>");
  out.println(" <b>This is a Cookie example</b>");
  out.println("</BODY></HTML>");
  out.close(); 
}
}
In the above example, a servlet class UseCookies defines the cookie class. Here  the age of
cookie has been set as setMaxAge(100). If its value is set to 0, the cookie will delete
immediately. After the time provided been expired, cookie will automatically deleted.
Here is the output

Using Cookies with Java Servlets


Cookies are pieces of data that an HTTP client can be asked to associate with a web site or
subsection of a web site1. Whenever the client requests a page, it sends along with the request
any cookies that it was previously asked to associate with that web site and/or page. Cookies
are used for cases where we need to "maintain state" across HTTP requests. In the real world,
this typically means for the following purposes:

 to create a temporary session where the site in some way "remembers in the short
term" what the user was doing or had chosen between web page requests, e.g.
remembering who the user is logged in as at the moment, or what they've ordered
from an on-line "shopping cart";
 to remember low-security information more permanently: for example, to
remember a user's search results preferences or who they are logged in as on their
social bookmarking site;
 to compile user statistics, e.g. for advertising purposes or for improving the
functionality of a site.
The Session Tracking API
Using sessions in servlets is quite straightforward, and involves looking up the session object
associated with the current request, creating a new session object when necessary, looking up
information associated with a session, storing information in a session, and discarding
completed or abandoned sessions.

Looking up the HttpSession object associated with the current request.

This is done by calling the getSession method of HttpServletRequest. If this returns null,
you can create a new session, but this is so commonly done that there is an option to
automatically create a new session if there isn't one already. Just pass true to getSession.
Thus, your first step usually looks like this:
HttpSession session = request.getSession(true);

Looking up Information Associated with a Session.

HttpSession objects live on the server; they're just automatically associated with the
requester by a behind-the-scenes mechanism like cookies or URL-rewriting. These session
objects have a builtin data structure that let you store any number of keys and associated
values. We can use getValue("key") to look up a previously stored value.

Here's one representative example, assuming ShoppingCart is some class you've defined
yourself that stores information on items being purchased.
HttpSession session = request.getSession(true);
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);
}
In most cases, you have a specific attribute name in mind, and want to find the value (if any)
already associated with it. However, you can also discover all the attribute names in a given
session by calling getValueNames, which returns a String array.

Associating Information with a Session

As discussed in the previous section, you read information associated with a session by using
getValue (or getAttribute in version 2.2 of the servlet spec). To specify information, you use
putValue (or setAttribute in version 2.2), supplying a key and a value. Note that putValue
replaces any previous values. Sometimes that's what you want (as with the referringPage
entry in the example below), but other times you want to retrieve a previous value and
augment it (as with the previousItems entry below).
Here's an example:

HttpSession session = request.getSession(true);


session.putValue("referringPage", request.getHeader("Referer"));
ShoppingCart previousItems =
(ShoppingCart)session.getValue("previousItems");
if (previousItems == null) {
previousItems = new ShoppingCart(...);
}
String itemID = request.getParameter("itemID");
previousItems.addEntry(Catalog.getEntry(itemID));
// You still have to do putValue, not just modify the cart, since
// the cart may be new and thus not already stored in the session.
session.putValue("previousItems", previousItems);
Life cycle of Servlet
The life cycle of a servlet can be categorized into four parts:

1. Loading and Inatantiation: The servlet container loads the servlet during startup or
when the first request is made. The loading of the servlet depends on the attribute
<load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive
value then the servlet is load with loading of the container otherwise it load when the
first request comes for service. After loading of the servlet, the container creates the
instances of the servlet.
2. Initialization: After creating the instances, the servlet container calls the init()
method and passes the servlet initialization parameters to the init() method. The init()
must be called by the servlet container before the servlet can service any request. The
initialization parameters persist untill the servlet is destroyed. The init() method is
called only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the
servlet container unloads the servlet.
3. Servicing the Request: After successfully completing the initialization process, the
servlet will be available for service. Servlet creates seperate threads for each request.
The sevlet container calls the service() method for servicing any request. The
service() method determines the kind of request and calls the appropriate method
(doGet() or doPost()) for handling the request and sends response to the client using
the methods of the response object.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any request,
the servlet container calls the destroy() method . Like the init() method this method is
also called only once throughout the life cycle of the servlet. Calling the destroy()
method indicates to the servlet container not to sent the any request for service and the
servlet  releases all the resources associated with it. Java Virtual Machine claims for
the memory associated with the resources for garbage collection.

                  Life Cycle of a Servlet 


JSP page error handling
Error handling for JSP pages can be performed in various ways:

Error handling from within the page

For JSP pages that require more intricate error handling and recovery, a page can be written
to directly handle errors from the data bean. The JSP page can either catch exceptions thrown
by the data bean or it can check for error codes set within each data bean, depending on how
the data bean was activated. The JSP page can then take an appropriate recovery action based
on the error received.

Error JSP page at the page level

A JSP page can specify its own default error JSP page from an exception occurring within it
through the JSP error tag. This enables a JSP page to specify its own handling of an error. A
JSP page that does not contain a JSP error tag will have an error fall through to the
application-level error JSP page. In the page-level error JSP page, it must call the JSP helper
class (com.ibm.server.JSPHelper) to roll back the current transaction.

Error JSP page at the application level

An application can specify a default error JSP page when an exception from within any of its
servlets or JSP pages occurs. . In the application-level error JSP page, a call must be made to
the servlet helper class to roll back the current transaction. This is because the Web controller
will not be in the execution path to roll back the transaction. Whenever possible, you should
rely on the preceding two types of JSP error handling. Use the application-level error
handling strategy only when required.

JSP is very mature about handling errors. JSP use Exception handling classes for
dealing with error. Every program or code can throw an error; to rectify these errors should
know what real problem is. These error classes in JSP tell us what exact problem is where we
have to do modify in our code to remove error. This give us detail and deep information of
error, can be display on particular error page or put it in error object System.err.

JSP provide try catch block to hand run time exception. JSP have property in

<%@ page isErrorPage="true" %>


<%@ page language="java" errorPage="error.jsp" %>

try catch block is important feature to caught exception in JSP page, do according to
programmer specification.
Example of try catch Error Handling in JSP
tryCatch.jsp

<%@ page language="java" errorPage="" %>


<html>
<head>
<title>Error Handling by try catch block in JSP</title>
</head>

<body>
<%
try{
int a=0;
int b=10;
int c=b/a;
}
catch(Exception e)
{
e.printStackTrace(); /// This will give detail information of error occur
out.print("Error caught by Catch block is : "+e.getMessage());
}
%>
</body>
</html>

This will show


Error caught by Catch block is :/ by zero
java.lang.ArithmeticException: / by zero, a number can be division by zero digits; it is caught
by arithmeticException and prints this error.
e.printStackTrace(); give us detail error information and can see at tomcat console mode or at
logs folder in catalina.out file.
Sometimes error handling is useful when we are inserting user data into a registration table
with unique field of UserId. If we enter duplicate UserId, sqlException will throw a duplicate
row field error. User can know, this UserId is already exists in database.

JSP can use customized error page by setting errorPage="error.jsp".


Example of Error page in JSP
errorPage.jsp

<%@ page language="java" errorPage="" %>


<html>
<head>
<title>Error Handling by try catch block in JSP</title>
</head>

<body>
<%
try{
int a=0;
int b=10;
int c=b/a;
}
catch(Exception e)
{
e.printStackTrace(); /// This will give detail information of error occur
out.print("Error caught by Catch block is : "+e.getMessage());
}
%>
</body>
</html>

second page is error page

error.jsp

<html>
<head>
<title>Caught Error in JSP Page</title>
</head>

<body>
Error is found on this page(This is own customized error page)
</body>
</html>
JSP Cookies
In world wide web the protocol we use is a http protocol. The Http protocol is a stateless
protocol means that it can't keep a state i.e. it can't persist values. To maintain a session we
used the concept of cookies.

When cookie based session management is used, a token is generated which contains user's
information, is sent to the browser by the server. The cookie is sent back to the server when
the user sends a new request. By this cookie, the server is able to identify the user. In this
way the session is maintained. Cookie is nothing but a name- value pair, which is stored on
the client machine. By default the cookie is implemented in most of the browsers. If we
want then we can also disable the cookie. For security reasons, cookie based session
management uses two types of cookies.
1) Non- secure session cookie: This cookie can flow between the browser and server
under the SSL or non- SSL connection.
2) Secure authentication cookie: It is used to authenticate the data. This cookie flow
over SSL. This type of authenication cookie are used where the information security is
very important.
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 objects have the following methods.

Method Description

Returns the comment describing the purpose of this cookie,


getComment()
or null if no such comment has been defined.

getMaxAge() Returns the maximum specified age of the cookie.

getName() Returns the name of the cookie.

Returns the prefix of all URLs for which this cookie is


getPath()
targeted.
getValue() Returns the value of the cookie.

If a web browser presents this cookie to a user, the cookie's


setComment(String)
purpose will be described using this comment.

Sets the maximum age of the cookie. The cookie will


expire after that many seconds have passed. Negative
setMaxAge(int) values indicate the default behavior: the cookie is not stored
persistently, and will be deleted when the user web browser
exits. A zero value causes the cookie to be deleted

This cookie should be presented only with requests


setPath(String)
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, slashes, question marks,
setValue(String)
the "at" sign, colon, and semicolon) should be avoided.
Empty values may not behave the same way on all
browsers.

JSP Sessions
On a typical web site, a visitor might visit several pages and perform several interactions.

If you are programming the site, it is very helpful to be able to associate some data with each
visitor.  For this purpose, "session"s can be used in JSP.

A session is an object associated with a visitor.  Data can be put in the session and retrieved
from it, much like a Hashtable.  A different set of data is kept for each visitor to the site.

Here is a set of pages that put a user's name in the session, and display it elsewhere.  Try out
installing and using these.

First we have a form, let us call it GetName.html

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
The target of the form is "SaveName.jsp", which saves the user's name in the session.  Note
the variable  "session".  This is another variable that is normally made available in JSPs, just
like out and request variables.  (In the @page directive, you can indicate that you do not need
sessions, in which case the "session" variable will not be made available.)
<%
   String name = request.getParameter( "username" );
   session.setAttribute( "theName", name );
%>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
The SaveName.jsp saves the user's name in the session, and puts a link to another page,
NextPage.jsp.

NextPage.jsp shows how to retrieve the saved name.

<HTML>
<BODY>
Hello, <%= session.getAttribute( "theName" ) %>
</BODY>
</HTML>
If you bring up two different browsers (not different windows of the same browser), or run
two browsers from two different machines, you can put one name in one browser and another
name in another browser, and both names will be kept track of.

The session is kept around until a timeout period.  Then it is assumed the user is no longer
visiting the site, and the session is discarded.
JAVA SCRIPT
What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
 Everyone can use JavaScript without purchasing a license

What can a JavaScript do?

 JavaScript gives HTML designers a programming tool - HTML authors are


normally not programmers, but JavaScript is a scripting language with a very simple
syntax! Almost anyone can put small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: document.write("<h1>" + name + "</h1>") can write a variable text into an
HTML page
 JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
 JavaScript can read and write HTML elements - A JavaScript can read and change
the content of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
 JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer

Java script event handling


Different event handlers with with different HTML tags. For example, while "onclick" can be
inserted into most HTML tags to respond to that tag's onclick action, something like "onload"
(see below) only works inside the <body> and <img> tags. Below are some of the most
commonly used event handlers supported by JavaScript.

Event Handlers:

onclick:   Use this to invoke JavaScript upon clicking (a link, or form boxes)
Use this to invoke JavaScript after the page or an image has finished
onload:  
loading.
onmouseover:   Use this to invoke JavaScript if the mouse passes by some link
onmouseout:   Use this to invoke JavaScript if the mouse goes pass some link

onunload:   Use this to invoke JavaScript right after someone leaves this page.

Events

By using JavaScript, we have the ability to create dynamic web pages. Events are actions that
can be detected by JavaScript.

Every element on a web page has certain events which can trigger a JavaScript. For example,
we can use the onClick event of a button element to indicate that a function will run when a
user clicks on the button. We define the events in the HTML tags.

Examples of events:

 A mouse click
 A web page or an image loading
 Mousing over a hot spot on the web page
 Selecting an input field in an HTML form
 Submitting an HTML form
 A keystroke

Note: Events are normally used in combination with functions, and the function will not be
executed before the event occurs!

For a complete reference of the events recognized by JavaScript, go to our complete


JavaScript reference.

onLoad and onUnload

The onLoad and onUnload events are triggered when the user enters or leaves the page.

The onLoad event is often used to check the visitor's browser type and browser version, and
load the proper version of the web page based on the information.

Both the onLoad and onUnload events are also often used to deal with cookies that should be
set when a user enters or leaves a page. For example, you could have a popup asking for the
user's name upon his first arrival to your page. The name is then stored in a cookie. Next time
the visitor arrives at your page, you could have another popup saying something like:
"Welcome John Doe!".

onFocus, onBlur and onChange

The onFocus, onBlur and onChange events are often used in combination with validation of
form fields.
Below is an example of how to use the onChange event. The checkEmail() function will be
called whenever the user changes the content of the field:

<input type="text" size="30" id="email" onchange="checkEmail()">

onSubmit

The onSubmit event is used to validate ALL form fields before submitting it.

Below is an example of how to use the onSubmit event. The checkForm() function will be
called when the user clicks the submit button in the form. If the field values are not accepted,
the submit should be cancelled. The function checkForm() returns either true or false. If it
returns true the form will be submitted, otherwise the submit will be cancelled:

<form method="post" action="xxx.htm" onsubmit="return checkForm()">

onMouseOver and onMouseOut

onMouseOver and onMouseOut are often used to create "animated" buttons.

Below is an example of an onMouseOver event. An alert box appears when an onMouseOver


event is detected:

<a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return


false"><img src="w3s.gif" alt="W3Schools" /></a>

You might also like