0% found this document useful (0 votes)
114 views23 pages

Explain The Reasons Why Servlet Is Preferred Over CGI. Ans: Servlets Are Server Side Components That Provides A Powerful Mechanism For

The document discusses the advantages of servlets over CGI. It lists 5 key advantages: 1) Platform independence as servlets are written in Java, 2) Performance as servlets initialize once and remain in memory, avoiding overhead of process creation for each request, 3) Extensibility as Java is object-oriented, 4) Safety as Java has features like memory management and exception handling, and 5) Security as servlets inherit security from the web server and Java security manager. The document also provides code examples to explain the RequestDispatcher interface methods forward() and include(), and a servlet code example to calculate the sum of squares of input integers.

Uploaded by

Raahul Sakpal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views23 pages

Explain The Reasons Why Servlet Is Preferred Over CGI. Ans: Servlets Are Server Side Components That Provides A Powerful Mechanism For

The document discusses the advantages of servlets over CGI. It lists 5 key advantages: 1) Platform independence as servlets are written in Java, 2) Performance as servlets initialize once and remain in memory, avoiding overhead of process creation for each request, 3) Extensibility as Java is object-oriented, 4) Safety as Java has features like memory management and exception handling, and 5) Security as servlets inherit security from the web server and Java security manager. The document also provides code examples to explain the RequestDispatcher interface methods forward() and include(), and a servlet code example to calculate the sum of squares of input integers.

Uploaded by

Raahul Sakpal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Rahu sakpal_10

1. Explain the reasons why servlet is preferred over CGI.

Ans: Servlets are server side components that provides a powerful mechanism for
developing server web applications for server side. Earlier CGI was developed to
provide server side capabilities to the web applications. Although CGI played a
major role in the explosion of the Internet, its performance, scalability and
reusability issues make it less than optimal solutions. Java Servlets changes all
that. Built from ground up using Sun’s write once run anywhere technology java
servlets provide excellent framework for server side processing.

Using servlets web developers can create fast and efficient server side applications
and can run it on any servlet enabled web server. Servlet runs entirely inside the
Java Virtual Machine. Since the servlet runs on server side so it does not depend
on browser compatibility.

Servlets have a number of advantages over CGI and other API’s.


They are:
1. Platform Independence:
Servlets are written entirely in java so these are platform independent. Servlets 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 provide a great advantages
over alternatives of servlets.

2. 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
any program initialization takes significant amount of time. But in case of servlets
initialization takes place first time it receives a request and remains in memory till
times out or server shut downs. After servlet is loaded, to handle a new request it
simply creates a new thread and runs service method of servlet. In comparison to
traditional CGI scripts which creates a new process to serve the request.

3. Extensibility:

1
Rahu sakpal_10

Java Servlets are developed in java which is robust, well-designed and object
oriented language which can be extended or polymorphed into new objects. So the
java servlets take all these advantages and can be extended from existing class to
provide the ideal solutions.

4. Safety:
Java provides very good safety features like memory management, exception
handling etc. Servlets inherits all these features and emerged as a very powerful
web server extension.

5. Secure:
Servlets are server side components, so it inherits the security provided by the web
server. Servlets are also benefited with Java Security Manager.

2. Explain the methods that RequestDispatcher interface does consist of


with the relevant code specification.

Ans: The RequestDispatcher interface defines an object that receives the request
from client and dispatches it to the resource(such as servlet, JSP, HTML file). This
interface has following two methods:

i. Public void forward(ServletRequest request, ServletResponse


response):
It forwards the request from one servlet to another resource (such as
servlet, JSP, HTML file).
ii. Public void include(ServletRequest request, ServletResponse
response):
It includes the content of the resource(such as servlet, JSP, HTML file) in
the response.

Difference between forward() vs include() method:


To understand the difference between these two methods, lets take an example:
Suppose you have two pages X and Y. In page X you have an include tag, this

2
Rahu sakpal_10

means that the control will be in the page X till it encounters include tag, after that
the control will be transferred to page Y. At the end of the processing of page Y,
the control will return back to the page X starting just after the include tag and
remain in X till the end.
In this case the final response to the client will be send by page X.

Now, we are taking the same example with forward. We have same pages X and
Y. In page X, we have forward tag. In this case the control will be in page X till it
encounters forward, after this the control will be transferred to page Y. The main
difference here is that the control will not return back to X, it will be in page Y till
the end of it.
In this case the final response to the client will be send by page Y.

CODE:

index.html:

<form action="servlet1" method="post">

Name:<input type="text" name="userName"/><br/>

Password:<input type="password" name="userPass"/><br/>

<input type="submit" value="login"/>

</form>

Login.java:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

3
Rahu sakpal_10

public class Login extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

String p=request.getParameter("userPass");

if(p.equals("servlet"){

RequestDispatcher rd=request.getRequestDispatcher("servlet2");

rd.forward(request, response);

else{

out.print("Sorry UserName or Password Error!");

RequestDispatcher rd=request.getRequestDispatcher("/index.html");

rd.include(request, response);

4
Rahu sakpal_10

WelcomeServlet.java:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

out.print("Welcome "+n);

3. Write a servlet that prints the sum of square of n integer numbers.

5
Rahu sakpal_10

Ans: Square.html:

<pre>

<form method=post action=”/Square”>

Enter a number : <input type=text name-t1>

<input type=submit value=”Find Ans”> <input type=reset

value=”clear”>

</form>

</pre>

Square.java:

public class Square extends HttpServlet {

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

response.setContentType(“text/html”);

PrintWriter out=response.getWriter();

int a=request.getParameter(“t1”);

int sum=0;

for(int i=1;i<=a;i++)

sum=sum+(i*i)

//sum=sum+pow(I,2);

6
Rahu sakpal_10

out.println(“The sum of square of “+ a+” is:”+sum);

4. Explain the life cycle phases of servlet.

Ans: The web container maintains the life cycle of a servlet instance. Let's see the
life cycle of the servlet:

1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle method
of the javax.servlet.Servlet interface. Syntax of the init method is given below:

7
Rahu sakpal_10

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet
is received. If servlet is not initialized, it follows the first three steps as described
above then calls the service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax of the service
method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:

public void destroy()

5. Explain the components of JDBC.

Ans: JDBC stands for Java Database Connectivity. For connectivity with the
database we uses JDBC. It establish connection to access the database. This
provides a set of classes in the java.sql package for Java applications to
communicate with databases. Mostly databases used a language called SQL. SQL
stands for Structured Query Language. JDBC gives you the opportunity to
communicate with standard database. JDBC includes four components:
1. The JDBC API
The JDBC API gives access of programming data from the Java. To use this,
applications can execute SQL statements and retrieve results and updation to the

8
Rahu sakpal_10

database. The JDBC API is part of the Java platform, it includes the Java Standard
Edition.
2. JDBC Driver Manager
The JDBC DriverManager is the class in JDBC API. The objects of this class can
connect Java applications to a JDBC driver. DriverManager is the very important
part of the JDBC architecture.
3. JDBC Test Suite
The JDBC driver test suite helps JDBC drivers to run your program. They are not
exhaustive,they do exercise with important features in the JDBC API.
4. JDBC-ODBC Bridge
The Java Software bridge provides JDBC access via ODBC drivers.You have to
load ODBC binary code for client machines for using this driver. This driver is
very important for application server code has to be in Java in a three-tier
architecture.
The program below describes how to run the JDBC program with
MySql. JDBCExample.java is the program to understand how to establish the
connection with database. The Url, Connection, Driver, Statement, Resultset etc.
and how to process the java code with database is mentioned here.

6. Write an exhaustive note on “PreparedStatement”. Attach the code


specification to support your answer.

Ans: The PreparedStatement interface inherits from Statement and differs from it
in two ways, first Instances of PreparedStatement contain an SQL statement that
has already been compiled. This is what makes a statement "prepared." Secondly,
the SQL statement contained in a PreparedStatement object may have one or more
IN parameters. An IN parameter is a parameter whose value is not specified when
the SQL statement is created. Instead the statement has a question mark (?) as a
placeholder for each IN parameter. A value for each question mark must be
supplied by the appropriate setXXX method before the statement is executed.
Because PreparedStatement objects are precompiled, their execution can be faster
than that of Statement objects. Consequently, an SQL statement that is executed
many times is often created as a PreparedStatement object to increase efficiency.

9
Rahu sakpal_10

Being a subclass of Statement, PreparedStatement inherits all the functionality of


Statement. In addition, it adds a set of methods that are needed for setting the
values to be sent to the database in place of the placeholders for IN parameters.
Also, the three methods execute, executeQuery, and executeUpdate are modified
so that they take no argument. The Statement forms of these methods (the forms
that take an SQL statement parameter) should never be used with a
PreparedStatement object. Before a PreparedStatement object is executed, the
value of each ? parameter must be set. This is done by calling a setXXX method,
where XXX is the appropriate type for the parameter. The first argument to the
setXXX methods is the ordinal position of the parameter to be set, with numbering
starting at 1. The second argument is the value to which the parameter is to be set.
Once a parameter value has been set for a given statement, it can be used for
multiple executions of that statement until it is cleared by a call to the method
clearParameters or until a new value is set.

CODE:

import java.io.*;

import java.sql.*;

class j2

public static void main (String args[]) throws Exception

try

Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection ("jdbc:odbc:tyitdemo");

PreparedStatement st =
10
Rahu sakpal_10

con.prepareStatement ("insert into students values(?,?)");

BufferedReader br =

new BufferedReader (new InputStreamReader (System.in));

String c = "yes";

while (!c.equals ("STOP"))

System.out.println ("enter roll number :");

String r = br.readLine ();

System.out.println ("enter name :");

String s = br.readLine ();

st.clearParameters ();

st.setInt (1, Integer.parseInt (r));

st.setString (2, s);

st.executeUpdate ();

System.out.println ("Continue?");

c = br.readLine ();

con.close ();

11
Rahu sakpal_10

catch (SQLException e)

System.out.println (e);

catch (ClassNotFoundException e)

System.out.println (e);

7. Explain the various JDBC drivers.

Ans: JDBC Driver is a software component that enables java application to


interact with the database. There are 4 types of JDBC drivers:

JDBC-ODBC bridge driver

Native-API driver (partially java driver)

Network Protocol driver (fully java driver)

Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

12
Rahu sakpal_10

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. This is now discouraged because of thin driver.

bridge driver

In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends
that you use JDBC drivers provided by the vendor of your database instead of the
JDBC-ODBC Bridge.

Advantages: easy to use.

can be easily connected to any database.

Disadvantages: Performance degraded because JDBC method call is converted into


the ODBC function calls.

The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.

Native-API driver

Advantage: performance upgraded than JDBC-ODBC bridge driver.

Disadvantage: The Native driver needs to be installed on the each client machine.

The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

13
Rahu sakpal_10

The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.

Network Protocol driver

Advantage: No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.

Disadvantages: Network support is required on client machine.

Requires database-specific coding to be done in the middle tier.

Maintenance of Network Protocol driver becomes costly because it requires


database-specific coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.

Thin driver

Advantage: Better performance than all other drivers.

No software is required at client side or server side.

Disadvantage: Drivers depend on the Database.

8. Write a jsp that accepts user-login details and forward the result either
“Access granted” or “Access denied” to result.jsp

Ans: Login.html:

<pre>

<form method=post action=”login.jsp”>


14
Rahu sakpal_10

Enter user ID: <input type=text name=t1>

Enter password: <input type=password name=p1>

<input type=submit value=”Login”> <input type=reset value=”Clear”>

</form></pre>

Login.jsp:

<%! int a,int b%>

<%

a=Integer.parseInt(request.getParameter(“t1”));

b=Integer.parseInt(request.getParameter(“p1”));

if((a!=” “) &&(b!=” “))

<jsp:forward page=”result.jsp”>

<jsp.param name=”res” value=”Access Granted”>

</jsp:forward>

else

<jsp:forward page=”result.jsp”>

<jsp.param name=”res” value=”Access Denied”>

</jsp:forward>
Result.jsp :

<%! String val%>

<%

15
Rahu sakpal_10

Val=request.getParameter(“res”);

Out.println(val);

%>

9. Write a servlet program to display the factorial of a number

Ans:

i) HTML form to input a given number

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1>Factorial of Number</h1>

<form action="MyServlet" method="Get">

Enter the Number:<input type="text" name="n1"/><br/>

<input type="submit" value="Find"/>

</form>

</body>

</html>

16
Rahu sakpal_10

ii) Servlet Program to accept the given number convert to integer and find the
factorial of a number and result is sent back to the Client.

package fact;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

String x=request.getParameter("n1");

int n=Integer.parseInt(x);

int i=1,fact=1;

if(n==0)

17
Rahu sakpal_10

out.println("<h1>factorial of 0"+"is"+n+"</h1>");

else

while(i<=n)

fact=fact*i;

i=i+1;

out.println("<h1>factorial of " + n +"="+fact+ "</h1>");

10.What is servlet? What are the different tasks carried out by servlet

Ans: Servlet technology is used to create a web application (resides at server side
and generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-
side programming language. However, there were many disadvantages to this
technology. We have discussed these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

Servlet can be described in many ways, depending on the context.MS using OOP
PHP tutorial MVC [2020]

18
Rahu sakpal_10

 Servlet is a technology which is used to create a web application.


 Servlet is an API that provides many interfaces and classes including
documentation.
 Servlet is an interface that must be implemented for creating any Servlet.
 Servlet is a class that extends the capabilities of the servers and responds to
the incoming requests. It can respond to any requests.
 Servlet is a web component that is deployed on the server to create a
dynamic web page.

Servlets perform the following major tasks −


 Read the explicit data sent by the clients (browsers). This includes an
HTML form on a Web page or it could also come from an applet or a
custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This
includes cookies, media types and compression schemes the browser
understands, and so forth.
 Process the data and generate the results. This process may require talking
to a database, executing an RMI or CORBA call, invoking a Web service,
or computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or
XML), binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes
telling the browsers or other clients what type of document is being
returned (e.g., HTML), setting cookies and caching parameters, and other
such tasks.

11. Write various classes of Servlet API. Write the purpose of each

Ans: There are many classes in javax.servlet.http package. They are as follows:

19
Rahu sakpal_10

1. Http Servlet: HTTP servlets can read HTTP headers and write HTML
coding to deliver a response to a browser client. Servlets are deployed on
WebLogic Server as part of a Web Application. A Web Application is a
grouping of application components such as servlet classes, JavaServer
Pages (JSP), static HTML pages, images, and security.
2. Cookie: A cookie is a small piece of information that is persisted between
the multiple client requests.A cookie has a name, a single value, and optional
attributes such as a comment, path and domain qualifiers, a maximum age,
and a version number.By default, each request is considered as a new
request. In cookies technique, we add cookie with response from the servlet.
So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.
3. Http ServletRequestWrapper: Class HttpServletRequestWrapper.
Provides a convenient implementation of the HttpServletRequest interface
that can be subclassed by developers wishing to adapt the request to a
Servlet. This class implements the Wrapper or Decorator pattern. Methods
default to calling through to the wrapped request object.
4. Http ServletResponseWrapper: Class HttpServletResponseWrapper.
Provides a convenient implementation of the HttpServletResponse interface
that can be subclassed by developers wishing to adapt the response from a
Servlet. This class implements the Wrapper or Decorator pattern.
5. Http SessionEvent: The HttpSessionEvent is notified when session object
is changed. The corresponding Listener interface for this event is
HttpSessionListener. We can perform some operations at this event such as
counting total and current logged-in users, maintaing a log of user details
such as login time, logout time etc.
6. Http SessionBindingEvent: Constructs an event that notifies an object that
it has been bound to or unbound from a session. To receive the event, the
object must implement HttpSessionBindingListener .
7. Http Utils (deprecated now): It provides a set of utility functions to enable
making http requests easily. This library is now written in Typescript and it
exports its own types, as well as some common ones from axios for
convenience.
20
Rahu sakpal_10

12. Write a note on


1. Sessions:

Ans: There are a number of problems that arise from the fact that HTTP is the
stateless protocol For example:

When an online shopping is done, it is a real annoyance that the Web server cannot
eas remember previous transactions.
This makes the applications such as shopping carts very problematic:
When an entry is added to the cart?
How does the server know what's already in the cart?
Even if servers did retain contextual information, the user will still have the
problems with commerce.
When the user moves from the page where it specified what it wants to buy [hosted
on the regular Web server] to the page that takes the credit card number and
shipping address [hosted on the secure server that uses SSL], how does the server
remember what the user is buying?
Here comes the entry of Session.
Sessions are great for storing temporary data about the visitors. Sessions are used
when the website does not want this data to be accessible external to the Web
server.Sessions and Cookies share a relationship between them. They serve the
same purpose to a limited extent and are interchangeably usable.

Sessions are a means to store and track client data while they navigate through a
series of pages or page iterations on the website.
The significant difference between a cookie and a session is that a cookie is stored
on the client's hard disk, while session data is stored on the Web server.
A session occurs between the time that a client logs in to the desktop environment
and the time that the client logs out. The session manager [a module of Java
Servlet] automatically starts after the Login Manager authenticates the client.
For example, a client can save the state of a session and return to that session the
next time the client logs in.
During a visit to an Internet shopping site, a session could be the series of
transactions that a client makes while adding items to a shopping cart. The session
21
Rahu sakpal_10

may consist of multiple requests to the same resource to many different resources
on the same website.
A session is the amount of time, which a client takes while navigating through a
site. In an HTTP transaction cach connection between the client and the Web
server is very br
This is an inherent trait of a stateless protocol.
In a typical stateless protocol transaction, the client:
Establishes a connection with the Web server
Issues a request
Receives a response
a Closes the connection
Since a persistent connection is not maintained between such requests, the Web
server's bond to the client is cut off once the connection is closed.
This disconnection between a client and the Web server leads to the following
limitations:
If the Web server requires client authentication, for example, a client must log in,
the client must re-login with every request. The Web server does not realize that it
has already authenticated this client because the connection between the two was
lost
Storing visitor specific information such as the contents of a shopping cart or
visitor defined preferences is not possible, as the Web server cannot distinguish
one client from another
The solution to these problems is to establish a persistent virtual connection
between the client and the Web server. Such a virtual connection associates each
request received by the Web server with the client that issued it. This association is
accomplished as follows: The visitor's web browser returns a piece of state

information with each new request The Web server uses this piece of information,
which is usually called a SESSION ID uniquely identify the visitor's Web browser
The Web server associates the current request with the client's previous requests
The Web server can thus identify the visitors using such virtual connections
These virtual connections are commonly referred to as sessions. Sessions are used
maintain state and a visitor's identity across multiple requests.

22
Rahu sakpal_10

Since the association between the HTTP client and the HTTP Web server persists
across multiple requests and/or connections for a specific period of time, the
question arises.

2. Cookies:
Ans: A cookie is a small piece of information that is persisted between the
multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we
add cookie with response from the servlet. So cookie is stored in the cache of the
browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets: Non-persistent cookie, Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

Advantage of Cookies: Simplest technique of maintaining the state.


Cookies are maintained at client side.
Disadvantage of Cookies: It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.

23

You might also like