Professional Documents
Culture Documents
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
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
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
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.
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:
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:
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:
//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.
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:
...
scart = (ShoppingCart)session.getValue(session.getId());
...
// Clear out shopping cart by invalidating the session
session.invalidate();
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 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:
"<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.
Explain about onclick and onload event handling using java script?
http://www.webdevelopersnotes.com/tutorials/javascript/index.php3
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?
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
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
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.
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
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:
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.
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.
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.
HTML
CSS
JavaScript
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:
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>
document.getElementById(id).innerHTML=new HTML
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
document.getElementById(id).style.property=new style
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.
Example
<html>
<body>
<script type="text/javascript">
document.getElementById("header").innerHTML="New Header";
</script>
</body>
</html>
Example explained:
New Header
Example
<html>
<body>
<script type="text/javascript">
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
Example explained:
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>