You are on page 1of 25

1 a) Explain life cycle of a servlet

Let us first discuss what is a servlet.

1. What is Servlet?
A servlet is a Java technology-based Web component, managed by a container called servlet
container or servlet engine, that generates dynamic content and interacts with web clients via a
request\/response paradigm.
2. What is servlet container?
The servlet container is a part of a Web server or application server that provides the network
services over which requests and responses are sent, decodes MIME-based requests, and
formats MIME-based responses. A servlet container also contains and manages servlets
through their lifecycle.
3.Difference between GET and POST
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query
length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a
cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of
data to the server to be processed, more versatile, most secure
1. Servlets are normal Java classes which are created when needed and destroyed when not
needed. Since Servlets run within a Servlet Container, creation and destruction of
Servlets is the duty of Servlet Container and not yours.
2. Implementing the init() and destory() methods of Servlet interface allows you to be
told by the Servlet Container that when it has created an instance of your Servlet and
when it has destroyed that instance.
3. An important point to remember is that your Servlet is not created and destroyed for
every request it receives, rather it is created and kept in memory where requests are
forwarded to it and your Servlet then generates response

Servlet Initialization (init())


So you have created your Servlet class by extending the HttpServlet class and have placed it in
/WEB-INF/classes/ directory of your application.

Now when will Servlet Container create an instance of your Servlet? there are two situations :

 When you have specifically told the Servlet Container to preload your Servlet when the
Servlet Container starts by setting the load-on-startup tag to a non-zero value e.g.
 <web-app>

 <servlet>
 <servlet-name>test</servlet-name>
 <servlet-class>com.wordpress.sharat.servlets.TestServlet</servlet-
class>
 <load-on-startup>1</load-on-startup>
 </servlet>

</web-app>

So when the Servlet Container starts it will preload your Servlet in the memory.

 If your Servlet is not already loaded, it’s instance will be created as soon as a request is
received for it by the Servlet Container.
 During the loading of the Servlet into the memory, Servlet Container will call your
Servlet’s init() method.
 Since init() is going to be called only once you can put Servlet initialization code in it
like getting hold of a database connection or whatever.

Responding to Requests(service())

1. Once your Servlet is initialized and it’s init() method called, any request that the
Servlet Container receives will be forwarded to your Servlet’s service() method.
2. HttpServlet class breakes this service() method into more useful doGet(),
doPost(), doDelete(), doOptions(), doPut() and doTrace() methods depending
on the type of HTTP request it receives.
3. So in order to generate respose you should override the doGet() or doPost() method as
required.
4. At this moment all the requests will be forwarded to the appropriate doGet() or
doPost() or whatever method as required. No new instance will be created for your
Servlet.

Servlet Destruction(destory())

When your application is stopped or Servlet Container shuts down, your Servlet’s destroy()
method will be called. This allows you to free any resources you may have got hold of in your
Servlet’s init() method.

Always Remember

 init() and destroy() methods will be called only once during the life time of your
Servlet
  while service() and it’s broken down methods ( doGet(), doPost() etc ) will be
called as many times as requests are received for them by the Servlet Container
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.
1

A What is the use of session tracking?

What is session?
The session is an object used by a servlet to track a user's interaction with a Web application
across multiple HTTP requests.
Session Tracking is one of the most powerful features of
Servlets and JSP. Basically, the servlet engine takes care
of using Cookies in the right way to preserve state across
successive requests by the same user. Your servlet just
needs to call a single method (getSession) and it has
access to a persistent hashtable of data that's unique to
the current user

public void doPost(HttpServletRequest request,


HttpServletResponse response){
...
//lets take the session obj
HttpSession session = request.getSession(true);
//now let us take the user name assosiated with this session
String currUserLogin = (String) session.getAttribute
("currentUserLogin")
...
//now we do the work according to the user name
doSomeWork(currUserLogin);
...

Session Tracking
Session tracking is a mechanism that servlets use to maintain state about a series of requests from
the same user (that is, requests originating from the same browser) across some period of time.

Sessions are shared among the servlets accessed by a client. This is convenient for applications
made up of multiple servlets. For example, Duke's Bookstore uses session tracking to keep track
of the books being ordered by a user. All the servlets in the example have access to the user's
session.

To use session tracking,

 Obtain a session (an HttpSession object) for a user.


 
 Store or get data from the HttpSession object.
 
 Invalidate the session (optional).
 

Obtaining a Session

The getSession method of the HttpServletRequest object returns a user's session. When you
call the method with its create argument as true, the implementation creates a session if
necessary.

To properly maintain the session, you must call getSession before any output is written to the
response. (If you respond using a Writer, then you must call getSession before accessing the
Writer, not just before sending any response data.)

The Duke's Bookstore example uses session tracking to keep track of the books in the user's
shopping cart. Here is an example of the CatalogServlet obtaining a session for a user:

public class CatalogServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Get the user's session and shopping cart
HttpSession session = request.getSession(true);
...
out = response.getWriter();
...
}
}

Storing and Getting Data from a Session

The HttpSession interface provides methods that store and return:


 :

 Standard session properties, such as a session identifier


 
 Application data, which is stored as a name-value pair, where the name is a
String and the value is an object in the Java programming language. (This is like
java.util.Dictionary.) Because multiple servlets have access to a user's
session, you should adopt a naming convention for organizing the names
associated with application data. This avoids servlets accidentally overwriting
each other's values in the session. One such convention is servletname.name
where servletname is the full name of the servlet, including its packages. For
example, com.acme.WidgetServlet.state is a cookie with the servletname
com.acme.WidgetServlet and the name state.

The Duke's Bookstore example uses session tracking to keep track of the books in the user's
shopping cart. Here is an example of the CatalogServlet getting a user's session identifier, and
getting and setting the application data associated with the user's session:

public class CatalogServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Get the user's session and shopping cart
HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getValue(session.getId());

// If the user has no cart, create a new one


if (cart == null) {
cart = new ShoppingCart();
session.putValue(session.getId(), cart);
}
...
}
}

Because an object can be associated with a session, the Duke's Bookstore example keeps track
of the books that a user has ordered within an object. The object is type ShoppingCart and each
book that a user orders is stored in the shopping cart as a ShoppingCartItem object. For
example, the following comes from further down in the doGet method of the CatalogServlet:

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());
...
// Check for pending adds to the shopping cart
String bookId = request.getParameter("Buy");

//If the user wants to add a book, add it and print the result
String bookToAdd = request.getParameter("Buy");
if (bookToAdd != null) {
BookDetails book = database.getBookDetails(bookToAdd);

cart.add(bookToAdd, book);
out.println("<p><h3>" + ...);
}
}
Finally, note that a session can be designated as new. A new session causes the isNew method of
the HttpSession class to return true, indicating that, for example, the client does not yet know
about the session. A new session has no associated data.

You must deal with situations involving new sessions. In the Duke's Bookstore example above,
if the user has no shopping cart (the only data associated with a session), the servlet creates a
new one. Alternatively, if you need information from the user to start a session (such as a user-
name), you might want to redirect the user to an "starting page" where you collect the necessary
information.
 

Invalidating the Session

A user's session can be invalidated manually or, depending on where the servlet is running,
automatically. (For example, the Java Web Server automatically invalidates a session when there
have been no page requests in some period of time, 30 minutes by default.) To invalidate a
session means to remove the HttpSession object and its values from the system.

To manually invalidate a session, use the session's invalidate method. Some applications have
a natural point at which to invalidate the session. The Duke's Bookstore example invalidates a
user's session after the user has bought the books. This happens in the ReceiptServlet:

public class ReceiptServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

...
scart = (ShoppingCart)session.getValue(session.getId());
...
// Clear out shopping cart by invalidating the session
session.invalidate();

// set content type header before accessing the Writer


response.setContentType("text/html");
out = response.getWriter();
...
}
}

Handling All Browsers

By default, session tracking uses cookies to associate a session identifier with a user. To also
support users that access a servlet with a browser that does not support cookies, or that is set up
to reject cookies, you must use URL rewriting instead. (While some web servers support URL
rewriting, the servletrunner utility does not. For session tracking to work when a servlet is
running within servletrunner, the user agent must support cookies.)

When you use URL rewriting you call methods that, when necessary, include the session ID in a
link. You must call these methods for every link in the servlet response.

The method that associates a session ID with a URL is HttpServletResponse.encodeUrl. If


you redirect the user to another page, the method to associate the session ID with the redirected
URL is called HttpServletResponse.encodeRedirectUrl.

The encodeUrl and encodeRedirectUrl methods decide whether the URL needs to be
rewritten, and return the URL either changed or unchanged. (The rules for URLs and redirected
URLS differ, but in general if the server detects that the browser supports cookies, then the URL
is not rewritten.)

The Duke's Bookstore example uses URL rewriting for all of the links that it returns to its users.
For example, the CatalogServlet returns the catalog with two links for each book. One link
offers details about the book and the other allows you to add the book to your shopping cart.
Both URLs are rewritten:

public class CatalogServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Get the user's session and shopping cart, the Writer, etc.
...
// then write the data of the response
out.println("<html>" + ...);
...
// Get the catalog and send it, nicely formatted
BookDetails[] books = database.getBooksSortedByTitle();
...
for(int i=0; i < numBooks; i++) {
...
//Print out info on each book in its own two rows
out.println("<tr>" + ...

"<a href=\"" +
response.encodeUrl("/servlet/bookdetails?bookId=" +
bookId) +
"\"> <strong>" + books[i].getTitle() +
"  </strong></a></td>" + ...

"<a href=\"" +
response.encodeUrl("/servlet/catalog?Buy=" + bookId)
+ "\">   Add to Cart  </a></td></tr>" +

}
}
}
If the user clicks on a link with a rewritten URL, the servlet recognizes and extracts the session
ID. Then the getSession method uses the session ID to get the user's HttpSession object.

On the other hand, if the user's browser does not support cookies and the user clicks on an un-
rewritten URL, the user's session is lost. The servlet contacted through that link creates a new
session, but the new session does not have the data associated with the previous session. Once a
servlet loses the session data, the data is lost for all servlets that share the session. You should
consistently use URL rewriting if your servlet is to support clients that do not support or accept
cookies.

Question: What is a Session?


Answer: A Session refers to all the request that a single client makes to a server. A session is
specific to the user and for each user a new session is created to track all the request from that
user. Every user has a separate session and separate session variable is associated with that
session. In case of web applications the default time-out value for session variable is 20
minutes, which can be changed as per the requirement.
Question: What is Session ID?
Answer: A session ID is an unique identification string usually a long, random and alpha-
numeric string, that is transmitted between the client and the server. Session IDs are usually
stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. 
Question: What is Session Tracking?
Answer: HTTP is stateless protocol and it does not maintain the client state. But there exist a
mechanism called "Session Tracking" which helps the servers to maintain the state to track the
series of requests from the same user across some period of time. 
Question: What  are different types of Session Tracking?
Answer: Mechanism for Session Tracking are:
               a) Cookies
               b) URL rewriting
               c) Hidden form fields
               d) SSL Sessions
Question: What is HTTPSession Class?
Answer: HttpSession Class provides a way to identify a user across across multiple request.
The servlet container uses HttpSession interface to create a session between an HTTP client
and an HTTP server. The session lives only for a specified time period, across more than one
connection or page request from the user. 
Question: Why do u use Session Tracking in HttpServlet?
Answer: In HttpServlet you can use Session Tracking to track the user state. Session is
required if you are developing shopping cart application or in any e-commerce application.
Question: What are the advantage of Cookies over URL rewriting?
Answer: Sessions tracking using Cookies are more secure and fast. Session tracking using
Cookies can also be used with other mechanism of Session Tracking like url rewriting.
Cookies are stored at client side so some clients may disable cookies so we may not sure that
the cookies may work or not. 
In url  rewriting requites large data transfer from and to the server. So, it leads to network
traffic and access may be become slow.
Question: What is session hijacking?
Answer: If you application is not very secure then it is possible to get the access of system
after acquiring or generating the authentication information. Session hijacking refers to the act
of taking control of a user session after successfully obtaining or generating an authentication
session ID. It involves an attacker using captured, brute forced or reverse-engineered session
IDs to get a control of a legitimate user's Web application session while that session is still in
progress.
Question: What is Session Migration?
Answer: Session Migration is a mechanism of moving the session from one server to another
in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.
Question: How to track a user session in Servlets?
Answer: The interface HttpSession can be used to track the session in the Servlet. Following
code can be used to create session object in the Servlet: HttpSession session =
req.getSession(true);
Question: How you can destroy the session in Servlet?
Answer: You can call invalidate() method on the session object to destroy the session. e.g.
session.invalidate()

How java servlets supports session tracking?

Explain about onclick and onload event handling using java script?

http://www.webdevelopersnotes.com/tutorials/javascript/index.php3

Explain various functions used in data Object

Explain cookies with an example servlet program

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 ServletExceptio
n, 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
4) a)Briefly explain the difference between Java beans and EJB?

b)Explain the type of EJBs?

1. JavaBeans may be visible or nonvisible at runtime.For


example, the visual GUI component may be a button,list
box,graphic or a chart.
An EJB is a nonvisual ,remote object.
2. JavaBeans are intended to be local to a single process
and are primarly intended to run on the client side.Although
one can develop server-side JavaBeans,it is far easier to
develop them using the EJB specification instead.
EJB's are remotely executable components or business
objects that can be deployed only on the server.
3. JavaBeans is a component technology to create generic
Java components that can be composed together into applets
and applications.
Even though EJB is a component technology,it neither
builds upon nor extends the original JavaBean specification.
4.JavaBeans have an external interface called the properties
interface, which allows a builder tool to interpret the
functionality of the bean.
EJBs have a dployement descriptor that describes its
functionality to an external builder tool or IDE
5.JavaBeans may have BeanInfo classes,property editors or
customizers
EJB's have no concept of BeanInfo classes,property
editors or customizers and provide no additional information
other than that described inthe deployment descriptor.
6. JavaBeans are not typed.
EJBs are of two types - session beans and entity beans.
7. No explicit support exists for transactions in javaBeans.

EJB's may be transactional and the EJB servers provide


transactional support.

8. Component bridges are available for JavaBeans.For ex: a


javabean can also be deployed as an Activex control.
An EJB cannot be deployed as an ActiveX control because
ActiveX controls are intended to run at the desktop and
EJB's are server side components.However CORBA-IIOP
compatibility via the EJB-to-CORBA mapping is defined by the
OMG.

Java Beans is intra-process component


where as EJB is an Inter-Process component

EJB is designed to work in distributed environment using rmi/iiop protocol where as JavaBean is
standalone and works only in the same JVM.

Implicit services are provided to EJb by the Container in which it si deployed according to EJB contract
but in JavaBean we need to code all these services
 

java bean is a client side programme.it will be having a interface.But ejb


is server side it may or may not be interface.

Javabean is a reusable component. Common type of GUI components like Swing button can be
quoted as an example.

EJB is also reusable component. But the difference is that the bean part of javabean is used
mostly at developement time whereas bean part of EJB starts off at runtime. Regular Javabean
runs in a JVM while the EJB bean runs under the control of EJB container(Server).

JavaBean define a model for creating general-purpose components that are typically used on the
client side. Those components may or may not contain a user interface.

EJBs define a server-side component fro creating highly specialized business logic components.
EJB components don't have GUI.
JavaBeans- are reuseable non-deployable components. They can't exist independently.EJB - are
deployable reuesable server side components. They can exist independently or in integration with other
components.

JavaBean :

1. Low-level approach for developing re-usable components for building different Java
applications (Applets stand-alone applications etc.).
2. Java Beans runs in a JVM just like other normal java class

EJB :

1. High-level approach to build Distributed java applications & its an Re-usable server-side
component

2. EJB runs under the control of EJB Container

the main difference is Ejb componenets are distributed which means develop once and run anywhere.

java beans are not distributed. which means the beans cannot be shared .

JAVA BEAN COMPONENTS ARE VISUAL COMPONENTS CAN CUSTOMISED THROUGH THROUGH EVENTS
AND PROPERTIES EJBS USED FOR MULTIUSER DISTRIBUTED TRANSACTIONAL SERVICES AND PROCESSES
NOT VISIBLE BY USER.

The main difference:


Javabean is a reusable s/w component that can be developed & run within a single system.
EJB is used in distributed environment. EJB is developed in one node made to run in any system.

Explain the cookies with and example servlet code?

Cookie: The most common meaning of "Cookie" on the Internet refers to a piece of information sent by
a Web Server to a Web Browser that the Browser software is expected to save and to send back to the
Server whenever the browser makes additional requests from the Server. Depending on the type of
Cookie used, and the Browsers' settings, the Browser may accept or not accept the Cookie, and may
save the Cookie for either a short time or a long time. Cookies might contain information such as login or
registration information, online "shopping cart" information, user preferences, etc. When a Server
receives a request from a Browser that includes a Cookie, the Server is able to use the information
stored in the Cookie. For example, the Server might customize what is sent back to the user, or keep a
log of particular users' requests. Cookies are usually set to expire after a predetermined amount of time
and are usually saved in memory until the Browser software is closed down, at which time they may be
saved to disk if their "expire time" has not been reached. Cookies do not read your hard drive and send
your life story to the CIA, but they can be used to gather more information about a user than would be
possible without them. From Matisse

Cookies are used to keep information about a session.


Go to a web site and log in. The login information could be stored into a cookie, so you won't have to log
in twice.

When you surf the Internet, websites you visit collect and record usage information about your
computer such as your IP address, browser type, operating system you are using, web pages last visited,
etc. This information automatically comes from your browser to identify you and track your browsing
habits and activities.
As you surf the web, most web sites send cookies to your computer to track your Internet usage. Most
cookies are "good" cookies, used for legitimate purposes, such as storing preferences, account
information and remembering the choices you have made on the site. But some cookies are "bad". For
example, cookies from one site might track your visits to different web sites to know your browsing
habits, purchase history, etc.
This article provides general information about computer cookies:

What are cookies?

A computer cookie is a piece of data which often includes an unique identifier, that is sent to your
browser from a web site you visit, stores as a file on your computer, identifies you as a unique user and
track your web usage. Computer cookies can do everything from monitoring your visit throughout web
sites, tracking how many times you've visited the site, how long you've been on the site, your log-in
information at a particular page to remembering important information about your computer.

How long cookies are stored on your PC


It depends on the type of cookies. There are two different types of computer cookies:
Session cookies
Session cookies ("non-persistent cookie") are cookies that only exist as long as your session on the web
site lasts and expires as soon as you leave the website. The primary purpose of session cookies is to help
with navigation, such as by indicating whether or not you've already visited a particular page and
retaining information about your preferences once you've visited a page. So session cookies are used to
facilitate your activities within that site.
Persistent cookies
The second type of cookies is "persistent cookies". Persistent cookies are stored on your computer in
order to recognize user and retain his/her personal preferences when he/she returns to a website. E.g.
because of persistent cookies a website remembers your name and password on protected login pages,
your email address appears by default when you open your Yahoo! or Hotmail email account, or your
personalized home page appears when you visit your favorite online merchant. Persistent cookies exist
beyond the life of your Internet session and may live for months or years. In most browsers, you can
adjust the length of time that persistent cookies are stored.
Problem
If anyone has access to your computer, he or she may use information stored in persistent cookies to
gather personal information about you.

What are cookies used for?


The primary purposes of cookies is to recognize user and retain his/her personal preferences when
he/she returns to a website. if you personalize Web pages, or register for products or services, a cookie
helps the Web page server to recall your specific information. This may be useful to simplify the process
of recording your personal information, such as billing addresses, shipping addresses, and so on. Cookies
allow websites to store user preferences and retrieval of this information for viewing customization of
movie listings, weather and other local information.

Cookies can do everything from monitoring your visit throughout web sites, tracking how many times
you've visited the site, how long you've been on the site, your log-in information at a particular page to
remembering important information about your computer. Cookies allow websites to track their visitors
so that they can know how many visitors have viewed the site, how many repeat visitors they have
received.

 How websites use cookies


Internet offers a wide variety of useful services such as free e-mail accounts, online forums, and e-
commerce sites. The use of cookies is essential for these sites. Without cookies, for example, the sites
would have no way to track the items that you placed into your virtual shopping cart as you browsed
about the site.
Session cookies are stored only until you close your browser. This type of cookie is mainly used to
remember choices that you make as you navigate through a web site.
Persistent cookies allow web sites to recognize you when you return to these sites. Persistent cookies
are used by websites to store your for preferences, maintain state information as you navigate different
pages on a website or return to the website later, for identifying purposes, demographic statistics and
also when you are shopping online ecommerce sites may use them to remember what you have in your
shopping basket.

 Can cookies be used maliciously?


In one of their malevolent forms, cookies from one web site might track your visits to a different web
site. For example, most of the ads that you see on web sites do not come from the site that you are
viewing, but from sites that provide ads to many sites. When the advertising site displays the ad, it can
send cookies on your computer. This lets the advertising company track your web usage over a range of
sites and profile your browsing habits.
 Cookies and privacy
Every time you visit a website, it will look for its cookie on your hard drive. It uses the information stored
within the cookie to know your name, your shopping preferences, etc.
Most browser offer advanced cookie management options that allows to accepte or reject cookies
depending on if they are first-part or third-party cookies and/or particular domain of the issuer. So you
have the ability to enable or disable cookies, or have your browser prompt you before accepting
cookies. But be careful as disabling cookies may prevent some websites from working correctly. There is
one very simple step for more privacy and to make sure that other sites are not collecting personal
information about you without your knowledge, choose to only allow cookies for the web site you are
visiting; block or limit cookies from a third-party.
Despite cookies are useful, they can also store such informattion as your name and password on
protected login pages, preferences, account information and choices you have made on the site. So,
even if you delete browser history, cookies like a map will show your surfing preferences, habits,
passwords, etc. So to protect your privacy, you should constatly delete cookies.
In Internet Explorer and MSN Explorer even if you delete cookies manually, cookies index.dat file stores
Internet surfing information. Cookies index.dat file can't be deleted manually as it is used by Windows
all the time.
Using Clear All History you cannot only delete cookies in Internet Explorer, MSN Explorer,Maxthon
(MyIE2), Firefox, AOL, Mozilla, Netscape and Opera but also delete cookies index.dat file. And the best
thing - you can do it automatically.
Important: But disabling cookies does not make you anonymous or prevent web sites from tracking your
browsing habits as websites you visit collect and record usage information about your computer such as
your IP address, browser type, operating system you are using, web pages last visited, etc. This
information automatically comes from your browser to identify you and track your browsing habits and
activities.

 What cookies can't do....


Can cookies "read" information from a hard drive?
No. Cookies are just harmless files. Cookies cannot look into information stored on your hard-drive. It is
technically impossible for cookies to read personal information. Cookies can only store data that is
provided by the server or generated by an explicit user action.

Can cookies be used to run programs and deliver viruses on your PC?
No. Cookies cannot be used to run programs or to deliver viruses to your computer
Explain the advantages of DHTML with java script with suitable
example
DHTML is NOT a language.

DHTML is a TERM describing the art of making dynamic and interactive web
pages.

DHTML combines HTML, JavaScript, the HTML DOM, and CSS.

What you should already know


Before you continue you should have a basic understanding of the following:

 HTML
 CSS
 JavaScript

DHTML is NOT a Language


DHTML stands for Dynamic HTML.

DHTML is NOT a language or a web standard.

To most people DHTML means the combination of HTML, JavaScript, DOM and CSS.
According to the World Wide Web Consortium (W3C):
"Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows
documents to be animated."

HTML
The W3C HTML 4 standard has rich support for dynamic content:

 HTML supports JavaScript


 HTML supports the Document Object Model (DOM)
 HTML supports HTML Events
 HTML supports Cascading Style Sheets (CSS)

DHTML is about using these features, to create dynamic and interactive web pages.

JavaScript
JavaScript is the most popular scripting language on the internet, and it works in all major browsers.

DHTML is about using JavaScript to control, access and manipulate HTML elements.

You can read more about JavaScript in the next chapter of this tutorial.

HTML DOM
The HTML DOM is a W3C standard. It describes the Document Object Model for HTML.

The HTML DOM defines a standard way for accessing and manipulating HTML documents.

DHTML is about using the DOM to access and manipulate HTML elements.

You can read more about the HTML DOM in a later chapter of this tutorial.

HTML Events
HTML events are a part of the HTML DOM.
DHTML is about creating web pages that reacts to (user)events.

You can read more about events in a later chapter of this tutorial.

CSS
CSS defines how to display HTML elements.

DHTML is about using JavaScript and the HTML DOM to change the style and positioning of HTML elements.

You can read more about CSS in a later chapter of this tutorial.

JavaScript Alone
In JavaScript, the statement: document.write(), is used to write output to a web page.

The following example uses JavaScript to display the current date and time on a page:

<html>
<body>

<script type="text/javascript">
document.write(Date());
</script>

</body>
</html>

Sun Jan 30 15:31:02 2011

JavaScript and the HTML DOM


A JavaScript can also be used to change the content or attributes of HTML elements.

To change the content of an HTML element:

document.getElementById(id).innerHTML=new HTML

To change the attribute of an HTML element:

document.getElementById(id).attribute=new value
JavaScript and HTML Events
A JavaScript can also be executed when an event occurs, like when a user clicks on an HTML element.

To execute code when a user clicks on an element, use the following event attribute:

onclick=JavaScript

JavaScript and CSS


A JavaScript can also change the style of HTML elements.

To change the style of an HTML element:

document.getElementById(id).style.property=new style

What is the HTML DOM?


The HTML DOM is:

 A Document Object Model for HTML


 A standard programming interface for HTML
 Platform- and language-independent
 A W3C standard

The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to access them.

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

Change an HTML Element


The following example changes the content of an h1 element:

Example

<html>
<body>

<h1 id="header">Old Header</h1>

<script type="text/javascript">
document.getElementById("header").innerHTML="New Header";
</script>

</body>
</html>

Example explained:

 The HTML document above contains an h1 element with id="header"


 We use the HTML DOM to get the element with id="header"
 A JavaScript changes the content (innerHTML) of that element

New Header

"Old Header" was changed to "New Header"

Change an HTML Attribute


The following example changes the src attibute of an img element:

Example

<html>
<body>

<img id="image" src="smiley.gif">

<script type="text/javascript">
document.getElementById("image").src="landscape.jpg";
</script>

</body>
</html>

Example explained:

 The HTML document above contains an img element with id="image"


 We use the HTML DOM to get the element with id="image"
 A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"
DHTML - HTML Events
HTML events can trigger actions in a browser.

HTML Events
Every element on an HTML page has 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

In the following example, the content of the h1 element will change when a user clicks on it:

Example

<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text</h1>
</body>
</html>

You can also add the script in the head section, and then call a function from the event handler:

Example

<html>
<head>
<script type="text/javascript">
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text</h1>
</body>
</html>

Compare and contrast DOM and SAX

You might also like