Vous êtes sur la page 1sur 18

Web Technologies Q&A

Unit 4,5,6,7&8

1. What Is A Servlet ? Explain its advantages

Java Servlets are server side components that provides a powerful mechanism for
developing server side of web application. With Java servlets web developers can create
fast and efficient server side application and can run it on any Servlet enabled web server.
Servlets runs entirely inside the Java Virtual Machine

Platform Independence :Java Servlets are 100% pure Java, so it is platform independent.
It can run on any Servlet enabled web server. For example if you develop an web
application in windows machine running Java web server. You can easily run the same on
apache web server (if Apache Serve is installed) without modification or compilation of
code. Platform independency of servlets provides a great advantage over alternatives of
Performance: Due to interpreted nature of java, programs written in java are slow. But the
java servlets runs very fast. These are due to the way servlets run on web server. For
anyprogram initialization takes significant amount of time. But in case of servlets
initializationtakes place very first time it receives a request and remains in memory till
times out orserver shut downs. After servlet is loaded,

2. Explain Tomcat installation and configuration?

Obtaining Tomcat
You can download Tomcat from http://archive.apache.org/dist/jakarta/ as compressed
file(zip). You can use WinZip to decompress into c:\ compression/decompression utility
Installing Tomcat
Before running the servlet, you need to start the Tomcat servlet engine. To start Tomcat,
you have to first set the JAVA_HOME environment variable to the JDK home directory.
The JDK home directory is where your JDK is stored.
Testing Tomcat
By default, Tomcat runs on part 8080. To prove that Tomcat is running, type the URL
http://localhost:8080 from a Web browser.

Creating Servlet
import java.io.*;
import javax.servlet.*;
public class FirstServlet extends GenericServlet
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
PrintWriter pw= res.getWriter();
pw.println("<b> Welcome to My Servlets</B>");
Web Technologies Q&A

Compiling Servlets
servlet.jar contains the classes and interfaces to support servlets. Servlet package is not
bundled with JDK, any webserver software will have servlet package Tomcat has servlet
packages in a file called servlet.jar for lower versions of Tomcat 5 and higher versions
including Tomcat 5 contains servlet-api.jar
Suppose you have installed Tomcat 4.1 at C:\Program Files\Apache Group\Tomcat 1.4
To compile FirstServlet.java, you need to add to the classpath from DOS prompt as
set classpath=%classpath%; C:\Program Files\Apache Group\Tomcat
or you can also use following classpath at compailation time as
c:/>Javac FirstServlet.java classpath C:\Program Files\Apache Group\Tomcat
Copy the resultant .class file into C:\Program Files\Apache Group\Tomcat1.4\webapps
\examples \ WEB-INF\ classes, so it can be found at runtime.

Running Servlets
To run the servlet FirstServlet, start a Web browser and type
http://localhost:8080/examples/servlet/FirstServlet in the URL
NOTE: You can use the servlet from anywhere on the Internet if your Tomcat is running
on a host machine on the Internet. Suppose the host name is sicet.cse.edu, use the URL
http:// sicet.cse.edu:8080/examples/servlet/FirstServlet to test the servlet.

3. Explain servlet life cycle?

Servlet Interfaces and Servlet Life Cycle:

Architecturally, all servlets must implement the Servlet interfaces. This interface defines
five methods
void init(ServletConfig cnfig)
The Servlet container calls this method once during a servlets execution cycle to
initialize the Servlet. The ServletConfig argument is supplied by the Servlet
container that executes the Servlet.

ServletConfig getServletConfig()
This method returns a reference to an object that implements interface ServletConfig.
This object provides access to the servlets configuration information such as Servlet
initialization parameters and servlets ServletContext, which provides the Servlet e
with access to its environment.

String getServletInfo()
This method is defined by a servlet programmer to return a string containing Servlet
information such as the servlets author and version.
Web Technologies Q&A

void service(ServletRequest request, ServletResponse response)

The Servlet container calls this method to respond to a client request to the servlet.

void destroy()
This cleanup method is called when a Servlet is terminated by its Servlet container.
Resources used by the Servlet, such as open file or an open database connection,
should be deallocated here.

A Servlet life cycle begins when the Servlet container loads the Servlet into memory.
Now it is ready to respond the requests. Before the Servlet can handle that request, the
Servlet container invokes the servlets init method. After init completes execution, the
Servlet can respond to its first request. All requests are handled by a servlets service
method, which receives the request, process the request and sends a response to the
client. During a servlets life cycle, method service is called once per request. Each new
request typically results in a new thread of execution in which method service executes.
When Servlet container terminates the servlet, the servlets destroy method is called to
release servlet resources.

4. Explain servlet interfaces and classes used for developing servlets?

Servlet Interfaces:
Web Technologies Q&A

The servlet packages define two abstract classes that implement the interfaces Servlet-
class GenericServlet (from package javax.servlet) and class HttpServlet (from package
javax.servlet.http). These classes provide default implementations of all the servlet
HttpServlet Class:
Web based servlets typically extend class HttpServlet. Class HttpServlet overrides
method service() to distinguish between the typical requests received from a client web
browser. The two common HTTP request methods are get() and post(). A get() request
gets (or receives) information from a server. Common uses of get requests are to retrieve
an HTML document or an image. A post() request posts (or sends) data to a server.
Common uses of post requests typically sends information, such as authentication
information or data from a form that gathers user input, to server.
Class HttpServlet defines methods doGet and doPost to respond to get and post
requests from a client, respectively. These methods are called by method service, which is
called when a request arrives at the server.
HttpServletRequest Interface:
Every call to doGet or doPost for an HttpServlet receives an object that implements
interface HttpServletRequest. The Web server that executes the servlet creates an
HttpServletRequest object and passes this to the servlets service() method. A few key
methods are given below:

Styring getParameter(String name)

Obtain the value of a parameter sent to the servlet as part of a get or post request.
The name argument represents the parameter name.

Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a post request.

String[] getParameterValues(String name)

For a parameter with multiple values, this method returns an array of strings
containing the values for a specified servlet parameter.

Cookie[] getCookes()
Return an array of Cookie objects stored on the client by the server. Cookie objects
can be used to uniquely identify clients to the servlet.

HttpSession getSession(Boolean create)

Return an HttpSession Object associated with the clients current browsing session.
This method can create an HttpSession object if one does not already exist for the client.
HttpSession objects are used in similar ways to Cookies for uniquely identifying clients.

HttpServletResponse Interfce:
Every call to doGet or doPost for an HttpServlet receives an object that implements
interface HttpServletResponse. The Web server that executes the servlet creates an
HttpServletResponse object and passes this to the servlets service() method. A few key
methods are given below:
Web Technologies Q&A

void addCookie(Cookie cookie)

Used to add a Cookie to the header of the response to the client. The Cookies
maximum age and whether Cookies are enabled on the client determine if Cookies
are stored on the client.

ServletOutputStream getOutputStream()
Obtains a byte-based output stream for sending binary data to the client.

PrintWriter getWriter()
Obtains a character-based output stream for sending text data to the client

void setContentType(String type)

Specifies the MIME type of the response to the browser. The MIME type helps the
browser determine how to display the data. For example, MIME type text/html
indicates that the response is an HTML document, so the browser displays the
HTML page.

5 What is JSP? Explain its advantages over Servlets?

JavaServer Pages (JSP). JavaServer Pages are built on top of Java servlets and designed
to increase the efficiency in which programmers, and even nonprogrammers, can create
web content.

Instead of embedding HTML in the code, you place all static HTML in a JSP page, just as
in a regular web page, and add a few JSP elements to generate the dynamic parts of the
page. The request processing can remain the domain of the servlet, and the business logic
can be handled by JavaBeans and EJB components.

A JSP page is handled differently compared to a servlet by the web server. When a servlet
is deployed into a web server in compiled (bytecode) form, then a JSP page is deployed
in its original, human-readable form.

When a user requests the specific page, the web server compiles the page into a servlet
and from there on handles it as a standard servlet.

This accounts for a small delay, when a JSP page is first requested, but any subsequent
requests benefit from the same speed effects that are associated with servlets.

6. Explain JSP components?

In JSP elements can be divided into 4 different types. These are:

1. Expressions
We can use this tag to output any data on the generated page. These data are
Web Technologies Q&A

automatically converted to string and printed on the output stream.

Syntax of JSP Expressions are:
<%="Any thing" %>
JSP Expressions start with Syntax of JSP Scriptles are with <%= and ends with %>.
Between these this you can put anything and that will convert to the String and that will
be displayed.
Example: <%="Hello World!" %>
Above code will display 'Hello World!'

2. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine.

Syntax of JSP Scriptles are:

<% //java codes %>

JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code
in the JSP Scriptlets. JSP Engine places these code in the _jspService() method.
Variables available to the JSP Scriptlets are:

a. Request: Request represents the clients request and is a subclass of HttpServletRequest.

Use this variable to retrieve the data submitted along the request.
Example: <% //java codes
String userName=null;
userName=request.getParameter("userName"); >

b. Response: Response represents the server response and is a subclass of

<% response.setContentType("text/html"); %>

c. Session: represents the HTTP session object associated with the request.
Your Session ID: <%= session.getId() %>

d. Out: out is an object of output stream and is used to send any output to the client.

3. Directives
A JSP "directive" starts with <%@ characters. In the directives we can import packages,
define error handling pages or the session information of the JSP page.

Syntax of JSP directives is:

<%@directive attribute="value" %>

a. page: page is used to provide the information about it.

Example: <%@page language="java" %>

b. include: include is used to include a file in the JSP page.

Web Technologies Q&A

Example: <%@ include file="/header.jsp" %>

c. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to
defined our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>

Page tag attributes are:

a. language="java"
This tells the server that the page is using the java language. Current JSP
specification supports only java language.
Example: <%@page language="java" %>

b. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to
import more than one packages.
Example: <%@page language="java" import="java.sql.*" %>

c. session="true"
When this value is true session data is available to the JSP page otherwise not. By
default this value is true.
Example: <%@page language="java" session="true" %>

d. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: %@page session="true" errorPage="error.jsp" %

e. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page contentType="text/html;charset=ISO-8859-1" %>

7. Explain Model view controller used in JSP technology?

JSP technology can play a part in everything from the simplest web application to
complex enterprise applications. How large a part JSP plays differs in each case, of
course. Letintroduce a design model called Model-View-Controller (MVC), suitable for
both simple and complex applications.

MVC was first described by Xerox in a number of papers published in the late 1980s. The
key point of using MVC is to separate logic into three distinct units: the Model, the View,
and the Controller. In a server application, we commonly classify the parts of the
application as business logic, presentation, and request processing.

Business logic is the term used for the manipulation of an application's data, such as
customer, product, and order information. Presentation refers to how the application data
is displayed to the user, for example, position, font, and size. And finally, request
processing is what ties the business logic and presentation parts together.
Web Technologies Q&A

In MVC terms, presentation should be separated from the business logic. Presentation of
that data (the View) changes fairly often. Just look at all the face-lifts many web sites go
through to keep up with the latest fashion in web design. Some sites may want to present
the data in different languages or present different subsets of the data to internal and
external users

8. WHAT ARE EXCEPTIONS in JSP ? how they are handled?

Exceptions mean exceptional events and as we all know exceptional events can occur
anywhere in a program e.g. you are trying to connect to a database and the database
server is down, now you wouldn't have expected this to happen ;).

You can catch exceptions in a JSP page like you would do in other Java classes. Simply
put the code which can throw an exception/s between a try..catch block.
try {
// Code which can throw can exception
} catch(Exception e) {
// Exception handler code here
} %>

There is yet another useful way of catching exceptions in JSP pages. You can specify
error page in the 'page' directive. Then if any exception is thrown, the control will be
transferred to that error page where you can display a useful message to the user about
what happened .
Web Technologies Q&A

Demonstration error page:

To demonstrate the run-time exception handling feature of JSP pages, we will build three
Form.html - Display a Form to the user to enter his or her age.
FormHandler.jsp - A JSP Page which receives this value and prints it on the user
ExceptionHandler.jsp - An exception handler JSP page which is actually an error
page to which control will be passed when an exception is thrown.

i. Form.html
Create a new Form.html page. Copy the following code and paste it into the Form.html
page :
<head> <title> form.html</title> </head>
<form action="FormHandler.jsp" method="post">
Enter your lab marks :
<input type="text" name="marks" />
<input type="submit" value="Submit" />
Form.html page simply displays a single input field Form to the user to enter his age in
years. The name of input field where user will enter his/her internal marks is "marks". We
will use this input field name "marks" in the FormHandler.jsp page to receive it's value.

ii. FormHandler.jsp
Create new FormHandler.jsp page. Copy and paste the following code in it.
<%@ page errorPage="ExceptionHandler.jsp" %>
<title> errorpage </title>
int marks;
marks = Integer.parseInt(request.getParameter("marks"));
<%-- Displaying Student marks --%>
<p>Your have scored : <%= marks %> marks.</p>
<p><a href="Form.html">Back</a>.</p>
Web Technologies Q&A

Code above is rather simple. Notice the first line, the page directive. It specifies an
errorPage ExceptionHandler.jsp, our exception handler JSP page.

<%@ page errorPage="ExceptionHandler.jsp" %>

Then we declare an int variable "marks". Then using the static method of Integer class we
parse the entered value using Integer.parseInt() method. The value is retrieved using
request.getParameter() method. The argument to request.getParameter() is the name of
Form field whose value we want to retrieve.

int marks;
marks = Integer.parseInt(request.getParameter("marks"));

If all goes well and user entered an int ( e.g. 48 ) value in the input field then we display
that value back to the user.

<p>Your have scored : <%= marks %> marks.</p>

Now things can go wrong and exceptional events can occur. For example, if student
didn'tenter a value and what if student entered his marks as String type instead of an
integer ?.

These things will be handled by the ExceptionHandler.jsp JSP page.

iii. ExceptionHandler.jsp
Create a new ExceptionHandler.jsp page. Copy and paste the following Ex:

<%@ page isErrorPage="true" import="java.io.*" %>

<head><title>Exceptional Even Occurred!</title>
<%-- Exception Handler --%>
<font color="orange">
<%= exception.toString() %><br>
To make a JSP page exception handler ( i.e. errorPage ), you have to specify isErrorPage
attribute in the page directive at the top and set it's value to true.

<%@ page isErrorPage="true" %>

Web Technologies Q&A

When a JSP page has been declared an errorPage, it is made available an object with
name of "exception" of type java.lang.Throwable. We use different methods of this
exception object to display useful information to the user.

9. Explain various types of JSP Action tags?

JSP actions or action tags are the constructs that follows XML syntax. The behavior of
the servlet engine is controlled by these action. Using JSP actions, a file is inserted into
another page dynamically, reuse a bean component, or forward a user from one page to
another page. The following are the JSP action tags.

Important actions tags:

<jsp:include> Includes a file at the time the page is requested.

<jsp:useBean> - Finds or instantiates a Java Bean.
<jsp:setProperty> - Sets the property of a Java Bean.
<jsp:getProperty> - Inserts the property of a Java Bean into the output.
<jsp:forward> - Forwards the requests to a new page.
<jsp:plugin> - used to generate browser specific HTML to specify Java applets. This tag
is replaced by either an <object> or <embed> tag depending on what is more appropriate
for Client Browser.

a. <jsp:include> : Unlike the include directive, which inserts the file at the time the JSP
page is translated into a servlet, this action inserts the file at the time the page is

Attributes used : page and flush

Syntax : <jsp:include page="relative URL" flush="true" />

b. <jsp:forward> : The forward action terminates the action of the current page and
forwards the request to another resource such as a static page, another JSP page, or a Java

syntax of this action is as follows:

<jsp:forward page="Relative URL" />

Only one attribute is used : page

c. The useBean action is quite versatile. It first searches for an existing object utilizing the
id and scope variables. If an object is not found, it then tries to create the specified object.

The simplest way to load a bean is as follows:

<jsp:useBean id="name" class="package.class" />

Web Technologies Q&A

Attributes : class, type and bean Name.

This action tag uses two more action tags :

jsp:setProperty and jsp:getProperty

d. <jsp:setProperty> : The setProperty action sets the properties of a Bean. The Bean
must have been previously defined before this action. There are two basic ways to use the
setProperty action:

use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

<jsp:useBean id="myName" ... />


<jsp:setProperty name="myName" property="someProperty" .../>

e. <jsp:getProperty> : The getProperty action is used to retrieve the value of a given

property and converts it to a string, and finally inserts it into the output.

The getProperty action has only two attributes, both of which are required and
simple syntax is as follows:

<jsp:useBean id="myName" ... />


<jsp:getProperty name="myName" property="someProperty" .../>

f. <jsp:plugin> : The plugin action is used to insert Java components into a JSP page. It
determines the type of browser and inserts the <object> or <embed> tags as needed.

If the needed plugin is not present, it downloads the plugin and then executes the Java
component. The Java component can be either an Applet or a JavaBean.

10. What is JDBC ? Explain various steps to configure JDBC?

JDBC Stands for Java Data Base Connectivity. It was developed by JavaSoft and is a part
of the java Enterprise API. JDBC provides the ability to create robust, platform
independent applications and Web base applets, which can access any database

JDBC Working Style:

Web Technologies Q&A

A set of API objects and methods, defined in JDBC, are used to interact with the
underlying database. At the beginning of the process, a Java program opens a connection
to a database. Then, it creates a statement object, passes SQL Statements to the
underluying DBMS through the statement object, and retrieves the results and
information about the result set.

The first thing you need to do is check that you are set up properly. This involves the
following steps:

1.Install Java and JDBC on your machine.

To install both the Java tm platform and the JDBC API, simply follow the
instructions for downloading the latest release of the JDK tm (Java
Development Kit tm ). When you download the JDK, you will get JDBC as

2. Install a driver on your machine.

Your driver should include instructions for installing it. For JDBC drivers
written for specific DBMSs, installation consists of just copying the driver
onto your machine; there is no special configuration needed.
The JDBC-ODBC Bridge driver is not quite as easy to set up. If you download
JDK, you will automatically get the JDBC-ODBC Bridge driver, which does
not itself require any special configuration. ODBC, however, does. If you do
not already have ODBC on your machine, you will need to see your ODBC
driver vendor for information on installation and configuration.

3. Install your DBMS if needed.

If you do not already have a DBMS installed, you will need to follow the
vendor's instructions for installation. Most users will have a DBMS installed
and will be working with an established database.

Configuring Database:
Configuring a database is not at all difficult, but it requires special permissions and is
normally done by a database administrator.

First, open the control panel. You might find "Administrative tools" select it, again you
may find shortcut for "Data Sources (ODBC)". When you open the Data Source
(ODBC)" or 32bit ODBC icon, youll see a "ODBC Data Source Administrator" dialog
window with a number of tabs, including User DSN, System DSN, File DSN, etc.,
in which DSN means Data Source Name. Select System DSN,. and add a new
entry there by clicking on ADD button. Select appropriate driver for the data source or
directory where database
lives. For Oracle select Microsoft ODBC for Oracle Driver. You can name the entry
anything you want, assume here we are giving our data source name as "MySource".
Web Technologies Q&A

11. Explain various types of JDBC drivers used to connect DBMS?

A JDBC driver is a software component enabling a Java application to interact with a

database.[1] JDBC drivers are analogous to ODBC drivers, ADO.NET data providers, and
OLE DB providers.

To connect with individual databases, JDBC (the Java Database Connectivity API)
requires drivers for each database. The JDBC driver gives out the connection to the
database and implements the protocol for transferring the query and result between client
and database.

JDBC technology drivers fit into one of four categories

Type 1 Driver - JDBC-ODBC bridge

The JDBC type1 driver, also known as the JDBC-ODBC bridge, is a database driver
implementation that employs the ODBC driver to connect to the database. The driver
converts JDBC method calls into ODBC function calls.

The driver is platform-dependent as it makes use of ODBC which in turn depends on

native libraries of the underlying operating system the JVM is running upon. Also, use of
this driver leads to other installation dependencies; for example, ODBC must be installed
on the computer having the driver and the database must support an ODBC driver. The
use of this driver is discouraged if the alternative of a pure-Java driver is available. The
other implication is that any application using a type 1 driver is non-portable given the
binding between the driver and platform. This technology isn't suitable for a high-
transaction environment. Type 1 drivers also don't support the complete Java command
set and are limited by the functionality of the ODBC driver.

Translates query obtained by JDBC into corresponding ODBC query, which is
then handled by the ODBC driver.
Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This
driver is native code and not Java, and is closed source.
Client -> JDBC Driver -> ODBC Driver -> Database

Type 2 Driver - Native-API Driver Or also called Partial Java Driver

The JDBC type 2 driver, also known as the Native-API driver, is a database driver
implementation that uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API.

a full-Java implementation, is preferred over this driver.

Web Technologies Q&A

Type 3 Driver - Network-Protocol Driver

The JDBC type 3 driver, also known as the Pure Java Driver for Database Middleware, is
a database driver implementation which makes use of a middle tier between the
calling program and the database. The middle-tier (application server) converts
JDBC calls directly or indirectly into the vendor-specific database protocol.

Type 4 Driver - Native-Protocol Driver

The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a
database driver implementation that converts JDBC calls directly into a vendor-
specific database protocol.Therefore it is called a THIN driver.

12. Draw four JDBC drivers architectures?

Web Technologies Q&A
Web Technologies Q&A

13. What are JavaBeans ? Explain features of Java Bean?

Java Beans are reusable Java components used for developing web applications.
The features of Java Beans are:

1. Properties, Methods, and Events

Properties are attributes of a Bean that are referenced by name. These properties are
usually read and written by calling methods on the Bean specifically created for that
The methods of a Bean are just the Java methods exposed by the class that implements
the Bean. These methods represent the interface used to access and manipulate the
component. Usually, the set of public methods defined by the class will map directly to
the supported methods for the Bean, although the Bean developer can choose to expose
only a subset of the public methods.
Events are the mechanism used by one component to send notifications to another. One
component can register its interest in the events generated by another. Whenever the
event occurs, the interested component will be notified by having one of its methods
Types of Properties:
Simple Properties
Bound Properties
Constrained Properties
Indexed Properties

2. Introspection
Introspection is the process of exposing the properties, methods, and events that a
JavaBean component supports. This process is used at run-time, as well as by a visual
development tool at design-time. The default behavior of this process allows for the
automatic introspection of any Bean. A low-level reflection mechanism is used to analyze
the Bean's class to determine its methods.

Bean environments can use java.beans.Introspector:

BeanInfo bi = java.beans.Introspector.

3. Customization
When you are using a visual development tool to assemble components into applications,
you will be presented with some sort of user interface for customizing Bean attributes.
These attributes may affect the way the Bean operates or the way it looks on the screen.
Web Technologies Q&A

4. Persistence
It is necessary that Beans support a large variety of storage mechanisms. This way, Beans
can participate in the largest number of applications. The simplest way to support
persistence is to take advantage of Java Object Serialization. This is an automatic
mechanism for saving and restoring the state of an object. Java Object Serialization is the
best way to make sure that your Beans are fully portable, because you take advantage of a
standard feature supported by the core Java platform.

14. Explain Java Bean API?

Java Bean API Consists of Interfaces , classes and Exceptions for implementation of Java
Bean Application: The API consists of following interfaces, classes and Exceptions: