Explain The Reasons Why Servlet Is Preferred Over CGI. Ans: Servlets Are Server Side Components That Provides A Powerful Mechanism For
Explain The Reasons Why Servlet Is Preferred Over CGI. Ans: Servlets Are Server Side Components That Provides A Powerful Mechanism For
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.
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.
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:
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>
Login.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
3
Rahu sakpal_10
response.setContentType("text/html");
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
else{
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.*;
response.setContentType("text/html");
String n=request.getParameter("userName");
out.print("Welcome "+n);
5
Rahu sakpal_10
Ans: Square.html:
<pre>
value=”clear”>
</form>
</pre>
Square.java:
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
Ans: The web container maintains the life cycle of a servlet instance. Let's see the
life cycle of the servlet:
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.
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.
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
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:
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:
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.
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
CODE:
import java.io.*;
import java.sql.*;
class j2
try
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
PreparedStatement st =
10
Rahu sakpal_10
BufferedReader br =
String c = "yes";
st.clearParameters ();
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);
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
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.
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
Disadvantage: The Native driver needs to be installed on the each client machine.
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.
Advantage: No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.
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
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></pre>
Login.jsp:
<%
a=Integer.parseInt(request.getParameter(“t1”));
b=Integer.parseInt(request.getParameter(“p1”));
<jsp:forward page=”result.jsp”>
</jsp:forward>
else
<jsp:forward page=”result.jsp”>
</jsp:forward>
Result.jsp :
<%
15
Rahu sakpal_10
Val=request.getParameter(“res”);
Out.println(val);
%>
Ans:
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h1>Factorial of Number</h1>
</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;
response.setContentType("text/html;charset=UTF-8");
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;
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
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
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.
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.
23