SlideShare a Scribd company logo
1 of 46
Download to read offline
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 1
Q. Write a short note on Java EE Server .
Java EE Server :
➢ Java EE Server is a server application that Implements the java EE
platform APIs and provides the standard Java EE services.
➢ Java EE Server are sometimes called Application Servers because they
allow serving application Data to client, much as how Web Servers
serve Web pages to Web Browsers.
➢ Java EE Servers host several application Component type that
correspond to the tiers in A multi-tiered application. The Java EE
server Provides services to these components in the
➢ Form of Containers as shown in diagram
➢ During the deployment process, installation of Java EE application
components takes place in The Java EE Containers on the Java EE
Server. Java EE server is used as runtime portion for The execution of
application, which contains The EJB and Web containers.
Topic : The Need for Dynamic Content, ,Java Servlet Technology .
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 2
Q. Write a short note on Java Servlet Technology :
Java Servlet Technology :
➢ It is a highly efficient CGI program written in Java.
➢ It is a way to have thin, dynamic web clients.
➢ It is a server-side program that services HTTP requests and returns the
results as HTTP responses.
➢ It has a lifecycle and runs inside a JVM at the Web server.
➢ The Servlet's output is delivered to a Web browser.
➢ It is supported by virtually all Web servers and Application Servers
➢ It solves the performance problem by executing all requests as threads
in one process
➢ It can easily share resources.
➢ It can be easily ported to other platforms that support Java, as it runs
inside aJVM
➢ When a user issues a request for a URL that corresponds to a Java
Servlet the server hands the request off to the Servlet for processing.
➢ The Servlet dynamically produces a response to the request, typically
an HTML Web page and sends it back to the requesting Web browser.
➢ Java Servlets are efficient, due to an intuitive and automated threading
model in which each request is handled by a new lightweight thread.
➢ Servlets are also platform [i.e. hardware] independent .
Q. Why Servlets? What can Servlets do?
A Servlet is a small, self-contained, portion of code that is executed at the
Web Server in response to an HTTP request from a client's browser.
Servlets can do the following:
➢ A servlet can process and/ or store data submitted by an HTML form.
➢ A Servlet can provide dynamic content, for example, return the results
of a database query to the client
➢ A Servlet can manage state information on top of the stateless HTIP,
for example, for an online shopping cart system which manages
shopping carts for many concurrent customers and maps every request
to the right customer
➢ Servlets can be used as a plug-in, that features a search engine or semi-
customized applications such as web-based banking or inventory
systems
➢ A Servlet can handle multiple requests concurrently and these requests
can be
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 3
synchronized to support systems allowing collaboration between
people
➢ Servlets can forward requests to other Servers and Servlets. This
allows them to be used to balance load among several servers that
mirror the same content
➢ Servlets can maintain and track sessions [either by URL rewriting or
cookies].
➢ Servlets clean up the session precisely when a session is terminated,
either by logging off or by a time-out.
➢ Servlets can pass data between themselves .
➢ Servlets can be used to serve as the HTTP speaking middle tier
between any kind of thin client and large enterprise services being
made available via EJB's
Q. Write a short note on Servlet API
Java Servlet API :
➢ Java provides a Servlet Application Programming Interface [API]
which is a class library [basic classes and interfaces] for implementing
Servlets
➢ The Java API forms a standard interface for developing Web
application, regardless of the underlying operating system. Without
the implementation of Java API it is not possible to develop dynamic
applications. This Java API consists of a set of important interfaces
that can be implemented in different areas so that developers can
conveniently build Java-powered applications.
➢ Servlets can access the entire family of Java APIs. The Java Servlet
API is the class library using which requests can be processed and
responses can be constructed, dynamically. The API thus helps define
the expected interactions of a Web container and a Servlet.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 4
The following are the basic classes and Interfaces used for
implementing the Servlet.
javax.servlet Package
javax.servlet package is the core of the Servlet API.
iavax.servlet package includes the basic Servlet interface, which all Servlets
must implement in one form or another and an abstract GenericServlet
class for developing basic Servlets.
This package also includes classes for:
Communicating with the host server and client:
o ServletRequest
o ServleResponse
Communicating with the client:
o ServletInputStream
o ServletOutputStream
Q.Write a short note on Servlet Interface.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 5
Servlet Interface :
➢ Servlet interface is a collection of empty method signatures.
➢ A servlet must directly or indirectly [by subclassing the
GenericServlet or HttpServlet class] implement the servlet interface.
This interface holds method sigantures that bring the following basic
Servlet functionalities:
➢ Initializing a Servlet
➢ Handling a client request
➢ Destroying a Servlet
The following are the methods available in this interface:
Methods Description
init () Is used for initializing the servlet parameters provided
by the ServletConfig object.
Is called only once when the Servlet is first loaded. It
is commonly used to initialize resources to be used by
a Servlet when requests are received.
For example, database or network connections, file
initialization and other environment settings.
None of the Servlets methods can be called unless the
Servlet is initialized using init().
destroy() destroy() is also called only once immediately before
the Servlet is unloaded.
Is used to clear all retained resources such as database
connection, threads, file handles and so on. This
method is overridden in order to free up any resources
being used by the Servlet
service() Is the actual heart of the HTTP Request-Response
model.
Is called to handle a single client request.
A Servlet receives request information through the
ServletRequest object and sends data back to the
client through the ServletResponse object.
getServletConfig() Provides the ServletConfig object for initializing the
Servlet’s parameters.
getServletInfo() Provides the Servlet metadata such as author, servlet
version and other copyright information. This method
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 6
needs to be overridden inside the Servlet for it to
return the required information.
Q. Write a short note on ServletContext Interface .
ServletContext Interface :
All Servlets belong to one Servlet context. ServletContext can only be
called at context initialization time.
The ServletContext interface provides a set of methods which allow
communicating with the server such as:
❑ Finding path information
❑ Accessing other Servlets running on the server
❑ Writing to the server log file
ServletContext allows enabling applications to load Servlets and Filters at
runtime that are needed.
The following are the methods available in this interface:
Methods Description
getAttribute() Returns the value of the named server
attribute as an Object.
getAttributeNames() Returns an Enumeration containing the
attribute names available within in the
current ServletContext.
getContext() Returns a ServletContext object that
corresponds to a specified URL on the
server.
getContextPath() Returns the context path of the web
application.
getMimeType() Returns the MIME type of the given file.
getRealPath() Returns the real file system path of any
given virtual path.
getServletInfo() Returns the name and version of the
servlet container on which the servlet is
running.
getInitParameter() Returns a String containing the value of
the named context-wide initialization
parameter
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 7
getRequestDispatcher() Returns a RequestDispatcher object that
act as a wrapper for the resource located
at the given path.
setAttribute() Binds an object to a given attribute name
in the current ServletContext.
removeAttribute() Removes the Attribute with the given
name from the current ServletContext
Q. Write a short note on ServletContext Interface .
ServletConfig Interface :
The ServletConfig objects help Servers pass initialization and context
information to Servlets such as:
➢ A series of initialization parameters
➢ A servletContext object, which provides information about the server
environment
The following are the methods available in this interface:
Methods Description
getInitParameter() Returns the value of the named Servlet
initialization parameter.
getInitParameterNames() Returns all the servlet’s initialization parameter
names as an Enumeration of String objects.
getServletContext() Returns the Servlet’s ServletContext object.
Q. List and explain ServletRequest And ServletResponse Interfaces.
ServletRequest And ServletResponse Interfaces :
➢ When a Servlet accepts a call from a client, it receives two objects,
one is a ServletRequest and the other is a ServletResponse.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 8
➢ ServletRequest interface encapsulates the communication from the
client to the server, while
➢ ServletResponse interface encapsulates the communication from the
Servlet back to the client.
ServletRequest interface allows the Servlet to access information such
as:
➢ Names of the parameters passed by the client
➢ The protocol [scheme] such as the HTTP POST and PUT methods
being used by the client
➢ The names of the remote host that made the request
➢ The server that received it
➢ An input stream for reading binary data from the request body
Subclasses of ServletRequest allow the Servlet to retrieve more protocol-
specific data. For example, HttpServletRequest contains methods for
accessing HTTP-specific header information.
The following are the commonly used methods available in this
interface:
Methods Description
getAttribute() Returns the value of the named attribute as an
Object.
getParameter() Returns the value of a request parameter as a
String.
getParametrValues() Returns an array of String objects containing all
of the values the given request parameter has.
getRequestDispatcher() Returns a RequestDispatcher object that acts as a
wrapper for the resource located at the given
path.
getServerName() Returns the host name of the server to which the
request was sent.
removeAttribute() Removes the attribute from this request.
setAttribute() Stores an Attribute in this request.
ServletResponse interface provides methods to the Servlet for replaying
to the client.
ServletResponse interface allows Servlet:
➢ To set the content length and mime type of the reply
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 9
➢ Provides an output stream and a Writer
Through ServletResponse interface, the Servlet can send the reply data.
Subclasses of ServletResponse provide the servlet with more protocol-
specific capabilities. For example, HttpServletResponse contains methods
that allow the Servlet to manipulate HTTP-specific header information.
The following are the commonly used methods available in this
interface:
Methods Description
getOutputStream() Returns a ServleOutputStream suitable for writing
binary data in the response.
getWriter() Returns a PrintWriter object that can send character
text to the client
reset() Clears any data that exists in the buffer as well as
the status code and headers.
Q. Write a short note on GenericServlet Class.
GenericServlet Class :
➢ Javax.Servlet.GenericServlet class provides the basic implementation
of the Servlet interface. It also implements ServletsConfig interface.
➢ GenericServlet may be directly extended by a Servlent, although it’s
more common to extend a protocol-specific subclass such as
HttpServlet.
➢ GenericServlet makes writing Servlets easier.
ServletInputStream And ServletOutputStream Classes :
➢ ServletInputStream and ServletOutputStream classes are abstract
classes that a Servlet container implements.
➢ ServletInputStream class provides an input stream for reading binary
data from a client request.
➢ ServletInputStream class is returned by getInputStream () of
ServletRequest.
➢ A Servlet that filters binary output from other sources generally
receives its input through this stream.
The following is the method available in this class:
Methods Description
readLine() Reads the input stream one line at a time.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 10
➢ ServletOutputStream class provides an output stream for sending
binary data back to a client.
➢ A servlet obtains ServletOutputStream object from getOutputStream ()
of ServletResponse.
The following are the commonly used methods available in this class:
Methods Description
print () Writes a character to the client, with no carriage return
line feed at the end.
printIn() Writes a carriage return line feed to the client.
Q. Write a short note on Requestdispactcher.
RequestDispatcher Interface :
➢ RequestDispatcher interface defines an object that receives requests
from the client and sends them to any resource such as a Servlet
HTML file or JSP file on the server.
➢ The Servlet container creates RequestDispatcher object, which is used
as a wrapper around a server resource located at a particular path or
given by a particular name.
➢ This interface is intended to wrap Servlets, but a Servlet container can
create RequestDispatcher objects to wrap any type of resource.
The following are the methods available in this interface:
Methods Description
forward() Forwards a request from a Servlet to another resource
such as Servlet, JSP or HTML file on the server.
include() Includes the content of a resource such as Servlet,
JSP, HTML, file in the response.
Q. List and explain The classes and interfaces described so for make up
a Basic Servlet.
The classes and interfaces described so for make up a Basic Servlet.
Javax.servlet.http Package:
Javax.servlet.http package is used to develop Servlets that support the HTTP
protocol.
This package holds specialized classes that help perform tedious tasks
such as:
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 11
➢ HttpServlet class includes support for different HTTP request methods
and headers
➢ HttpServletRequest and HttpServletResponse interfaces allow
additional direct interaction with the web server. (Refer to explaination
given above)
➢ HttpSession provides built-in session tracking functionality
➢ Cookie class allows quickly setting up and processing HTTP cookies
Q. Write a short note on HttpServlet Class.
HttpServlet Class :
➢ HttpServlet inherits basic Servlet functionality by extending
GenericServlet class.
➢ HttpServlet is an abstract class that resides in javax.servlet.http
package. Because it is abstract, it cannot be instantiate. Rather, when
building an HTTP servlet, HttpServlet class must be extended with at
least one of its methods implemented.
➢ A functional HTTP Servlet must override at least one of methods
typically service(),doGet(), doPost(). Although HttpServlet does not
provide the implementation for most of its methods,it does provide a
framework for supporting the HTTP protocol.
➢ HTTP Servlets have some additional objects that provide session-
tracking capabilities. The Servlet writer can use these APIs to maintain
state between the Servlet and the client that persists across multiple
connections during some time period.
The following are the commonly used methods available in this class:
Method Description
Service() Handles dispatching requests to the protected, HTTP-
specific service () and cannot be overridden disabling
dispatching to the handler methods for each HTTP
request type.
doGet() Is called in response to an HTTP GET request
[including conditional GET requests]. Overriding this
method to support a GET request also automatically
supports an HTTP HEAD request. A HEAD request
is a GET request that returns no body in the response,
only the request header fields.
doPost() Is called in response to an HTTP POST request. The
HTTP POST method allows the client to send data of
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 12
unlimited length to the Web Server a single time and
is useful when posting information such as credit card
numbers.
Q. Write a short note on HttpServletRequest And HttpServletResponse
Interfaces.
HttpServletRequest And HttpServletResponse Interfaces :
➢ HttpServletRequest interface provides methods for extracting HTTP
parameters from the query string or the request body depending on the
type of request such as GET or POST.
➢ HttpServletResponse interface provides an OutputStream for
returning binary data such as a GIF or JPEG image and PrintWriter
for returning text output.
➢ HttpServletRequest interface extends ServletRequest interface to
provide request information for HTTP Servlets. HttpServletResponse
interface extends ServletResponse interface to provide HTTP
protocol-specific functionality including response headers and status
codes.
➢ HttpServletRequest and HttpServletResponse interface give full access
to all information about the request and allows controlling the output
sent to the client as the response to the request.
HttpServletRequest interface includes:
❑ Support for:
o Cookies
o Session tracking
❑ Access to HTTP header information
➢ HttpServletRequest interface also parses incoming HTTP form data
and stores it as Servlet parameters.
➢ HttpServletResponse interface also defines a series of constants that
represent various HTTP status codes and includes helper functions
for session tracking operations.
The following are the commonly used methods available in
HttpServletRequest interface:
Methods Description
getCookies() Returns an array containing all of the Cookie
objects the client sent with this request.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 13
getSession() Returns the current session associated with this
request or if the request does not have a session,
created one.
authenticate() Uses the container login mechanism configured for
the ServletContext to authenticate the user making
this request. This method may modify and commit
the argument HttpServletResponse.
login() Validates the Provided username and password in
the password validation realm used by the Web
container login mechanism configured for the
ServletContext.
The following are the commonly used methods available in
HttpServletResponse interface:
Method Description
addCookie() Adds the specified cookie to the response.
encodeURL() Encodes the specified URL by including the session ID in
it or if encoding is not needed, returns the URL
unchanged.
sendRedirect() Sends a temporary redirect response to the client using
the specified redirect location URL.
setStatus() Sets the status code for this response.
Q. Write a short note on HttpSession Interface .
HttpSession Interface :
➢ HttpSession interface provides a way to identify a user across more
than one page request or visit to a website and to store information
about that user.
➢ With the help of the HttpSession interface, a session can be created
between an HTTP client and an HTTP server. This session can persist
for a specified time period, across more than one connection or page
request from the user.
➢ A session usually corresponds to one user, who may visit a site many
times. The server can maintain a session in many ways such as using
cookies or rewriting URLs.
This interface allows Servlets to:
View and manipulate information about a session such as:
o The session identifier
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 14
o Creation time
o Last accessed time
Bind objects to sessions, allowing user information to persist across
multiple user connection
A Servlet obtains an HttpSession object using getSession() of
HttpServletRequest.
The following are the commonly used methods available in this
interface:
Method Description
getId() Returns a string containing the unique
identifier assigned to this session.
getMaxInactiveInterval() Returns the maximum time interval, in
seconds, that the Servlet container will keep
this session open between client accesses.
Invalidate() Invalidates this session then unbinds any
objects bound to it.
isNew() Returns true if the client does not yet know
about the session or if the client chooses not
to join the session.
setMaxInactiveInterval() Specifies the time, in seconds, between
client requests before the Servlet container
will invalidate this session.
Q. Write a short note on Cookies Class.
Cookies Class : Cookies are often used for Session management or in
situations where it is required to uniquely identify a client.
The Cookie class allows Servlets to:
➢ Read, create and manipulate HTTP-style cookies
➢ Store small amounts of data on the client
A servlet uses getCookies() of HttpServletRequest to retrieve cookies
submitted as part of client request.
addCookie() of HttpServletResponse can be used to send a new cookie to
the Web Browser.
Since cookies are set using HTTP headers, addCookie() must be called
before any output is sent to the client.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 15
The following are the commonly used methods available in this class:
Method Description
getDomain() Returns the domain name set for this cookie.
getMaxAge() Returns the maximum age of the cookie, in seconds. By
default, -1 indicates that the cookie will persist until
browser shutdown.
getName() Returns the name of the cookie.
getValue Returns the value of the cookie.
setDomain() Specifies the domain within which this cookie should be
presented.
setMaxAge() Sets the maximum age of the cookie in seconds.
setValue() Assigns a new value to a cookie after the cookie is
created.
Q. Write a short note on the Servlet Skeleton.
Servlet Skeleton :
➢ According to Sun Microsystems when any Servlet is crafted its code
spec must have a standard skeleton.
➢ In its most general form, a Servlet is an instance of a class which
implements javax.servlet.Servlet interface.
➢ Most Servlets, however, extend one of the standard implementations
of that interface, namely javax.servlet.GenericServlet and
javax.servlet.http.HttpServlet.
➢ Developers use this as a blueprint when crafting their Servlet code.
Implementing Servlet interface or extending
GenericServlet/HttpServlet classes provides a framework for creating a
Servlet as well as significant default functionality. The Servlet’s code spec
must override at least one method when my custom functionality is being
implemented.
In order to initialize a Servlet, the web server:
➢ Loads the Servlet class [and probably other classes which are
referenced by the Servlet] and creates an instance by calling the no-
args constructor
➢ Calls the Servlet’s init(ServletConfig config) method
o Init()is called only once when the Servlet is loaded in memory
for the first time and store ServletConfig object. The Servlet
creator can encapsulate any code that must run before the main
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 16
code spec of the Servlet is executed such as connecting to a
database for instance.
➢ ServletConfig object supplies a Servlet with information about its
initialization parameters. These parameters are given to the Servlet
itself and are not associated with any single request. ServletConfig
object can be retrieved by calling the Servlet’s getServletConfig()
method. This is handled by GenericServlet.
➢ Any Java enabled Web server automatically invokes the Servlet’s
service() method in response to a client request. This means when a
Servlet is initialized, its service(ServletRequest request,
ServletResponse response) method is called for every request to the
Servlet.
➢ Hence, service() must be overridden to provide customized
functionality the moment a Servlet is invoked. However, if a Servlet
developer chooses not to override service(), there are other methods
that can be invoked in response to a client request.
➢ When the Servlet needs to be unloaded for example, because a new
version should be loaded or the server is shutting down, destroy() us
called.
Based on this brief description, a skeleton of a common Servlet has been
constructed.
For simplicity, the skeleton Servlet that follows does not include
parameters passed to its methods or exception handling code for any
exceptions that are thrown:
1. public class SkeletonServlet extends HttpServlet {
2. public void init ( ) {
3. /* Initialization code goes here */
4. }
5. public void service ( ) {
6. /* Meaningful work happens here*/
7. }
8. public void destroy ( ) {
9. /*Free resources here*/
10. }
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 17
11. }
Servlets may or may not implement init() or destroy(). Implementation of
these methods is not mandatory.
Q. Write a short note on The Servlet Life Cycle .
The Servlet Life Cycle :
The Servlet lifecycle describes how a Servlet is:
➢ Loaded
➢ Instantiated
➢ Initialized
➢ Services requests
➢ Destroyed
➢ Finally garbage collected
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 18
Every Servlet engine must adhere to the Servlet lifecycle.
Initialization :
➢ In order to initialize a Servlet, the Servlet engine first locates its class.
A Servlet class may reside on the local file system, a remote file
system or be some other network resource. The Servlet engine uses the
usual Java class loading facilities to load the Servlet class into the
JVM. Once loaded, the Servlet engine instantiates an instance of that
Servlet class [and probably other classes which are referenced by the
Servlet].
➢ Then it calls the Servlet’s init (Servlet Config config) method.
➢ Init() is called immediately after the Server constructs the Servlet’s
instance.
Depending on the server and its configuration, this can be called at any
of the following cases:
➢ When the Server starts
➢ When the Servlet is first requested, just before service () is invoked.
➢ At the request of the server administrator.
Why Not Use A Constructor Instead Of init()?
➢ In the oldest version of Java i.e. JDK 1.0 for which Servlets were
originally written, constructors for dynamically loaded Java classes
such as Servlets were incapable of accepting arguments. This
prevented from providing , a new Servlet, any information about itself
and its environment. To overcome this issue, a Server [Servlet engine]
had to call a Servlet’s init() method and pass along an object that
implements the ServletConfig interface.
➢ Java does not allow interfaces to declare constructors i.e.
javax.servlet.Servlet interface cannot declare a constructor that accepts
a ServletConfig parameter.It has to declare another method such as
init().
➢ Indirectly one can still define constructors for Servlets, but from
within a constructor there is no access to servletConfig object or the
ability to throw a ServletException.
init() is guaranteed to be called:
1. Before the Servlet handles its first request
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 19
2. Only once during the Servlet’s lifecycle
init() :
init() is declared as follows:
public void init (ServletConfig config) throws ServletException
During initialization, the Servlet has access to two objects:
➢ ServletConfig
➢ ServletContext
This is because to init() an object of ServletConfig is passed as a parameter.
When a Servlet is setup for the first time, the configuration data such as
information about the parameters and references to the ServletContext is
stored in ServletConfig object.
The following are the common tasks that can be implemented by
overriding init() of Servlet interface:
1. Reading initializing parameters using ServletConfig object
2. Reading configuration data from persistent resources like
configuration file
3. Initializing a database driver, a connection pool or logging service
4. Opening a JDBC connection
5. Writing log information to a network resource
A servlet that cannot complete its initialization process throws
UnavailableException.
Only after the completion of initialization, will the server be ready for client
requests to handle [i.e.before service() is called] or the Servlet is destroyed.
Runtime :
After the server loads and initializes the servlet, the Servlet is able to handle
client requests.
It processes them in service(). Each client’s request to service () is run in
separate Servlet thread.
service() is declared as follows:
public void service (ServletRequest request, Servlet Response response)
throws ServletException, IOException
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 20
For, every request to the servlet, its service() method is called. Two objects
i.e. ServletRequest and ServletResponse are passed as parameters to service.
ServletRequest object helps in accessing the original request data and
ServletResponse object provides methods that help the Servlet to build a
response.
Servlets can run multiple service() methods at a time. It is important
therefore, that service() be written in a thread-safe manner.
For example, if a service () method updates some crucial data in the Servlet
object, access to this thread should be synchronized. If for some reason, the
server should not run another service() concurrently, the Servlet should
implement SingleThreadModel interface. This interface guarantees that no
two threads will execute the Servlet’s service() concurrently.
Destruction :
➢ When instructed to unload the Servlet, perhaps by the server
administrator or programmatically by the servlet itself, the Servlet
engine calls the Servlet’s destroy (). The Servlet is then eligible for
garbage collection.
➢ All resource which were allocated in init() should be releasedin
destroy().
Destroy() is declared as follows:
public void destroy ()
The method is run once. The server will not run it again until after it reloads
and reinitializes the Servlet.
The common tasks implemented in destroy () are:
➢ Synchronizing cleanup tasks such as closing any open resource,
closing a connection pool
➢ Informing another application that Servlet will no longer be in service
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 21
➢ Destroy()is guaranteed to be called only once during the servlet’s
lifecycle.
➢ During a servlet’s lifecycle , it is imporatnatn to write thread -safe
code for destroying the Servlet and unless the Servlet implements
SingelThreadModel interface, serviceing client requests.
➢ There may still be thread that eeccute service when destroy() is called,
so destroy() has to be thread -safe.
A Simple Welcome Servlet .( Using GenericServlet class & Service
Method)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class myGenericServlet extends GenericServlet {
public void init()
{
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("Text/html");
Server locates and
loads the servlet
Server instantiate one or
more object instances of the
servlet class
Client request arrives
Server initializes the
servlet by invoking init()
Server delegates the
client request to the
servlet through service() Service() processes
the client request
Service() then returns
the output to the client
Servlet waits until the
next client request
arrives
To free memory
resources, the server
calls destroy()
Servlet is unloaded
by the server
Diagram 6.2 the servlet lifecycle
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 22
PrintWriter out=response.getWriter();
out.println("Welcome to the world of Java!");
}
public void destroy()
{
}
}
A Simple Welcome Servlet . (Using Service Method )
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
public class WelcomeServ extends HttpServlet {
public void init()
{ }
protected void service(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("Text/html");
PrintWriter out=response.getWriter();
out.println("Welcome to the world of Java!");
}
}
WelcomeServlet with doGet & doPost Methods and HttpServlet class
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void init()
{
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 23
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("Text/html");
PrintWriter out=response.getWriter();
out.println("Welcome to the world of Java in LIIT !");
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request,response);
}
}
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 24
Chapter 7 :Working With Servlets
Q.Write a short note on Servlets.
Servlets :
➢ A servlet is a Java program that must be run by a Java Servlet engine
on a Java enabled Web server. The servlet’s output is delivered to a
Web browser.
➢ Sun GlassFish Enterprise Server that comes bundled with the
NetBeans IDE 6.8 has built-in support for running Java Servlets. This
book uses the bundled server to demonstrate and run Servlets.
Working with Servlets requires the knowledge of:
➢ What is a web application
➢ The organization of a web application
➢ How to create a Servlet file
➢ Compiling and building the application
➢ Deploying the application
➢ Executing the Servlet/ web application
Chapter 8 Working with Databases: What Is JDBC?
Q. Write a short note on JDBC.
Goal of JDBC is to make possible the following:
➢ Programmers can write applications in the Java programming
language to access any database, using standard SQL statements or
even specialized extensions of SQL while still following Java
language conventions.
➢ Database vendors and database tool vendors can supply the low-level
drivers. Thus, they can optimize their drivers for their specific
products.
Typical Uses of JDBC : The traditional client/server model has a rich GUI
on the client and a database on the server (see Figure 4-2).
In this model, a JDBC driver is deployed on the client.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 25
However, the world is moving away from client/server and toward a "three-
tier model" or even more advanced "n-tier models."
In the three-tier model, the client does not make database calls. Instead, it
calls on a middleware layer on the server that in turn makes the database
queries.
The three-tier model has a couple of advantages.
➢ It separates visual presentation (on the client) from the business logic
(in the middle tier) and the raw data (in the database). Therefore, it
becomes possible to access the same data and the same business rules
from multiple clients, such as a Java application or applet or a web
form.
➢ Communication between the client and middle tier can occur through
HTTP (when you use a web browser as the client), RMI, or another
mechanism.
➢ JDBC manages the communication between the middle tier and the
back-end database.
Client JDBC
Database protocol
Database
server
Figure 4-2 A traditional client/server application
Figure 4.1 JDBC-to-database communication path
Java application
JDBC Driver Manger
JDBC/ODBC bridge Vendor-supplied JDBC driver
ODBC driver
Database
Database
JDBC API
JDBC Driver API
Client (visual
presentation)
Middle tier
(business logic)
JDBC
HTTP, RMI, etc… Database protocol
Database
server
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 26
Q. Write a short note on JDBC Architecture.
JDBC Architecture :
In Java, the technology that enables database access and manipulation is
called Java Database Connectivity (JDBC).
JDBC has two parts:
a. JDBC Core Application Programming Interface (API):java.sql package
b. JDBC Optional Package API.: javax.sql package
The javax.sql package supports connection pooling, distributed transactions,
rowsets, and so on.
The most important members of the java.sql package are as follows:
➢ The DriverManager class ,
➢ The Driver interface ,
➢ The Connection interface,
➢ The Statement interface
➢ The ResultSet interface,
➢ The PreparedStatement interface ,
➢ The ResultSetMetaOata interface
Accessing a database with JDBC can be summarized in the following
four steps:
1. Load the JDBC database driver. 2. Create a connection. 3. Create a
statement.
4. Create a resultset, if you expect the database server to send back some
data.
Step 1: Load a JDBC Database Driver : If you want to access a particular
database, you need to get the JDBC driver for that database. JDBC Drivers
are available for most popular databases like Oracle, Sybase, DB2,
Microsoft SQL Server, MySQL. Drivers are available for Open Database
Connectivity (ODBC), which means that if you can't find a JDBC driver for
a certain database, that database can be connected through ODBC.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 27
Step 2:Creating connection:
➢ After you register a JDBC driver with the DriverManager, you can
use it to get a connection to the database.
➢ In JDBC, database connection is represented by the
java.sql.Connection interface. You.use the DriverManager class's
getConnection method to obtain a Connection object.
Connection connection =
DriverManager.getConnection("jdbc:odbc:MarketingOata",
"sa", "1945");
➢ The Connection object obtained through the DriverManager class's
getConnection method is an open connection you can use to pass your
SQL statements to the database server.
Step 3: Creating a Statement :
➢ After you have a Connection object, you can pass a SQL statement. To
do this, you need to create another JDBC object called Statement.
➢ To create a Statement object from an open Connection object, you
write the following:
Statement statement = connection.createStatement();
➢ Next, use the methods in the Statement class interface to manipulate
your data or data structure. You will use two important methods:
executeUpdate and executeQuery.
The signatures for both methods are as follows:
public int executeUpdate(String sql) throws SQLException
public ResultSet executeQuery(String sql) throws SQLException
Step 4: Creating a ResultSet :
➢ A ResultSet is the representation of a database table that is returned
from a Statement object.
➢ A ResultSet object maintains a cursor pointing to its current row of
data. When the cursor is first returned, it is positioned before the first
row. To access the first row of the ResultSet, you need to call the
next() method of the ResultSet interface.The next() method moves the
cursor to the next row and can return either a true or false value. It
returns true if the new current row is valid; it returns false if there are
no more rows. Normally you use this method in a while loop to iterate
through the ResultSet object.
➢ To get the data from the ResultSet, you can use one of many the
getXXX methods of ResultSet, such as getString getlnt, getLong.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 28
for example:
String sql = "SELECT FirstName, LastName FROM Users";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next())
{
System.out.println(resuItSet.getString(l) + ":" +
resuItSet.getString("LastName") ); .
}
The first column is retrieved by passing its column index, which is 1 for the
first column. The second column is obtained by passing its column name.
Q. List the various steps involved to access a database using JDBC.
Accessing Database : To access and work with a database using JDBC,
the following are the steps involved:
➢ Configuring JDBC Driver
➢ Creating A Database Connection
➢ Executing Queries
➢ Processing The Results
➢ Closing The Database Connection
Configuring JDBC Driver :
➢ The first step to establish a database connection using a JDBC driver
involves loading the specific driver class into the application’s JVM.
This makes the driver available later, when required for opening the
connection.
➢ Class.forName(String).newInstance() is used to load the JDBC driver
class:
➢ Class.forName(“com.mysql.jdbc.Driver”).newInstance();
➢ The above code spec indicates that the JDBC driver from some JDBC
vendor has to be loaded into the application.
➢ Class.forName() is a static method. This instructs the JVM to
dynamically locate, load and link the class specified to it as a
parameter.newInstance() indicates that a new instance of the current
class should be created.
➢ When the driver class is loaded into memory, it creates an instance of
itself and registers with java.sql.DriverManager class as an available
database driver.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 29
Creating A Database Connection
➢ Once the driver is loaded, a database connection needs to be
established.
➢ A database URL identifies a database connection and notifies the
driver manager about which driver and data source is used.
Syntax: [For Database URL]
jdbc:<SubProtocol>:<SubName>
Here,
➢ Jdbc indicates that JDBC is being used to establish the database
connection
➢ SubProtocol is the name of the database the developer wants to
connect to. Example mysql, oracle, odbc and so on
➢ SubName is typically a logical name or alias, which provides
additional information on how and where to connect
The following list represents the syntax for three common JDBC
database URLs. Each type of database driver requires different
information within its URL:
JDBC Database URL Driver Used
MySQL jdbc:mysql://Server[:Port]/Database_Name MySQL
Connector/J
JDBC Driver
Oracle jdbc:oracle:thin:@Server:Port:Instance_Name Oracle Type 4
JDBC Driver
ODBC jdbc:odbc:Data_Source_Name JDBC- ODBC
Bridge Driver
To Create a database connection, the JDBC connection method
getConnection() of DriverManager is used as follows:
Connection con =
DriverManager.getConnection(“jdbc:mysql://localhost/test”, “user”,
“password”);
➢ The method is passed a specially formatted URL that specifies the
database.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 30
➢ The URL used is dependent upon the JDBC driver implemented.
➢ It always begins with jdbc:protocol, but the rest depends upon the
particular vendor. It returns a class that implements
java.sql.Connection interface
➢ Within getConnection(), DriverManager queries each registered driver
until it locates one that recognizes the specified database URL.
➢ Once the correct driver is located, DriverManager uses it to create
Connection object.
➢ While using JDBC, it is required to import java.sql package as the
driver manager, the connection objects and the other JDBC objects are
contained in this package.
***To improve the performance of JDBC, define the database connection as
an instance variable then open the Db connection within the Servlet’s init().
Then the database connection will be established only once i.e. when the
Servlet is first loaded and will be shared across all Db requests thereafter.
Q. List and explain various ways of Executing Queries.
Executing Queries :
After establishing database connection there should be some way to execute
queries. There are three ways of executing a query:
➢ Standard Statement
➢ Prepared Statement
➢ Callable Statement
Standard Statement
The simplest way to execute a query is to use java.sql.Statement class.
To obtain a new statement object createStatement() of Connection
object is used which is written as follows:
Statement stmt= con.createStatement();
➢ Statement objects are never instantiated directly.
➢ A query that returns data can be executed using executeQuery() of
Statement. This method executes the statement and returns
java.sql.ResultSet class that encapsulates the retrieved data.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 31
The following code spec defines ResultSet object that encapsulates the
retrieved data:
ResultSet rs =stmt.executeQuery (“SELECT* FROM Books”);
For inserts, updates or deletes, use executeUpdate(). executeUpdate()
accepts an SQL statement that contains user instructions to insert, update or
delete table data.
Prepared Statement
➢ A prepared Statement is used for an SQL statement, which must be
executed multiple times.
➢ When a prepared statement is created, the SQL statement is sent to the
database for pre-compilation [if this is supported by the JDBC driver].
➢ As they are precompiled, Prepared Statement executes much faster
than standard SQL statements.
Syntax:
PreparedStatement pstmt= con. PrepareStatement(“INSERT INTO
Books(BookNo, Name) VALUES(?,?)”);
**The question marks in the PreparedStatement syntax represent dynamic
query parameters. These parameters can be changed each time the prepared
statement is called.
Callable Statement
➢ Callable Statement is used to execute SQL stored procedures. Methods
are provided to specify input parameters and retrieve return values.
➢ Callable Statement object extends PreparedStatement and therefore,
inherits its methods.
Syntax:
CallableStatement cstmt= con.prepareCall(“{call getBooks(?,?)}”);
Processing The Results
➢ ResultSet object is a cursor [i.e. a specific place in memory], which
holds SQL query output.
➢ Next(), a method that belongs to ResultSet object, can be used to
navigate across data rows in the opened cursor one row at a time,
starting from the topmost row.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 32
➢ ResultSet object also has many other methods for retrieving data from
the current row.getString() and getObject() are among the most
frequently used for retrieving specific column values from a data row.
Syntax:
While(rs.next()){
String event=rs.getString(“event”);
Object count= (Integers) rs. getObject(“count”);
}
***ResultSet is linked to its parent Statement. Therefore, if a Statement is
closed or used to execute another query, any related ResultSet objects are
closed automatically.
When a call is made to getConnection(), DriverManager object queries each
registered driver, if it recognizes the URL. If a driver agrees, the driver
manager uses that driver to create Connection object.
Closing The Database Connection
➢ Since database connections are a valuable application resource and
consume a lot of system resources to create, the DB connection should
be closed only when all table data processing is complete. Connection
object has a built-in method, close() for this purpose.
➢ In addition to closing the database connection, application code spec,
should explicitly close all Statement and ResultSet objects using their
close() methods.
➢ While it is true that the JVM’s built-in garbage collection processes
will eventually release resources that are no longer active, it is always
a good practice to manually release these resources as soon as they are
no longer useful.
Syntax:
rs.close();
stmt.close();
conn.close();
Q. Write a short note on MySQL Connector/J
➢ MySQL provides connectivity to client applications developed in the
Java EE 6 using a JDBC driver named MySQL Connector/J.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 33
➢ MySQL Connector/J is a native java driver that converts JDBC calls
into the network protocol used by the MySQL database.
➢ MySQL Connector/J is a Type 4 driver, which means that MySQL
Connector is pure Java code spec and communicates directly with the
MySQL server using the MySQL protocol.
➢ MySQL Connector/J allows the developers working with Java EE 6,to
build applications which interact with MySQL and connect all
corporate data even in a heterogeneous environment.
➢ Download the MySQL Connector/J JDBC Driver from the website
http://www.mysql.com
Servlet Programs :
Write a simple servlet program that will display the factorial of a given
number Oct’12 Octo’15
Input.html
<html> <head> <title>Factorial</title> </head>
<body>
<form method="get" action="factorialServlet">
Enter a value to find its factorial : <input type="text" name="text1"/>
<input type="submit" value="ok”>
</form>
</body>
</html>
factorialSevlet.java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 34
public class FactorialServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int num = Integer.parseInt(request.getParameter("text1"));
int facto=1;
for(int i=1;i<=num; i++)
{
facto=facto*i;
}
out.println(“Factorical of a number is “ + facto); }
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{ doGet(request,response); }}
Write a servlet program that will read a string from user. If the string
is ‘Examination’ then greet the user otherwise display error message.
Octo’12
Read.html
<html>
<head> <title></title> </head>
<body>
<form method="get" action="ReadDemo">
<pre> Enter String: <input type="text" name="txtname"/>
<input type="submit" value="Submit"/>
</pre>
</form>
</body>
</html>
ReadDemo.java
import java.io.*;
import javax.servlet.ServletException;
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 35
import javax.servlet.http.*;
public class ReadDemo extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response )
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String value=request.getParameter("txtname");
if(value.equals("Examination"))
{ out.println("Welcome to LIIT");
}
else
{ out.println("Plz try different!!!!!!!!!!"); }
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
doGet(request,response);
}}
Write a servlet that prints the sum of square of n integer numbers.
Oct’13
Input.html
<html> <head> <title></title> </head>
<body>
<form method="get" action="Calculate">
<pre> Enter Number: <input type="text" name="txtnum"/>
<input type="submit" value="Calculate"/>
</pre> </form> </body> </html>
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 36
Calculate.java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class calculate extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String value=request.getParameter("txtnum");
out.println(value);
int num=Integer.parseInt(value); int sum=0;
for(int i=1;i<=num;i++)
{ sum=sum+(i*i); }
out.println("sum of squre is: "+ sum);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request,response); }
}
Write a servlet application to find the sum of digits of the number
entered by the user through the HTML form. Oct’14
Input.html.
<html> <head> <title></title> </head>
<body>
<form method="get" action="Calsum">
<pre> Enter Number: <input type="text" name="txtnum"/>
<input type="submit" value="Calculate"/>
</pre> </form> </body> </html>
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 37
Calsum.java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class calculate extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
int number=Integer.parseInt(request.getParameter("txtnum"));
int sum = 0;
int input = number;
while (input != 0) {
int lastdigit = input % 10;
sum += lastdigit;
input /= 10;
}
out.println("Sum of digits of number %d is %d", number, sum);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request,response);
}}
Write a servlet application for simple calculator .
<html>
<head> <title></title> </head>
<body>
<center>
<table border=1>
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 38
<tr> <td>
<center> <h2>Calculator</h2></center>
<form method="post" action="CalculatorServlet">
<pre>
Enter Number1 : <input type="text" name="txtNum1"
size="20" >
Enter Number2 : <input type="text" name="txtNum2"
size="20" >
Chooser Operator :
<select name="op">
<option value="+"> plus</option>
<option value="-"> minus</option>
<option value="*"> multiply</option>
<option value="/"> divide</option>
</select>
<br>
<input type="Submit" Value="Calculate">
</pre>
</form> </td> </tr> /table> </center> </body> </html>
CalculatorServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CalculatorServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("Text/html");
PrintWriter out = response.getWriter();
String op=request.getParameter("op");
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 39
double num1=Double.parseDouble(request.getParameter("txtNum1"));
double num2=Double.parseDouble(request.getParameter("txtNum2"));
double result=0;
if(op.equals("+" ))
result=num1+num2;
else if(op.equals("-"))
result=num1-num2;
else if(op.equals("*"))
result=num1*num2;
else if(op.equals("/"))
result=num1/num2;
else if(op.equals("%"))
result=num1%num2;
out.println("Result :"+result);
out.println("<br><br><a href=myinput.html>Go to Input
file</a></body></html>");
}
}
Write a servlet application for a login page. If the username and
password are correct then it says message “Hello <username>” else a
message “login failed”
Logininput.html
<html>
<body>
<form method="post" action="loginservlet">
<pre>
UserName : <input type="text" name="txtUsername" size="20" >
Password : <input type="password" name="txtPwd" size="20" >
<input type="Submit">
</pre>
</form>
</body>
</html>
loginsrevlet.java
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 40
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class loginservlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("Text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("txtUsername").trim();
String password=request.getParameter("txtPwd").trim();
if(( name.equals("ria"))&& (password.equals("lalita")) )
out.println("Welcome Dear "+ name +"You are a valid user");
else
out.println("Sorry Login Failed !");
}
}
Create a registration servlet in Java using JDBC. Accept the details
such as Username, Password, Email, and Country from the user using
HTML Form and store the registration details in the database.
Regisgtration.html
<html>
<head> <title>Registration Form</title>
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 41
</head>
<body>
<form method=GET action="storedetails">
<pre>
Username : <input type=text name=txtUsername>
Password :<input type="password" name="txtPwd">
Email id : <input type=text name="txtEmail">
Country : <select name="country">
<option value="India"> India </option>
<option value="USA"> USA </option>
<option value="UK"> UK </option>
<option value="Australia"> Australia </option>
<option value="Newzealand"> New zealand
</option>
</select>
<br>
<input type=submit name=Submit > <input type=reset name=Reset>
</pre>
</form> </body></html>
Storedetails.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class storedetails extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doPost(request,response);
}
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 42
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("Text/html");
PrintWriter out = response.getWriter();
try {
String username=request.getParameter("txtUsername");
String pwd=request.getParameter("txtPwd");
String emailid=request.getParameter("txtEmail");
String country=request.getParameter("country");
Following is the connectionstring for Type 1 driver with sql servler
database
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Connection con =
DriverManager.getConnection("jdbc:odbc:Authentication");
Following is the connectionstring for Type 4 driver with mysql
database
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/dbtyit2018","root","r
oot");
PreparedStatement ps=con.prepareStatement("insert into tblusers
Values(?,?,?,?)");
ps.setString(1,username);
ps.setString(2,pwd);
ps.setString(3,emailid);
ps.setString(4,country);
int reccount= ps.executeUpdate();
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 43
if(reccount>0)
out.println("Records added successfully!<br> <br>");
else
out.println("No Records added !<br> <br>");
out.println("<a href=displayDetails>Display All Records</a>");
}catch(Exception e)
{
out.println(e);
}
}
}
Displaydetails.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class displayDetails extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("Text/html");
PrintWriter out = response.getWriter();
try {
Following is the connectionstring for Type 1 driver with sql servler
database
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Connection con =
DriverManager.getConnection("jdbc:odbc:Authentication");
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 44
Following is the connectionstring for Type 4 driver with mysql
database
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost/dbtyit2018","root","r
oot");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from tblusers");
while(rs.next())
{
out.println("Username: "+ rs.getString(1)+"<br>");
out.println("Password : "+ rs.getString(2)+"<br>");
out.println("Emailid : "+ rs.getString(3)+"<br>");
out.println("Country : "+ rs.getString(4)+"<br>");
out.println("<br><br>");
}
}catch (Exception ae){ out.println(ae.getMessage());
} finally { out.close();
}
}
}
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 45
Most Important & Most Expected Questions :
Q. Write a short note on Java Servlet Technology.
Q. Write a short note on Servlet API.
Q. List and explain ServletRequest And ServletResponse Interfaces.
Q. Write a short note on GenericServlet Class.
Q. Write a short note on Requestdispactcher.
Q. Write a short note on HttpServlet Class.
Q. Write a short note on HttpServletRequest And HttpServletResponse
Interfaces.
Q. Write a short note on HttpSession Interface .
Q. Write a short note on Cookies Class.
Q. Write a short note on the Servlet Skeleton.
Q. Write a short note on The Servlet Life Cycle .
Q. Write a short note on JDBC.
Q. Write a short note on JDBC Architecture.
Q. List the various steps involved to access a database using JDBC.
Q. List and explain various ways of Executing Queries.
******Every Question on Every Unit will have at minimum 1 ,
maximum 2 Java Programs .So Study Programs very well.
LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163
TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in
Enterprise Java Notes by Prof Tanuja Parihar 9967271104 46

More Related Content

What's hot

Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...
Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...
Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...tanujaparihar
 
Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...
Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...
Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...Mumbai B.Sc.IT Study
 
Online Quiz System Project Report ppt
Online Quiz System Project Report pptOnline Quiz System Project Report ppt
Online Quiz System Project Report pptKishan Maurya
 
Online Food Ordering System
Online Food Ordering SystemOnline Food Ordering System
Online Food Ordering SystemAnkita Jangir
 
Online Food Ordering System Presentation
Online Food Ordering System PresentationOnline Food Ordering System Presentation
Online Food Ordering System PresentationRohanRajMudvari
 
Real estate management system
Real estate management systemReal estate management system
Real estate management systemSouvikSarkar75
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
Web development ppt
Web development pptWeb development ppt
Web development pptParasJain222
 
Project synopsis on face recognition in e attendance
Project synopsis on face recognition in e attendanceProject synopsis on face recognition in e attendance
Project synopsis on face recognition in e attendanceNitesh Dubey
 
E-Restaurant Management System
E-Restaurant Management SystemE-Restaurant Management System
E-Restaurant Management SystemArno Lordkronos
 
project
projectproject
projectdnraj
 
Hotel management
Hotel managementHotel management
Hotel managementArman Ahmed
 
Online doctor appointment
Online doctor appointmentOnline doctor appointment
Online doctor appointmentAmna Nawazish
 
Online Quiz System Project Report
Online Quiz System Project Report Online Quiz System Project Report
Online Quiz System Project Report Kishan Maurya
 
Hospital management system in java
Hospital management system in javaHospital management system in java
Hospital management system in javaVarun Yadav
 

What's hot (20)

Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...
Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...
Liit tyit sem 5 enterprise java unit 5 important questins with solutions for ...
 
Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...
Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...
Advanced Web Programming (Question Paper) [October – 2018 | Choice Based Syll...
 
Online Quiz System Project Report ppt
Online Quiz System Project Report pptOnline Quiz System Project Report ppt
Online Quiz System Project Report ppt
 
Online quiz system
Online quiz systemOnline quiz system
Online quiz system
 
Online Food Ordering System
Online Food Ordering SystemOnline Food Ordering System
Online Food Ordering System
 
Online Food Ordering System Presentation
Online Food Ordering System PresentationOnline Food Ordering System Presentation
Online Food Ordering System Presentation
 
Real estate management system
Real estate management systemReal estate management system
Real estate management system
 
Food order
Food orderFood order
Food order
 
Restaurant Management System
Restaurant Management SystemRestaurant Management System
Restaurant Management System
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Web development ppt
Web development pptWeb development ppt
Web development ppt
 
Project synopsis on face recognition in e attendance
Project synopsis on face recognition in e attendanceProject synopsis on face recognition in e attendance
Project synopsis on face recognition in e attendance
 
E-Restaurant Management System
E-Restaurant Management SystemE-Restaurant Management System
E-Restaurant Management System
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
HOSPITAL MANAGEMENT SYSTEM project report
HOSPITAL MANAGEMENT SYSTEM project reportHOSPITAL MANAGEMENT SYSTEM project report
HOSPITAL MANAGEMENT SYSTEM project report
 
project
projectproject
project
 
Hotel management
Hotel managementHotel management
Hotel management
 
Online doctor appointment
Online doctor appointmentOnline doctor appointment
Online doctor appointment
 
Online Quiz System Project Report
Online Quiz System Project Report Online Quiz System Project Report
Online Quiz System Project Report
 
Hospital management system in java
Hospital management system in javaHospital management system in java
Hospital management system in java
 

Similar to Liit tyit sem 5 enterprise java unit 1 notes 2018

WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and ServletsRaghu nath
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.pptsindhu991994
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIPRIYADARSINISK
 

Similar to Liit tyit sem 5 enterprise java unit 1 notes 2018 (20)

WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
J servlets
J servletsJ servlets
J servlets
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
Servlet classnotes
Servlet classnotesServlet classnotes
Servlet classnotes
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 

More from tanujaparihar

Mca cet mca entrance test papers for download
Mca cet mca entrance test papers for downloadMca cet mca entrance test papers for download
Mca cet mca entrance test papers for downloadtanujaparihar
 
B sc it syit sem 3 sem 4 syllabus as per mumbai university
B sc it syit sem 3 sem 4 syllabus as per mumbai universityB sc it syit sem 3 sem 4 syllabus as per mumbai university
B sc it syit sem 3 sem 4 syllabus as per mumbai universitytanujaparihar
 
B sc it syit sem 3 python programming notes for download
B sc it syit sem 3 python programming notes for downloadB sc it syit sem 3 python programming notes for download
B sc it syit sem 3 python programming notes for downloadtanujaparihar
 
Bsc it syit sem 3 dbms unit 1 notes for download
Bsc it syit sem 3 dbms unit 1 notes for downloadBsc it syit sem 3 dbms unit 1 notes for download
Bsc it syit sem 3 dbms unit 1 notes for downloadtanujaparihar
 
Mca colleges in_mumbai
Mca colleges in_mumbaiMca colleges in_mumbai
Mca colleges in_mumbaitanujaparihar
 
Mca entrance 2018 syllabus
Mca entrance 2018 syllabusMca entrance 2018 syllabus
Mca entrance 2018 syllabustanujaparihar
 
Mca cet mca entrance classes
Mca cet mca entrance classesMca cet mca entrance classes
Mca cet mca entrance classestanujaparihar
 
Liit tyit sem 5 linux unit 1 2018 most important questions with answers
Liit tyit sem 5 linux unit 1 2018 most important questions with answers Liit tyit sem 5 linux unit 1 2018 most important questions with answers
Liit tyit sem 5 linux unit 1 2018 most important questions with answers tanujaparihar
 
Best techniques to score marks in exams by prof tanuja parihar
Best techniques to score marks in exams by prof tanuja pariharBest techniques to score marks in exams by prof tanuja parihar
Best techniques to score marks in exams by prof tanuja parihartanujaparihar
 
Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...
Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...
Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...tanujaparihar
 
Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...
Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...
Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...tanujaparihar
 
Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions
Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions
Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions tanujaparihar
 

More from tanujaparihar (14)

Mca cet mca entrance test papers for download
Mca cet mca entrance test papers for downloadMca cet mca entrance test papers for download
Mca cet mca entrance test papers for download
 
B sc it syit sem 3 sem 4 syllabus as per mumbai university
B sc it syit sem 3 sem 4 syllabus as per mumbai universityB sc it syit sem 3 sem 4 syllabus as per mumbai university
B sc it syit sem 3 sem 4 syllabus as per mumbai university
 
B sc it syit sem 3 python programming notes for download
B sc it syit sem 3 python programming notes for downloadB sc it syit sem 3 python programming notes for download
B sc it syit sem 3 python programming notes for download
 
Bsc it syit sem 3 dbms unit 1 notes for download
Bsc it syit sem 3 dbms unit 1 notes for downloadBsc it syit sem 3 dbms unit 1 notes for download
Bsc it syit sem 3 dbms unit 1 notes for download
 
NimCet syllabus
NimCet syllabusNimCet syllabus
NimCet syllabus
 
Mca colleges in_mumbai
Mca colleges in_mumbaiMca colleges in_mumbai
Mca colleges in_mumbai
 
Mca entrance 2018 syllabus
Mca entrance 2018 syllabusMca entrance 2018 syllabus
Mca entrance 2018 syllabus
 
Mca cet mca entrance classes
Mca cet mca entrance classesMca cet mca entrance classes
Mca cet mca entrance classes
 
Mah mca cet 2018
Mah mca cet 2018Mah mca cet 2018
Mah mca cet 2018
 
Liit tyit sem 5 linux unit 1 2018 most important questions with answers
Liit tyit sem 5 linux unit 1 2018 most important questions with answers Liit tyit sem 5 linux unit 1 2018 most important questions with answers
Liit tyit sem 5 linux unit 1 2018 most important questions with answers
 
Best techniques to score marks in exams by prof tanuja parihar
Best techniques to score marks in exams by prof tanuja pariharBest techniques to score marks in exams by prof tanuja parihar
Best techniques to score marks in exams by prof tanuja parihar
 
Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...
Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...
Liit tyit sem 5 artificial intelligence unit 1 2018 notes most important ques...
 
Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...
Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...
Liit tyit sem 5 enterprise java unit 4 notes mosst important questions with s...
 
Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions
Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions
Liit tyit sem 5 enterprise java unit 3 2018 imp questions with solutions
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

Liit tyit sem 5 enterprise java unit 1 notes 2018

  • 1. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 1 Q. Write a short note on Java EE Server . Java EE Server : ➢ Java EE Server is a server application that Implements the java EE platform APIs and provides the standard Java EE services. ➢ Java EE Server are sometimes called Application Servers because they allow serving application Data to client, much as how Web Servers serve Web pages to Web Browsers. ➢ Java EE Servers host several application Component type that correspond to the tiers in A multi-tiered application. The Java EE server Provides services to these components in the ➢ Form of Containers as shown in diagram ➢ During the deployment process, installation of Java EE application components takes place in The Java EE Containers on the Java EE Server. Java EE server is used as runtime portion for The execution of application, which contains The EJB and Web containers. Topic : The Need for Dynamic Content, ,Java Servlet Technology .
  • 2. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 2 Q. Write a short note on Java Servlet Technology : Java Servlet Technology : ➢ It is a highly efficient CGI program written in Java. ➢ It is a way to have thin, dynamic web clients. ➢ It is a server-side program that services HTTP requests and returns the results as HTTP responses. ➢ It has a lifecycle and runs inside a JVM at the Web server. ➢ The Servlet's output is delivered to a Web browser. ➢ It is supported by virtually all Web servers and Application Servers ➢ It solves the performance problem by executing all requests as threads in one process ➢ It can easily share resources. ➢ It can be easily ported to other platforms that support Java, as it runs inside aJVM ➢ When a user issues a request for a URL that corresponds to a Java Servlet the server hands the request off to the Servlet for processing. ➢ The Servlet dynamically produces a response to the request, typically an HTML Web page and sends it back to the requesting Web browser. ➢ Java Servlets are efficient, due to an intuitive and automated threading model in which each request is handled by a new lightweight thread. ➢ Servlets are also platform [i.e. hardware] independent . Q. Why Servlets? What can Servlets do? A Servlet is a small, self-contained, portion of code that is executed at the Web Server in response to an HTTP request from a client's browser. Servlets can do the following: ➢ A servlet can process and/ or store data submitted by an HTML form. ➢ A Servlet can provide dynamic content, for example, return the results of a database query to the client ➢ A Servlet can manage state information on top of the stateless HTIP, for example, for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer ➢ Servlets can be used as a plug-in, that features a search engine or semi- customized applications such as web-based banking or inventory systems ➢ A Servlet can handle multiple requests concurrently and these requests can be
  • 3. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 3 synchronized to support systems allowing collaboration between people ➢ Servlets can forward requests to other Servers and Servlets. This allows them to be used to balance load among several servers that mirror the same content ➢ Servlets can maintain and track sessions [either by URL rewriting or cookies]. ➢ Servlets clean up the session precisely when a session is terminated, either by logging off or by a time-out. ➢ Servlets can pass data between themselves . ➢ Servlets can be used to serve as the HTTP speaking middle tier between any kind of thin client and large enterprise services being made available via EJB's Q. Write a short note on Servlet API Java Servlet API : ➢ Java provides a Servlet Application Programming Interface [API] which is a class library [basic classes and interfaces] for implementing Servlets ➢ The Java API forms a standard interface for developing Web application, regardless of the underlying operating system. Without the implementation of Java API it is not possible to develop dynamic applications. This Java API consists of a set of important interfaces that can be implemented in different areas so that developers can conveniently build Java-powered applications. ➢ Servlets can access the entire family of Java APIs. The Java Servlet API is the class library using which requests can be processed and responses can be constructed, dynamically. The API thus helps define the expected interactions of a Web container and a Servlet.
  • 4. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 4 The following are the basic classes and Interfaces used for implementing the Servlet. javax.servlet Package javax.servlet package is the core of the Servlet API. iavax.servlet package includes the basic Servlet interface, which all Servlets must implement in one form or another and an abstract GenericServlet class for developing basic Servlets. This package also includes classes for: Communicating with the host server and client: o ServletRequest o ServleResponse Communicating with the client: o ServletInputStream o ServletOutputStream Q.Write a short note on Servlet Interface.
  • 5. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 5 Servlet Interface : ➢ Servlet interface is a collection of empty method signatures. ➢ A servlet must directly or indirectly [by subclassing the GenericServlet or HttpServlet class] implement the servlet interface. This interface holds method sigantures that bring the following basic Servlet functionalities: ➢ Initializing a Servlet ➢ Handling a client request ➢ Destroying a Servlet The following are the methods available in this interface: Methods Description init () Is used for initializing the servlet parameters provided by the ServletConfig object. Is called only once when the Servlet is first loaded. It is commonly used to initialize resources to be used by a Servlet when requests are received. For example, database or network connections, file initialization and other environment settings. None of the Servlets methods can be called unless the Servlet is initialized using init(). destroy() destroy() is also called only once immediately before the Servlet is unloaded. Is used to clear all retained resources such as database connection, threads, file handles and so on. This method is overridden in order to free up any resources being used by the Servlet service() Is the actual heart of the HTTP Request-Response model. Is called to handle a single client request. A Servlet receives request information through the ServletRequest object and sends data back to the client through the ServletResponse object. getServletConfig() Provides the ServletConfig object for initializing the Servlet’s parameters. getServletInfo() Provides the Servlet metadata such as author, servlet version and other copyright information. This method
  • 6. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 6 needs to be overridden inside the Servlet for it to return the required information. Q. Write a short note on ServletContext Interface . ServletContext Interface : All Servlets belong to one Servlet context. ServletContext can only be called at context initialization time. The ServletContext interface provides a set of methods which allow communicating with the server such as: ❑ Finding path information ❑ Accessing other Servlets running on the server ❑ Writing to the server log file ServletContext allows enabling applications to load Servlets and Filters at runtime that are needed. The following are the methods available in this interface: Methods Description getAttribute() Returns the value of the named server attribute as an Object. getAttributeNames() Returns an Enumeration containing the attribute names available within in the current ServletContext. getContext() Returns a ServletContext object that corresponds to a specified URL on the server. getContextPath() Returns the context path of the web application. getMimeType() Returns the MIME type of the given file. getRealPath() Returns the real file system path of any given virtual path. getServletInfo() Returns the name and version of the servlet container on which the servlet is running. getInitParameter() Returns a String containing the value of the named context-wide initialization parameter
  • 7. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 7 getRequestDispatcher() Returns a RequestDispatcher object that act as a wrapper for the resource located at the given path. setAttribute() Binds an object to a given attribute name in the current ServletContext. removeAttribute() Removes the Attribute with the given name from the current ServletContext Q. Write a short note on ServletContext Interface . ServletConfig Interface : The ServletConfig objects help Servers pass initialization and context information to Servlets such as: ➢ A series of initialization parameters ➢ A servletContext object, which provides information about the server environment The following are the methods available in this interface: Methods Description getInitParameter() Returns the value of the named Servlet initialization parameter. getInitParameterNames() Returns all the servlet’s initialization parameter names as an Enumeration of String objects. getServletContext() Returns the Servlet’s ServletContext object. Q. List and explain ServletRequest And ServletResponse Interfaces. ServletRequest And ServletResponse Interfaces : ➢ When a Servlet accepts a call from a client, it receives two objects, one is a ServletRequest and the other is a ServletResponse.
  • 8. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 8 ➢ ServletRequest interface encapsulates the communication from the client to the server, while ➢ ServletResponse interface encapsulates the communication from the Servlet back to the client. ServletRequest interface allows the Servlet to access information such as: ➢ Names of the parameters passed by the client ➢ The protocol [scheme] such as the HTTP POST and PUT methods being used by the client ➢ The names of the remote host that made the request ➢ The server that received it ➢ An input stream for reading binary data from the request body Subclasses of ServletRequest allow the Servlet to retrieve more protocol- specific data. For example, HttpServletRequest contains methods for accessing HTTP-specific header information. The following are the commonly used methods available in this interface: Methods Description getAttribute() Returns the value of the named attribute as an Object. getParameter() Returns the value of a request parameter as a String. getParametrValues() Returns an array of String objects containing all of the values the given request parameter has. getRequestDispatcher() Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. getServerName() Returns the host name of the server to which the request was sent. removeAttribute() Removes the attribute from this request. setAttribute() Stores an Attribute in this request. ServletResponse interface provides methods to the Servlet for replaying to the client. ServletResponse interface allows Servlet: ➢ To set the content length and mime type of the reply
  • 9. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 9 ➢ Provides an output stream and a Writer Through ServletResponse interface, the Servlet can send the reply data. Subclasses of ServletResponse provide the servlet with more protocol- specific capabilities. For example, HttpServletResponse contains methods that allow the Servlet to manipulate HTTP-specific header information. The following are the commonly used methods available in this interface: Methods Description getOutputStream() Returns a ServleOutputStream suitable for writing binary data in the response. getWriter() Returns a PrintWriter object that can send character text to the client reset() Clears any data that exists in the buffer as well as the status code and headers. Q. Write a short note on GenericServlet Class. GenericServlet Class : ➢ Javax.Servlet.GenericServlet class provides the basic implementation of the Servlet interface. It also implements ServletsConfig interface. ➢ GenericServlet may be directly extended by a Servlent, although it’s more common to extend a protocol-specific subclass such as HttpServlet. ➢ GenericServlet makes writing Servlets easier. ServletInputStream And ServletOutputStream Classes : ➢ ServletInputStream and ServletOutputStream classes are abstract classes that a Servlet container implements. ➢ ServletInputStream class provides an input stream for reading binary data from a client request. ➢ ServletInputStream class is returned by getInputStream () of ServletRequest. ➢ A Servlet that filters binary output from other sources generally receives its input through this stream. The following is the method available in this class: Methods Description readLine() Reads the input stream one line at a time.
  • 10. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 10 ➢ ServletOutputStream class provides an output stream for sending binary data back to a client. ➢ A servlet obtains ServletOutputStream object from getOutputStream () of ServletResponse. The following are the commonly used methods available in this class: Methods Description print () Writes a character to the client, with no carriage return line feed at the end. printIn() Writes a carriage return line feed to the client. Q. Write a short note on Requestdispactcher. RequestDispatcher Interface : ➢ RequestDispatcher interface defines an object that receives requests from the client and sends them to any resource such as a Servlet HTML file or JSP file on the server. ➢ The Servlet container creates RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. ➢ This interface is intended to wrap Servlets, but a Servlet container can create RequestDispatcher objects to wrap any type of resource. The following are the methods available in this interface: Methods Description forward() Forwards a request from a Servlet to another resource such as Servlet, JSP or HTML file on the server. include() Includes the content of a resource such as Servlet, JSP, HTML, file in the response. Q. List and explain The classes and interfaces described so for make up a Basic Servlet. The classes and interfaces described so for make up a Basic Servlet. Javax.servlet.http Package: Javax.servlet.http package is used to develop Servlets that support the HTTP protocol. This package holds specialized classes that help perform tedious tasks such as:
  • 11. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 11 ➢ HttpServlet class includes support for different HTTP request methods and headers ➢ HttpServletRequest and HttpServletResponse interfaces allow additional direct interaction with the web server. (Refer to explaination given above) ➢ HttpSession provides built-in session tracking functionality ➢ Cookie class allows quickly setting up and processing HTTP cookies Q. Write a short note on HttpServlet Class. HttpServlet Class : ➢ HttpServlet inherits basic Servlet functionality by extending GenericServlet class. ➢ HttpServlet is an abstract class that resides in javax.servlet.http package. Because it is abstract, it cannot be instantiate. Rather, when building an HTTP servlet, HttpServlet class must be extended with at least one of its methods implemented. ➢ A functional HTTP Servlet must override at least one of methods typically service(),doGet(), doPost(). Although HttpServlet does not provide the implementation for most of its methods,it does provide a framework for supporting the HTTP protocol. ➢ HTTP Servlets have some additional objects that provide session- tracking capabilities. The Servlet writer can use these APIs to maintain state between the Servlet and the client that persists across multiple connections during some time period. The following are the commonly used methods available in this class: Method Description Service() Handles dispatching requests to the protected, HTTP- specific service () and cannot be overridden disabling dispatching to the handler methods for each HTTP request type. doGet() Is called in response to an HTTP GET request [including conditional GET requests]. Overriding this method to support a GET request also automatically supports an HTTP HEAD request. A HEAD request is a GET request that returns no body in the response, only the request header fields. doPost() Is called in response to an HTTP POST request. The HTTP POST method allows the client to send data of
  • 12. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 12 unlimited length to the Web Server a single time and is useful when posting information such as credit card numbers. Q. Write a short note on HttpServletRequest And HttpServletResponse Interfaces. HttpServletRequest And HttpServletResponse Interfaces : ➢ HttpServletRequest interface provides methods for extracting HTTP parameters from the query string or the request body depending on the type of request such as GET or POST. ➢ HttpServletResponse interface provides an OutputStream for returning binary data such as a GIF or JPEG image and PrintWriter for returning text output. ➢ HttpServletRequest interface extends ServletRequest interface to provide request information for HTTP Servlets. HttpServletResponse interface extends ServletResponse interface to provide HTTP protocol-specific functionality including response headers and status codes. ➢ HttpServletRequest and HttpServletResponse interface give full access to all information about the request and allows controlling the output sent to the client as the response to the request. HttpServletRequest interface includes: ❑ Support for: o Cookies o Session tracking ❑ Access to HTTP header information ➢ HttpServletRequest interface also parses incoming HTTP form data and stores it as Servlet parameters. ➢ HttpServletResponse interface also defines a series of constants that represent various HTTP status codes and includes helper functions for session tracking operations. The following are the commonly used methods available in HttpServletRequest interface: Methods Description getCookies() Returns an array containing all of the Cookie objects the client sent with this request.
  • 13. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 13 getSession() Returns the current session associated with this request or if the request does not have a session, created one. authenticate() Uses the container login mechanism configured for the ServletContext to authenticate the user making this request. This method may modify and commit the argument HttpServletResponse. login() Validates the Provided username and password in the password validation realm used by the Web container login mechanism configured for the ServletContext. The following are the commonly used methods available in HttpServletResponse interface: Method Description addCookie() Adds the specified cookie to the response. encodeURL() Encodes the specified URL by including the session ID in it or if encoding is not needed, returns the URL unchanged. sendRedirect() Sends a temporary redirect response to the client using the specified redirect location URL. setStatus() Sets the status code for this response. Q. Write a short note on HttpSession Interface . HttpSession Interface : ➢ HttpSession interface provides a way to identify a user across more than one page request or visit to a website and to store information about that user. ➢ With the help of the HttpSession interface, a session can be created between an HTTP client and an HTTP server. This session can persist for a specified time period, across more than one connection or page request from the user. ➢ A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs. This interface allows Servlets to: View and manipulate information about a session such as: o The session identifier
  • 14. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 14 o Creation time o Last accessed time Bind objects to sessions, allowing user information to persist across multiple user connection A Servlet obtains an HttpSession object using getSession() of HttpServletRequest. The following are the commonly used methods available in this interface: Method Description getId() Returns a string containing the unique identifier assigned to this session. getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the Servlet container will keep this session open between client accesses. Invalidate() Invalidates this session then unbinds any objects bound to it. isNew() Returns true if the client does not yet know about the session or if the client chooses not to join the session. setMaxInactiveInterval() Specifies the time, in seconds, between client requests before the Servlet container will invalidate this session. Q. Write a short note on Cookies Class. Cookies Class : Cookies are often used for Session management or in situations where it is required to uniquely identify a client. The Cookie class allows Servlets to: ➢ Read, create and manipulate HTTP-style cookies ➢ Store small amounts of data on the client A servlet uses getCookies() of HttpServletRequest to retrieve cookies submitted as part of client request. addCookie() of HttpServletResponse can be used to send a new cookie to the Web Browser. Since cookies are set using HTTP headers, addCookie() must be called before any output is sent to the client.
  • 15. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 15 The following are the commonly used methods available in this class: Method Description getDomain() Returns the domain name set for this cookie. getMaxAge() Returns the maximum age of the cookie, in seconds. By default, -1 indicates that the cookie will persist until browser shutdown. getName() Returns the name of the cookie. getValue Returns the value of the cookie. setDomain() Specifies the domain within which this cookie should be presented. setMaxAge() Sets the maximum age of the cookie in seconds. setValue() Assigns a new value to a cookie after the cookie is created. Q. Write a short note on the Servlet Skeleton. Servlet Skeleton : ➢ According to Sun Microsystems when any Servlet is crafted its code spec must have a standard skeleton. ➢ In its most general form, a Servlet is an instance of a class which implements javax.servlet.Servlet interface. ➢ Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. ➢ Developers use this as a blueprint when crafting their Servlet code. Implementing Servlet interface or extending GenericServlet/HttpServlet classes provides a framework for creating a Servlet as well as significant default functionality. The Servlet’s code spec must override at least one method when my custom functionality is being implemented. In order to initialize a Servlet, the web server: ➢ Loads the Servlet class [and probably other classes which are referenced by the Servlet] and creates an instance by calling the no- args constructor ➢ Calls the Servlet’s init(ServletConfig config) method o Init()is called only once when the Servlet is loaded in memory for the first time and store ServletConfig object. The Servlet creator can encapsulate any code that must run before the main
  • 16. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 16 code spec of the Servlet is executed such as connecting to a database for instance. ➢ ServletConfig object supplies a Servlet with information about its initialization parameters. These parameters are given to the Servlet itself and are not associated with any single request. ServletConfig object can be retrieved by calling the Servlet’s getServletConfig() method. This is handled by GenericServlet. ➢ Any Java enabled Web server automatically invokes the Servlet’s service() method in response to a client request. This means when a Servlet is initialized, its service(ServletRequest request, ServletResponse response) method is called for every request to the Servlet. ➢ Hence, service() must be overridden to provide customized functionality the moment a Servlet is invoked. However, if a Servlet developer chooses not to override service(), there are other methods that can be invoked in response to a client request. ➢ When the Servlet needs to be unloaded for example, because a new version should be loaded or the server is shutting down, destroy() us called. Based on this brief description, a skeleton of a common Servlet has been constructed. For simplicity, the skeleton Servlet that follows does not include parameters passed to its methods or exception handling code for any exceptions that are thrown: 1. public class SkeletonServlet extends HttpServlet { 2. public void init ( ) { 3. /* Initialization code goes here */ 4. } 5. public void service ( ) { 6. /* Meaningful work happens here*/ 7. } 8. public void destroy ( ) { 9. /*Free resources here*/ 10. }
  • 17. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 17 11. } Servlets may or may not implement init() or destroy(). Implementation of these methods is not mandatory. Q. Write a short note on The Servlet Life Cycle . The Servlet Life Cycle : The Servlet lifecycle describes how a Servlet is: ➢ Loaded ➢ Instantiated ➢ Initialized ➢ Services requests ➢ Destroyed ➢ Finally garbage collected
  • 18. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 18 Every Servlet engine must adhere to the Servlet lifecycle. Initialization : ➢ In order to initialize a Servlet, the Servlet engine first locates its class. A Servlet class may reside on the local file system, a remote file system or be some other network resource. The Servlet engine uses the usual Java class loading facilities to load the Servlet class into the JVM. Once loaded, the Servlet engine instantiates an instance of that Servlet class [and probably other classes which are referenced by the Servlet]. ➢ Then it calls the Servlet’s init (Servlet Config config) method. ➢ Init() is called immediately after the Server constructs the Servlet’s instance. Depending on the server and its configuration, this can be called at any of the following cases: ➢ When the Server starts ➢ When the Servlet is first requested, just before service () is invoked. ➢ At the request of the server administrator. Why Not Use A Constructor Instead Of init()? ➢ In the oldest version of Java i.e. JDK 1.0 for which Servlets were originally written, constructors for dynamically loaded Java classes such as Servlets were incapable of accepting arguments. This prevented from providing , a new Servlet, any information about itself and its environment. To overcome this issue, a Server [Servlet engine] had to call a Servlet’s init() method and pass along an object that implements the ServletConfig interface. ➢ Java does not allow interfaces to declare constructors i.e. javax.servlet.Servlet interface cannot declare a constructor that accepts a ServletConfig parameter.It has to declare another method such as init(). ➢ Indirectly one can still define constructors for Servlets, but from within a constructor there is no access to servletConfig object or the ability to throw a ServletException. init() is guaranteed to be called: 1. Before the Servlet handles its first request
  • 19. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 19 2. Only once during the Servlet’s lifecycle init() : init() is declared as follows: public void init (ServletConfig config) throws ServletException During initialization, the Servlet has access to two objects: ➢ ServletConfig ➢ ServletContext This is because to init() an object of ServletConfig is passed as a parameter. When a Servlet is setup for the first time, the configuration data such as information about the parameters and references to the ServletContext is stored in ServletConfig object. The following are the common tasks that can be implemented by overriding init() of Servlet interface: 1. Reading initializing parameters using ServletConfig object 2. Reading configuration data from persistent resources like configuration file 3. Initializing a database driver, a connection pool or logging service 4. Opening a JDBC connection 5. Writing log information to a network resource A servlet that cannot complete its initialization process throws UnavailableException. Only after the completion of initialization, will the server be ready for client requests to handle [i.e.before service() is called] or the Servlet is destroyed. Runtime : After the server loads and initializes the servlet, the Servlet is able to handle client requests. It processes them in service(). Each client’s request to service () is run in separate Servlet thread. service() is declared as follows: public void service (ServletRequest request, Servlet Response response) throws ServletException, IOException
  • 20. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 20 For, every request to the servlet, its service() method is called. Two objects i.e. ServletRequest and ServletResponse are passed as parameters to service. ServletRequest object helps in accessing the original request data and ServletResponse object provides methods that help the Servlet to build a response. Servlets can run multiple service() methods at a time. It is important therefore, that service() be written in a thread-safe manner. For example, if a service () method updates some crucial data in the Servlet object, access to this thread should be synchronized. If for some reason, the server should not run another service() concurrently, the Servlet should implement SingleThreadModel interface. This interface guarantees that no two threads will execute the Servlet’s service() concurrently. Destruction : ➢ When instructed to unload the Servlet, perhaps by the server administrator or programmatically by the servlet itself, the Servlet engine calls the Servlet’s destroy (). The Servlet is then eligible for garbage collection. ➢ All resource which were allocated in init() should be releasedin destroy(). Destroy() is declared as follows: public void destroy () The method is run once. The server will not run it again until after it reloads and reinitializes the Servlet. The common tasks implemented in destroy () are: ➢ Synchronizing cleanup tasks such as closing any open resource, closing a connection pool ➢ Informing another application that Servlet will no longer be in service
  • 21. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 21 ➢ Destroy()is guaranteed to be called only once during the servlet’s lifecycle. ➢ During a servlet’s lifecycle , it is imporatnatn to write thread -safe code for destroying the Servlet and unless the Servlet implements SingelThreadModel interface, serviceing client requests. ➢ There may still be thread that eeccute service when destroy() is called, so destroy() has to be thread -safe. A Simple Welcome Servlet .( Using GenericServlet class & Service Method) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class myGenericServlet extends GenericServlet { public void init() { } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("Text/html"); Server locates and loads the servlet Server instantiate one or more object instances of the servlet class Client request arrives Server initializes the servlet by invoking init() Server delegates the client request to the servlet through service() Service() processes the client request Service() then returns the output to the client Servlet waits until the next client request arrives To free memory resources, the server calls destroy() Servlet is unloaded by the server Diagram 6.2 the servlet lifecycle
  • 22. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 22 PrintWriter out=response.getWriter(); out.println("Welcome to the world of Java!"); } public void destroy() { } } A Simple Welcome Servlet . (Using Service Method ) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.WebServlet; public class WelcomeServ extends HttpServlet { public void init() { } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("Text/html"); PrintWriter out=response.getWriter(); out.println("Welcome to the world of Java!"); } } WelcomeServlet with doGet & doPost Methods and HttpServlet class import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void init() {
  • 23. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 23 } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("Text/html"); PrintWriter out=response.getWriter(); out.println("Welcome to the world of Java in LIIT !"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
  • 24. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 24 Chapter 7 :Working With Servlets Q.Write a short note on Servlets. Servlets : ➢ A servlet is a Java program that must be run by a Java Servlet engine on a Java enabled Web server. The servlet’s output is delivered to a Web browser. ➢ Sun GlassFish Enterprise Server that comes bundled with the NetBeans IDE 6.8 has built-in support for running Java Servlets. This book uses the bundled server to demonstrate and run Servlets. Working with Servlets requires the knowledge of: ➢ What is a web application ➢ The organization of a web application ➢ How to create a Servlet file ➢ Compiling and building the application ➢ Deploying the application ➢ Executing the Servlet/ web application Chapter 8 Working with Databases: What Is JDBC? Q. Write a short note on JDBC. Goal of JDBC is to make possible the following: ➢ Programmers can write applications in the Java programming language to access any database, using standard SQL statements or even specialized extensions of SQL while still following Java language conventions. ➢ Database vendors and database tool vendors can supply the low-level drivers. Thus, they can optimize their drivers for their specific products. Typical Uses of JDBC : The traditional client/server model has a rich GUI on the client and a database on the server (see Figure 4-2). In this model, a JDBC driver is deployed on the client.
  • 25. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 25 However, the world is moving away from client/server and toward a "three- tier model" or even more advanced "n-tier models." In the three-tier model, the client does not make database calls. Instead, it calls on a middleware layer on the server that in turn makes the database queries. The three-tier model has a couple of advantages. ➢ It separates visual presentation (on the client) from the business logic (in the middle tier) and the raw data (in the database). Therefore, it becomes possible to access the same data and the same business rules from multiple clients, such as a Java application or applet or a web form. ➢ Communication between the client and middle tier can occur through HTTP (when you use a web browser as the client), RMI, or another mechanism. ➢ JDBC manages the communication between the middle tier and the back-end database. Client JDBC Database protocol Database server Figure 4-2 A traditional client/server application Figure 4.1 JDBC-to-database communication path Java application JDBC Driver Manger JDBC/ODBC bridge Vendor-supplied JDBC driver ODBC driver Database Database JDBC API JDBC Driver API Client (visual presentation) Middle tier (business logic) JDBC HTTP, RMI, etc… Database protocol Database server
  • 26. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 26 Q. Write a short note on JDBC Architecture. JDBC Architecture : In Java, the technology that enables database access and manipulation is called Java Database Connectivity (JDBC). JDBC has two parts: a. JDBC Core Application Programming Interface (API):java.sql package b. JDBC Optional Package API.: javax.sql package The javax.sql package supports connection pooling, distributed transactions, rowsets, and so on. The most important members of the java.sql package are as follows: ➢ The DriverManager class , ➢ The Driver interface , ➢ The Connection interface, ➢ The Statement interface ➢ The ResultSet interface, ➢ The PreparedStatement interface , ➢ The ResultSetMetaOata interface Accessing a database with JDBC can be summarized in the following four steps: 1. Load the JDBC database driver. 2. Create a connection. 3. Create a statement. 4. Create a resultset, if you expect the database server to send back some data. Step 1: Load a JDBC Database Driver : If you want to access a particular database, you need to get the JDBC driver for that database. JDBC Drivers are available for most popular databases like Oracle, Sybase, DB2, Microsoft SQL Server, MySQL. Drivers are available for Open Database Connectivity (ODBC), which means that if you can't find a JDBC driver for a certain database, that database can be connected through ODBC.
  • 27. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 27 Step 2:Creating connection: ➢ After you register a JDBC driver with the DriverManager, you can use it to get a connection to the database. ➢ In JDBC, database connection is represented by the java.sql.Connection interface. You.use the DriverManager class's getConnection method to obtain a Connection object. Connection connection = DriverManager.getConnection("jdbc:odbc:MarketingOata", "sa", "1945"); ➢ The Connection object obtained through the DriverManager class's getConnection method is an open connection you can use to pass your SQL statements to the database server. Step 3: Creating a Statement : ➢ After you have a Connection object, you can pass a SQL statement. To do this, you need to create another JDBC object called Statement. ➢ To create a Statement object from an open Connection object, you write the following: Statement statement = connection.createStatement(); ➢ Next, use the methods in the Statement class interface to manipulate your data or data structure. You will use two important methods: executeUpdate and executeQuery. The signatures for both methods are as follows: public int executeUpdate(String sql) throws SQLException public ResultSet executeQuery(String sql) throws SQLException Step 4: Creating a ResultSet : ➢ A ResultSet is the representation of a database table that is returned from a Statement object. ➢ A ResultSet object maintains a cursor pointing to its current row of data. When the cursor is first returned, it is positioned before the first row. To access the first row of the ResultSet, you need to call the next() method of the ResultSet interface.The next() method moves the cursor to the next row and can return either a true or false value. It returns true if the new current row is valid; it returns false if there are no more rows. Normally you use this method in a while loop to iterate through the ResultSet object. ➢ To get the data from the ResultSet, you can use one of many the getXXX methods of ResultSet, such as getString getlnt, getLong.
  • 28. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 28 for example: String sql = "SELECT FirstName, LastName FROM Users"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { System.out.println(resuItSet.getString(l) + ":" + resuItSet.getString("LastName") ); . } The first column is retrieved by passing its column index, which is 1 for the first column. The second column is obtained by passing its column name. Q. List the various steps involved to access a database using JDBC. Accessing Database : To access and work with a database using JDBC, the following are the steps involved: ➢ Configuring JDBC Driver ➢ Creating A Database Connection ➢ Executing Queries ➢ Processing The Results ➢ Closing The Database Connection Configuring JDBC Driver : ➢ The first step to establish a database connection using a JDBC driver involves loading the specific driver class into the application’s JVM. This makes the driver available later, when required for opening the connection. ➢ Class.forName(String).newInstance() is used to load the JDBC driver class: ➢ Class.forName(“com.mysql.jdbc.Driver”).newInstance(); ➢ The above code spec indicates that the JDBC driver from some JDBC vendor has to be loaded into the application. ➢ Class.forName() is a static method. This instructs the JVM to dynamically locate, load and link the class specified to it as a parameter.newInstance() indicates that a new instance of the current class should be created. ➢ When the driver class is loaded into memory, it creates an instance of itself and registers with java.sql.DriverManager class as an available database driver.
  • 29. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 29 Creating A Database Connection ➢ Once the driver is loaded, a database connection needs to be established. ➢ A database URL identifies a database connection and notifies the driver manager about which driver and data source is used. Syntax: [For Database URL] jdbc:<SubProtocol>:<SubName> Here, ➢ Jdbc indicates that JDBC is being used to establish the database connection ➢ SubProtocol is the name of the database the developer wants to connect to. Example mysql, oracle, odbc and so on ➢ SubName is typically a logical name or alias, which provides additional information on how and where to connect The following list represents the syntax for three common JDBC database URLs. Each type of database driver requires different information within its URL: JDBC Database URL Driver Used MySQL jdbc:mysql://Server[:Port]/Database_Name MySQL Connector/J JDBC Driver Oracle jdbc:oracle:thin:@Server:Port:Instance_Name Oracle Type 4 JDBC Driver ODBC jdbc:odbc:Data_Source_Name JDBC- ODBC Bridge Driver To Create a database connection, the JDBC connection method getConnection() of DriverManager is used as follows: Connection con = DriverManager.getConnection(“jdbc:mysql://localhost/test”, “user”, “password”); ➢ The method is passed a specially formatted URL that specifies the database.
  • 30. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 30 ➢ The URL used is dependent upon the JDBC driver implemented. ➢ It always begins with jdbc:protocol, but the rest depends upon the particular vendor. It returns a class that implements java.sql.Connection interface ➢ Within getConnection(), DriverManager queries each registered driver until it locates one that recognizes the specified database URL. ➢ Once the correct driver is located, DriverManager uses it to create Connection object. ➢ While using JDBC, it is required to import java.sql package as the driver manager, the connection objects and the other JDBC objects are contained in this package. ***To improve the performance of JDBC, define the database connection as an instance variable then open the Db connection within the Servlet’s init(). Then the database connection will be established only once i.e. when the Servlet is first loaded and will be shared across all Db requests thereafter. Q. List and explain various ways of Executing Queries. Executing Queries : After establishing database connection there should be some way to execute queries. There are three ways of executing a query: ➢ Standard Statement ➢ Prepared Statement ➢ Callable Statement Standard Statement The simplest way to execute a query is to use java.sql.Statement class. To obtain a new statement object createStatement() of Connection object is used which is written as follows: Statement stmt= con.createStatement(); ➢ Statement objects are never instantiated directly. ➢ A query that returns data can be executed using executeQuery() of Statement. This method executes the statement and returns java.sql.ResultSet class that encapsulates the retrieved data.
  • 31. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 31 The following code spec defines ResultSet object that encapsulates the retrieved data: ResultSet rs =stmt.executeQuery (“SELECT* FROM Books”); For inserts, updates or deletes, use executeUpdate(). executeUpdate() accepts an SQL statement that contains user instructions to insert, update or delete table data. Prepared Statement ➢ A prepared Statement is used for an SQL statement, which must be executed multiple times. ➢ When a prepared statement is created, the SQL statement is sent to the database for pre-compilation [if this is supported by the JDBC driver]. ➢ As they are precompiled, Prepared Statement executes much faster than standard SQL statements. Syntax: PreparedStatement pstmt= con. PrepareStatement(“INSERT INTO Books(BookNo, Name) VALUES(?,?)”); **The question marks in the PreparedStatement syntax represent dynamic query parameters. These parameters can be changed each time the prepared statement is called. Callable Statement ➢ Callable Statement is used to execute SQL stored procedures. Methods are provided to specify input parameters and retrieve return values. ➢ Callable Statement object extends PreparedStatement and therefore, inherits its methods. Syntax: CallableStatement cstmt= con.prepareCall(“{call getBooks(?,?)}”); Processing The Results ➢ ResultSet object is a cursor [i.e. a specific place in memory], which holds SQL query output. ➢ Next(), a method that belongs to ResultSet object, can be used to navigate across data rows in the opened cursor one row at a time, starting from the topmost row.
  • 32. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 32 ➢ ResultSet object also has many other methods for retrieving data from the current row.getString() and getObject() are among the most frequently used for retrieving specific column values from a data row. Syntax: While(rs.next()){ String event=rs.getString(“event”); Object count= (Integers) rs. getObject(“count”); } ***ResultSet is linked to its parent Statement. Therefore, if a Statement is closed or used to execute another query, any related ResultSet objects are closed automatically. When a call is made to getConnection(), DriverManager object queries each registered driver, if it recognizes the URL. If a driver agrees, the driver manager uses that driver to create Connection object. Closing The Database Connection ➢ Since database connections are a valuable application resource and consume a lot of system resources to create, the DB connection should be closed only when all table data processing is complete. Connection object has a built-in method, close() for this purpose. ➢ In addition to closing the database connection, application code spec, should explicitly close all Statement and ResultSet objects using their close() methods. ➢ While it is true that the JVM’s built-in garbage collection processes will eventually release resources that are no longer active, it is always a good practice to manually release these resources as soon as they are no longer useful. Syntax: rs.close(); stmt.close(); conn.close(); Q. Write a short note on MySQL Connector/J ➢ MySQL provides connectivity to client applications developed in the Java EE 6 using a JDBC driver named MySQL Connector/J.
  • 33. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 33 ➢ MySQL Connector/J is a native java driver that converts JDBC calls into the network protocol used by the MySQL database. ➢ MySQL Connector/J is a Type 4 driver, which means that MySQL Connector is pure Java code spec and communicates directly with the MySQL server using the MySQL protocol. ➢ MySQL Connector/J allows the developers working with Java EE 6,to build applications which interact with MySQL and connect all corporate data even in a heterogeneous environment. ➢ Download the MySQL Connector/J JDBC Driver from the website http://www.mysql.com Servlet Programs : Write a simple servlet program that will display the factorial of a given number Oct’12 Octo’15 Input.html <html> <head> <title>Factorial</title> </head> <body> <form method="get" action="factorialServlet"> Enter a value to find its factorial : <input type="text" name="text1"/> <input type="submit" value="ok”> </form> </body> </html> factorialSevlet.java import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.*;
  • 34. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 34 public class FactorialServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int num = Integer.parseInt(request.getParameter("text1")); int facto=1; for(int i=1;i<=num; i++) { facto=facto*i; } out.println(“Factorical of a number is “ + facto); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }} Write a servlet program that will read a string from user. If the string is ‘Examination’ then greet the user otherwise display error message. Octo’12 Read.html <html> <head> <title></title> </head> <body> <form method="get" action="ReadDemo"> <pre> Enter String: <input type="text" name="txtname"/> <input type="submit" value="Submit"/> </pre> </form> </body> </html> ReadDemo.java import java.io.*; import javax.servlet.ServletException;
  • 35. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 35 import javax.servlet.http.*; public class ReadDemo extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String value=request.getParameter("txtname"); if(value.equals("Examination")) { out.println("Welcome to LIIT"); } else { out.println("Plz try different!!!!!!!!!!"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }} Write a servlet that prints the sum of square of n integer numbers. Oct’13 Input.html <html> <head> <title></title> </head> <body> <form method="get" action="Calculate"> <pre> Enter Number: <input type="text" name="txtnum"/> <input type="submit" value="Calculate"/> </pre> </form> </body> </html>
  • 36. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 36 Calculate.java import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.*; public class calculate extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String value=request.getParameter("txtnum"); out.println(value); int num=Integer.parseInt(value); int sum=0; for(int i=1;i<=num;i++) { sum=sum+(i*i); } out.println("sum of squre is: "+ sum); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } Write a servlet application to find the sum of digits of the number entered by the user through the HTML form. Oct’14 Input.html. <html> <head> <title></title> </head> <body> <form method="get" action="Calsum"> <pre> Enter Number: <input type="text" name="txtnum"/> <input type="submit" value="Calculate"/> </pre> </form> </body> </html>
  • 37. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 37 Calsum.java import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.*; public class calculate extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); int number=Integer.parseInt(request.getParameter("txtnum")); int sum = 0; int input = number; while (input != 0) { int lastdigit = input % 10; sum += lastdigit; input /= 10; } out.println("Sum of digits of number %d is %d", number, sum); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }} Write a servlet application for simple calculator . <html> <head> <title></title> </head> <body> <center> <table border=1>
  • 38. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 38 <tr> <td> <center> <h2>Calculator</h2></center> <form method="post" action="CalculatorServlet"> <pre> Enter Number1 : <input type="text" name="txtNum1" size="20" > Enter Number2 : <input type="text" name="txtNum2" size="20" > Chooser Operator : <select name="op"> <option value="+"> plus</option> <option value="-"> minus</option> <option value="*"> multiply</option> <option value="/"> divide</option> </select> <br> <input type="Submit" Value="Calculate"> </pre> </form> </td> </tr> /table> </center> </body> </html> CalculatorServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CalculatorServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("Text/html"); PrintWriter out = response.getWriter(); String op=request.getParameter("op");
  • 39. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 39 double num1=Double.parseDouble(request.getParameter("txtNum1")); double num2=Double.parseDouble(request.getParameter("txtNum2")); double result=0; if(op.equals("+" )) result=num1+num2; else if(op.equals("-")) result=num1-num2; else if(op.equals("*")) result=num1*num2; else if(op.equals("/")) result=num1/num2; else if(op.equals("%")) result=num1%num2; out.println("Result :"+result); out.println("<br><br><a href=myinput.html>Go to Input file</a></body></html>"); } } Write a servlet application for a login page. If the username and password are correct then it says message “Hello <username>” else a message “login failed” Logininput.html <html> <body> <form method="post" action="loginservlet"> <pre> UserName : <input type="text" name="txtUsername" size="20" > Password : <input type="password" name="txtPwd" size="20" > <input type="Submit"> </pre> </form> </body> </html> loginsrevlet.java
  • 40. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 40 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class loginservlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("Text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("txtUsername").trim(); String password=request.getParameter("txtPwd").trim(); if(( name.equals("ria"))&& (password.equals("lalita")) ) out.println("Welcome Dear "+ name +"You are a valid user"); else out.println("Sorry Login Failed !"); } } Create a registration servlet in Java using JDBC. Accept the details such as Username, Password, Email, and Country from the user using HTML Form and store the registration details in the database. Regisgtration.html <html> <head> <title>Registration Form</title>
  • 41. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 41 </head> <body> <form method=GET action="storedetails"> <pre> Username : <input type=text name=txtUsername> Password :<input type="password" name="txtPwd"> Email id : <input type=text name="txtEmail"> Country : <select name="country"> <option value="India"> India </option> <option value="USA"> USA </option> <option value="UK"> UK </option> <option value="Australia"> Australia </option> <option value="Newzealand"> New zealand </option> </select> <br> <input type=submit name=Submit > <input type=reset name=Reset> </pre> </form> </body></html> Storedetails.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class storedetails extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }
  • 42. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 42 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("Text/html"); PrintWriter out = response.getWriter(); try { String username=request.getParameter("txtUsername"); String pwd=request.getParameter("txtPwd"); String emailid=request.getParameter("txtEmail"); String country=request.getParameter("country"); Following is the connectionstring for Type 1 driver with sql servler database // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Connection con = DriverManager.getConnection("jdbc:odbc:Authentication"); Following is the connectionstring for Type 4 driver with mysql database Class.forName("com.mysql.jdbc.Driver"); Connection con= DriverManager.getConnection("jdbc:mysql://localhost/dbtyit2018","root","r oot"); PreparedStatement ps=con.prepareStatement("insert into tblusers Values(?,?,?,?)"); ps.setString(1,username); ps.setString(2,pwd); ps.setString(3,emailid); ps.setString(4,country); int reccount= ps.executeUpdate();
  • 43. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 43 if(reccount>0) out.println("Records added successfully!<br> <br>"); else out.println("No Records added !<br> <br>"); out.println("<a href=displayDetails>Display All Records</a>"); }catch(Exception e) { out.println(e); } } } Displaydetails.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class displayDetails extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("Text/html"); PrintWriter out = response.getWriter(); try { Following is the connectionstring for Type 1 driver with sql servler database // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Connection con = DriverManager.getConnection("jdbc:odbc:Authentication");
  • 44. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 44 Following is the connectionstring for Type 4 driver with mysql database Class.forName("com.mysql.jdbc.Driver"); Connection con= DriverManager.getConnection("jdbc:mysql://localhost/dbtyit2018","root","r oot"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from tblusers"); while(rs.next()) { out.println("Username: "+ rs.getString(1)+"<br>"); out.println("Password : "+ rs.getString(2)+"<br>"); out.println("Emailid : "+ rs.getString(3)+"<br>"); out.println("Country : "+ rs.getString(4)+"<br>"); out.println("<br><br>"); } }catch (Exception ae){ out.println(ae.getMessage()); } finally { out.close(); } } }
  • 45. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 45 Most Important & Most Expected Questions : Q. Write a short note on Java Servlet Technology. Q. Write a short note on Servlet API. Q. List and explain ServletRequest And ServletResponse Interfaces. Q. Write a short note on GenericServlet Class. Q. Write a short note on Requestdispactcher. Q. Write a short note on HttpServlet Class. Q. Write a short note on HttpServletRequest And HttpServletResponse Interfaces. Q. Write a short note on HttpSession Interface . Q. Write a short note on Cookies Class. Q. Write a short note on the Servlet Skeleton. Q. Write a short note on The Servlet Life Cycle . Q. Write a short note on JDBC. Q. Write a short note on JDBC Architecture. Q. List the various steps involved to access a database using JDBC. Q. List and explain various ways of Executing Queries. ******Every Question on Every Unit will have at minimum 1 , maximum 2 Java Programs .So Study Programs very well.
  • 46. LIIT Coaching Classes for T.Y.I.T. , T.Y. B.Sc. Comp Sc & MCA Entrance Contact : 9967271104 / 9619607163 TYIT Sem 5 Enterprise Java Unit 1 Imp Questions www.liit.org.in Enterprise Java Notes by Prof Tanuja Parihar 9967271104 46