Professional Documents
Culture Documents
Overview of Servlet Cookies
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:
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:
[]()=,"/?@:;
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.
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);
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.
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:
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.
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.
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.
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
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
<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>
<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>
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
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.
<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.
<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?
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!
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!".
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:
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: