Professional Documents
Culture Documents
EA software services include online shopping and payment processing, interactive product
catalogs, computerized billing systems, security, content management, IT service management,
content switching modules, resource planning, business intelligence, human resource
management, manufacturing, application integration, forms automation, sales force
automation, enterprise resource planning and business process management.
Java platform consists of a Java Virtual Machines and implementations of standard libraries.
To develop the applications for different types of system , there are now three version of the java
Platform:
i) Used for developing and running distributed multi –tier architecture java applications .
ii) These applications are mostly modular software components running on an application
server.
Its Core component is Enterprise Java Beans(EJBs), followed by Java Server Pages (JSPs) and Java Servlet
Pages and Java Servlets and a variety of interfaces for linking to the information resources in the
enterprise. Java EE includes several API Specifications such as JDBC, RMI, Java Mail, Java Mesagging
System, Web services , XML and so on and defines how to Coordinate them.
Java EE Technologies:
Web Application Technologies:
Java Servlet
A servlet is a program that extends the functionality of a web server . Servlet receives a Request
from a client, dynamically generate the response and then send the response containing an
HTML or XML document to the client.
Java Server Pages
Java server pages technology helps to generate dynamic content for a web client. A JSP is a text based
document that contains two types of text:
Static Data
JSP Elements
It encapsulates core functionality of JSP Applications. This technology allows creating a standard
set of tags, instead of mixing tags from numerous vendors in a JSP Application.
JavaServer Faces
Facelets
It refers to java server Faces view definition Framework which is a page declaration language developed
for use with java server technology.
JMS API is a messaging standard that allows javaEE application components to create, send ,
receive and read messages.
Java Mail
It includes Java Mail with a service provider interface that allows application components to
send mails.
Java API for RESTful web services defines APIs for the development of web services built
according to the REST architectural style.
Java API for XML Based web services provides support for web services using the SOAP/HTTP
Protocol.
Security Technologies
JACC
Java Authorization Contract for Containers specification defines a contract between a Java EE
application server and an authorization policy provider. It enable services to authenticate and
enforce access controls upon users.
JASPIC
Java Authentication service provider Interface for Containers specification defines a Service
Provider Interface by which authentication providers that implement message message
authentication mechanisms may be integrated in client or server message processing
containers or runtimes.
Glassfish Server
GlassFish is an Application Server which can also be used as a Web Server (Http Server).
A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.
An Application Server (e.g. GlassFish) means: It can manage Java EE applications (usually
both servlet/JSP and EJBs).
Applications are developed to support companies in their business operations. They take data as
input, process the data based on business rules and provide data or information as output. Based
on this fact, all applications have three elements:
1. The User Interface or the presentation element through which data is taken as input
2. The Application Logic or the business rule element, which helps in implementing the
operations to be performed on the data input
3. The Data Storage or the data management element, which manages the storage and
retrieval of data
These three elements form the core of all application architecture used in Commercial
Application Development.
As a developer, before deciding on the number of tiers in application architecture, the following
factors must be considered:
Advantages:
The simplest and least expensive alternative
Less equipment to purchase and maintain
Disadvantages:
1. This type of implementation is lower security and the lack of scalability. An architecture
is scalable when it can be easily expanded or augmented to meet increasing performance
needs
2. Having all of the site's major components and data on a single computer behind the
domain firewall leaves the site more vulnerable to malicious attacks
3. Running all of the site's components on a single computer also limits expansion and
optimization possibilities
If the developer knows that the application will not grow over time, then the developer may
decide to use single tier architecture.
2. Server- Used to store and access business data, captured by the user interface run on the
Client in a data store at the Server
The Server is always a more powerful machine as it has to service multiple client requests to
store or retrieve data.
In other words, the client machine gets the data from the user and passes it to the server for
processing whereas the server validates the input data based on business rules and accordingly
the data is updated in the database.
Advantages:
Adds additional security by removing sensitive customer data from the single computer
Having the database on a separate computer improves the overall performance of the site
Allows optimizing each machine for more specific performance requirements
Disadvantages:
This architecture is the evolution of two tier applications. Logically the application is divided
into three constituent layers:
User Services - Presentation Layer: Provides service such as the Graphical User Interface
and other automation tasks that the application has to perform
Business Services - Business Layer: Implements business rules. This layer encapsulates
the business logic from users such that they need not know how business logic is applied.
When business is upgraded, only the business layer is affected and must be upgraded, the
rest of the application services can remain untouched
Data Services - Data Layer: Provides data availability and integrity. It is responsible for
adding, modifying and deleting data from the data store
This architecture, while it is the most expensive, is the most secure and scalable of the three
options.
Since, the Business Layer has been moved from the Presentation Layer, it reduces the security
risk.
As usage on the site grows, additional Business Layer can be added and the application can be
cloned across multiple computers.
Each of the three layers can now be optimized for peak operating efficiencies.
The main functions of:
4. Multi-Tier Architecture
Today the industry appears to be rapidly moving towards multi-tier architecture. Multi-tier
architecture does not prevent the use of the two or three-tiered architecture.
Depending on the scale of the application and the requirements for access to data, two or three-
tiered architecture is often used for department specific applications.
Java EE architecture is based on the notion of Multi-tier applications. Java EE makes it very easy
to build industrial-strength applications based on two, three or more application layers and
provides all that is required to make this possible.
User Interface Tier: Handles the user's interaction with the application. It could be a web
browser run through a firewall, a heavier desktop application or even a wireless device .
Presentation Tier: Defines what the user interface displays and how a user's requests are
handled depends on what user interfaces are supported, a need may arise to have slightly
different versions of the presentation logic to handle each client appropriately. This is the layer
that provides an interface for the end user to the application data manipulation code spec
Business Tier: This is where the brains of the application reside. It contains stuffs such the
business rules, business data manipulation and so on. For example: If a Payroll system is created
and a need arises to ensure that no employee is paid a wage below a pre-specified minimum
wage, then this logic is placed in the business layer. This layer does not know anything about
HTML nor does it output it. It does not even care about Databases/tables or SQL. It really should
not have any code to access databases/tables. These tasks are assigned to corresponding layers
either above or below the Business tier
Infrastructure Services: Provides additional functionality which are required by the application
components such as messaging transactional support and so on
Integration Tier / Data Access Tier: Is responsible for providing access to backend resources
including powerful relational databases and external systems. This layer is where generic
methods to interface with the data store are written. This layer contains no data business rules or
data manipulation or transformation logic. It is merely a reusable interface to a database engine
and through the engine business data stored in related tables
Data Tier: Since this has been deemed the Age of Information and since all information needs to
be stored, the Data tier is an essential part of any commercial application. Developing a system
without a data tier is possible but for most applications the data tier must exist. Basically, the
Data tier could be a DBMS such as SQL Server, M.S. Access, Oracle, MySQL, Plain text files
(binary files) and so on. This layer is only intended to deal with the storage and retrieval of
business data. It does not care about how plans are made on manipulating or delivering this data
to the requester
Enterprise Architecture
Java EE platform is designed to help developers create large-scale multi-tiered salable reliable
and securer network applications. A distributed multi-tier application model can be described as
an enterprise application as these applications are designed to solve the problems encountered by
large enterprises
Large corporations
Agencies of an enterprise
Governments
However, in an increasingly networked world, the benefits application are helpful, even
essential, for:
Individual developers
Small organizations
Application logic is divided into components according to functions and the various application
components put together make up the enterprise application. These components are physically
installed on different computers, at different physical locations, depending on the tier in the
multi-tiered environment to which the application component belongs. All components work
together in harmony across the enterprise.
4. Enterprise Information System (EIS) Tier Software run on the Database Server
Machine
The Client Tier
The Client Tier consists of a client program that makes requests to the Web Tier.
Web Client
A web client consists of:
Dynamic web pages containing various types of markup language such as HTML, XML
and so on, which are generated by web components running in the web tier
A web browser, which renders the pages received from the server
In fact, such heavyweight operations are off-loaded to enterprise beans executing on the Java EE
server, where they can leverage the security, speed, services and reliability of Java EE server-
side technologies.
1. Application Client
An application client runs on a client machine and provides a way for users to handle tasks that
require a richer user interface than cannot be provided by a markup language.
It typically has a Graphical User Interface (GUI) created from Swing or Abstract Window
Toolkit (AWT) API, but a command-line interface is certainly possible.
Application clients directly access enterprise beans running in the business tier. An application
client can open an HTTP connection to establish communication with a Servlet running in the
web tier. Application clients written in languages other than Java can interact with Java EE
servers, enabling the Java EE platform to interoperate with legacy systems, clients and non-Java
languages.
The Web Tier consists of components that handle the interaction between clients and the
business tier.
The Web Tier usually performs the following tasks:
Dynamically generate content in various formats for the client
Collect input from the client and return appropriate results from the components in the
Business Tier
Control the flow of screens or pages on the client
Maintain the state of data for a user's session
Perform some basic logic and hold some data temporarily in JavaBeans components
Servlets: Are Java programming language classes that dynamically process requests and
constructs responses
JavaServer Pages [SP]: Are text-based documents that execute as Servlets but allow a more
natural approach to creating static content
JavaServer Faces [JSF]: A user-interface component framework for Web applications that
allows including:
UI components such as fields and buttons on a page
Convert and validate UI component data
Save UI component data to server-side data stores
Maintain component state
JavaServer Faces Facelets: Are a type of JavaServer Faces applications that use XHTML pages
rather than JSP pages
Expression Language: A set of standard tags used in JSP and Facelets pages to refer to Java EE
components
JavaServer Pages Standard Tag Library [JSTL]: A tag library that encapsulates core
functionality common to JSP pages
JavaBeans Components: Are objects that act as temporary data stores for the pages of an
application
The Business Tier
In a well-designed enterprise application, the core functionality often exists in the Business Tier.
The Business Tier consists of components that provide the business logic for an application
Business logic is code that provides functionality to a particular business domain such as
banking, retail , finance or an e-commerce site. In Java EE, the business logic is handled by
Enterprise Beans.
An enterprise bean:
Receives data from the client program
Processes it, if necessary
Sends it to the Enterprise Information System Tier for storage
Retrieves data from storage
Processes it, if necessary
Sends it back to the client program
These resources typically are located on a separate machine than the Java EE server and are
accessed by components on the Business Tier.
For example, Java EE application components might need access to enterprise information
systems for database connectivity.
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 servers are sometimes called Application Servers because they allow serving application
data to clients, much as Web Servers serve web pages to Web Browsers.
Java EE servers host several application component types that correspond to the tiers in a multi-
tiered application. The Java EE server provides services to these components in the form of a
Container
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 the runtime portion for the
execution of an application, which contains the EJB and Web containers.
Java EE Containers
Database
Writing multi-tiered applications that run on thin clients is quite time consuming, because a host
of issues, taken for granted on thick clients have to be coded for. These issues would be
transaction and state management, multithreading, resource pooling and so on. Java architecture
changes this, making Java EE applications easy to write, because business logic is organized into
reusable components.
For every component type, Java EE server provides a container that takes care of these
application services. Since application developers need not develop these services themselves
they are free to concentrate on solving application to business process mapping issues.
Containers are like interfaces connecting them with the low-level platform specific component
that is first assembled into Java EE Module and deployed into its container. Then only the
component can be executed.
A Java EE runtime container is built to automatically provide services such as security and
transaction management to appropriate code spec that is run within them.
Assembling an application requires the crafting of a business logic component that is run within
a container and then specifying container settings for each such component and for the overall
Java EE application itself. These settings customize the underlying support provided by the Java
EE server bound to security, transaction management, Java Naming and Directory lookups,
remote connectivity and so on.
Java EE application components use the protocols and methods of the container to access other
application components and services provided by the Java EE server. The Java EE application
server provides an application client container, an applet container, a web container and an EJB
container.
Allows configuring a web component or enterprise bean so that only authorized users can
access the system resources
Allows specifying relationships among methods that make up a single transaction so that
all methods in one transaction are treated as a single unit
Provides a unified interface to multiple naming and directory services in the enterprise so
that application components can access these services
Manage low-level communications between clients and enterprise beans. After an
enterprise bean is created, a client invokes methods on it as if it were in the same virtual
machine
The container also manages non-configurable services such as enterprise bean and Servlet
lifecycles, database connection resource pooling, data persistence and access to the Java EE
platform APIs.
Container Types
The deployment process installs Java EE application components in the Java EE containers
EJB container is responsible for spawning the EJB on demand, binding the EJB to an appropriate
naming service so that other applications can find and use the EJB. This approach ensures that
only authorized clients have access to the EJB's methods. Additionally, the EJB container takes
care of such things as persistent storage, EJB state caching as well as activating and passivating
the bean on demand.
EJB container is responsible for managing the execution of the enterprise beans containing the
business logic tier of the Java EE application.
Web Container
A Java EE container that hosts web applications is a Web Container.Web container provides the
underlying services for managing and executing web components. A web container extends a
Java enabled Web server's functionality by providing developers the environment to run Servlets,
JSPs, JSFs, JSTLs, Listeners, Filters and so on.
It is responsible for instantiating, initializing and invoking Servlets and supporting the HTTP and
HTTPS protocols. It is the container used to feed web pages to client browsers.
Application Client Container provides client components. Application clients services required
for the execution of application and their container run on the client,
Applet Container
Applet Container is provided by the majority of the Web browsers for the execution of applets.
When applets are developed, the visual aspect of the application is given more priority while the
applet container gives a secure environment.
The applet container uses a sandbox security model where code executed in the sandbox is not
allowed to play outside the sandbox i.e. the container prevents any code downloaded to the local
computer from accessing local system resources such as processes or files.
Servlet
The Need For Dynamic Content
In the earlier days, web pages were static i.e a user requests a resource (such as a web page, an
image, a video and so on) and the server returns it. However, with the growth of in the earlier
days, web pages were static i.e. a user requests a resource (such as a web page, commercial
activities on the Web and the rapid spread and adoption of the World Wide Web as a network
without geographical boundaries, companies wanted to deliver dynamic to their customers such
as:
Displaying bank account details
Performing bank transactions
Booking tickets
Weather reports
News headlines
And during those days, the only way dynamic data could be rendered to the Web was using
Common Gateway Interface (CGI). CGI programs provide a relatively simple way to create Web
applications that accepts user input, queries a database and returns relevant results back to the
Web browser.
Being the most common of the web technologies, almost every leading Web server in existence
today provides support for CGI programs. A CGI program can be written in many languages
such as C, C++, VB Script, TCL, REXX, Python, Icon, AppleScript, although the most popular
language for CGI programming is PERL.
Disadvantages In CGI
The biggest disadvantage of CGI programming is lack of scalability and reduced speed.
Each time a request is received by the Web server, an entirely new process thread is
created
It was platform dependent
A process thread consumes a lot of server side resources especially in multi-user situation
Difficult for beginners to program modules in this environment
Sharing resources such as database connections between scripts or multiple calls to the
same script was not available, leading to repeated execution of expensive operations
Alternatives To CGI
Several alternatives (proprietary APIs) of CGI came into picture.
FastCGI a mod_perl
Common Gateway Interface (CGI]
NSAPI
ISAPI
Java Servlets
Most of these had relatively better performance and scalability support. However, it was the Java
Servlets Technology which actually replaced CGI almost entirely.
Sun introduced Servlets la highly efficient CGI program written in Java) as a way to have thin,
dynamic web clients. Servlet was introduced as Java's solution to the issues of CGI and other
proprietary APIs.
A lava Servlet is a server-side program that services HTTP requests and returns the results as
HTTP responses. A good analogy for a Servlet is a non-visual applet that runs on a Web server.
It has a lifecycle similar to that of an applet and runs inside a JVM at the Web server.
A Servlet:
Is a module written using Java that runs in a server application (hence the name Servlets,
similar to Applets on the client side) to answer client requests
Is most commonly used with HTTP and the word Servlet is often used in the meaning of
HTTP Servlet
Is supported by virtually all Web servers and Application Servers
Solves the performance problem by executing all requests as threads in one process
Can be easily ported to other platforms that support Java, as it runs inside a JVM
Can easily share resources
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, they run using a set of standard interfaces
(that make up the Servlet engine) and a JVM. It is the JVM that is built to run on a specific
hardware platform.
Thus if a JVM exists for a specific hardware platform any Servlet crafted and validated on any
other hardware platform will run successfully.
Java Servlets provide an object-oriented and extensible middle tier for Web Server based
applications. Servlets can access all of the enterprise Java APIs such as INDI, JDBC, RMI and
Enterprise JavaBeans and so on.
Web servers generally cannot talk to databases. Hence, a Web server alone cannot dynamically
create web page content using data held in a database table. Even if there is a a large amount of
legacy data in a database table, this information cannot be made accessible to public through the
Web server, Internet and Browser combination.
This is where Servlets, [i.e. basically Java .class files] help extend the functionality of a Web
server. Web servers use the Servlet's ability to access a database table, extract table data and
convert this data into a format acceptable to a Web server for delivery to a client's browser
through the Internet.
Servlet Clients
Even though Servlets are written in Java, their clients may not necessarily be written in Java.
Servlet clients [i.e. an application that consumes the output of a Servlet) can be written in any
desired language. This simply means that Servlets are used in the middle tiers of distributed
application systems. Servlets can in turn be clients to other services, which are written in some
other language.
Servlet Container
A Servlet Container (i.e. the Servlet Engine) provides the runtime environment in which a
Servlet executes. The Servlet engine manages the lifecycle of Servlets from the moment they are
spawned until they are destroyed. The Servlet engine exposes an API based on the version of the
Servlet specification that it implements.
Servlets are supported by several Web servers such as Apache, Netscape, Microsoft IIS and
others.
Since Servlets run within a Web server's namespace they do not display a graphical interface to a
user. A Servlet's work is done behind the scene i.e. working with a Web server. Only the results
of a Servlet's processing (table data converted to suitably formatted HTML) are returned to a
client's browser.
Why Servlets?
Are loaded into memory once and run from memory thereafter
Are a powerful object-oriented abstraction of HTTP and platforms
Are tightly integrated with the Web server
Run within the secure and reliable scope of a Java Virtual Machine [JVM]
Provide direct Database Access using native and ODBC based DB drivers
Being on the Server-side provides code protection
Are supported by several Web servers
Are spawned as a thread, not as a process
Are portable across multiple Web servers
Are simple to design and implement
Service client requests efficiently
Obey the rules of a standard Servlet API
Return vanilla HTML to the requesting Browser
Are robust, scalable, secure CGI Replacement
There are given 6 steps to create a servlet example. These steps are required
for all the servers.
Here, we are going to use apache tomcat server in this example. The steps are
as follows:
DemoServlet.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10.
11. //writing html in the stream
12. pw.println("<html><body>");
13. pw.println("Welcome to servlet");
14. pw.println("</body></html>");
15.
16. pw.close();//closing the stream
17. }}
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>
Servlet API and Lifecycle: Java Servlet API, The Servlet Skeleton, The Servlet Life Cycle, A
Simple Welcome Servlet
Servlet API And Lifecycle
Now that the concept of Servlet is in place, let's move one step further and understand the basic
classes and interfaces that Java provides to deal with Servlets,
Java provides a Servlet Application Programming Interface (API) which is a class library (basic
classes and interfaces] for implementing Servlets
Java API forms a standard interface for developing Web applications, 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.
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.
javax.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.
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 signatures 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
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
environmental 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 memory, database connection,
threads, file handles and so on and also makes sure that any persistent state
is synchronized with the Servlet's current state in memory.
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.
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 applications to load Servlets and Filters at runtime that are needed.
Methods Description
getMajorVersion() Returns the major version of the Servlet API that this Servlet
container supports. This method returns 3 if the
implementations comply with Version 3.0.
getMinor Version() Returns the minor version of the Servlet API that this Servlet
container supports. This method return 0 if the implementations
comply with Version 3.0.
getEffective MinorVersion() Returns the minor version of Servlet specification that the
application represented by this ServletContext is based on.
getMimeType() Returns the MIME type of the given file. Common MIME |
types are text/html and image/gif.
getRealPath() Returns the real file system path of any given virtual path.
getServletInfo() Returns the real file system path of any given virtual path.
Returns the name and version of the servlet container on which
the servlet is running
getAttribute() Returns the servlet container attribute with the given name or
null if there is no attribute by that name.
addServlet() Adds the Servlet with the given name and class type or class
name to the current ServletContext.
addFilter() Adds the filter with the given name and class type or class
name to the current ServletContext.
createServlet() Instantiates the given Servlet class and performs any required
resource injection into the new Servlet instance before returning
it.
createFilter() Instantiates the given Filter class and performs any required
resource injection into the new Filter instance before returning
it.
setinitParameter() Sets the context initialization parameter with the given name
and value on the current ServletContext.
setSession Tracking Modes() Sets the session tracking modes that are to become effective for
the current ServletContext
removeAttribute() Removes the attribute with the given name from the current
ServletContext.
getSession Tracking Modes() Retrieves the session tracking modes that are in effect for the
current ServletContext
getEffectiveSessionTracking Retrieves the session tracking modes that are effective for this
Modes() ServletContext
addListener() Adds the listener with the given class name or class type to this
ServletContext.
getVirtualServerName() Returns the configuration name of the logical host on which the
ServletContext is deployed.
ServletConfig Interface
ServletConfig 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
Methods Description
When a Servlet accepts a call from a client, it receives two objects, one is a ServletRequest and
the other is a ServletResponse.
ServletRequest interface encapsulates the communication from the client to the server, while
ServletResponse interface encapsulates the communication from the Servlet back to the client.
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 ServletRequest interface:
Method Description
getContentLengthLong( Returns the length, in bytes, of the request body and made available
) by the input stream.
getParameterValues() Returns an array of String objects containing all of the values the
given request parameter has
getServerName() Returns the host name of the server to which the request was sent.
getServerPort() Returns the port number to which the request was sent.
getServletContext() Retrieves the servlet context to which this servlet was last dispatched.
startAsync() Puts this request into asynchronous mode and initializes its
AsyncContext with the original (unwrapped) ServletRequest and
ServletResponse objects.
isAsyncStarted() Checks if this request has been put into asynchronous mode.
ServletResponse interface provides methods to the Servlet for replying to the client.
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 the ServletResponse interface:
Methods Description
Method Description
getWriter() Returns a Print Writer 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.
setLocale() Sets the locale of the response, setting the headers (including the
Content-Type's charset) as appropriate.
ServletInputStream class provides an input stream for reading binary data from a client request.
A Servlet that filters binary output from other sources generally receives its input through this
stream.
Methods Description
isFinished() Returns true when all the data from the stream has been read.
ServletOutputStream class provides an output stream for sending binary data back to a client.
The following are the commonly used methods available in the ServletOutputStream class:
Methods Description
print() Writes a character to the client, with no carriage return line feed at the end.
Deployment Descriptor
Servlet uses the deployment descriptor (web.xml file) for deploying your application into a web
server. Servlet API 3.0 has introduced a new package called javax.servlet.annotation. It
provides annotation types which can be used for annotating a servlet class. If you use
annotation, then the deployment descriptor (web.xml) is not required. But you should use
tomcat7 or any later version of tomcat.
Annotations can replace equivalent XML configuration in the web deployment descriptor file
(web.xml) such as servlet declaration and servlet mapping. Servlet containers will process the
annotated classes at deployment time.
The annotation types introduced in Servlet 3.0 are −
1 @WebServlet
To declare a servlet.
@WebInitParam
2
To specify an initialization parameter.
@WebFilter
3
To declare a servlet filter.
@WebListener
4
To declare a WebListener
@HandlesTypes
5
To declare the class types that a ServletContainerInitializer can
handle.
@HttpConstraint
@HttpMethodConstraint
7
This annotation is used within the ServletSecurity annotation to
represent security constraints on specific HTTP protocol messages.
@MultipartConfig
8 Annotation that may be specified on a Servlet class, indicating that
instances of the Servlet expect requests that conform to the
multipart/form-data MIME type.
@ServletSecurity
9 This annotation is used on a Servlet implementation class to specify
security constraints to be enforced by a Servlet container on HTTP
protocol messages.
The @WebServlet is used to declare the configuration of a Servlet with a container. The
following table contains the list of attributes used for WebServlet annotation.
1 String name
Name of the Servlet
String[] value
2
Array of URL patterns
String[] urlPatterns
3
Array of URL patterns to which this Filter applies
Int loadOnStartup
4
The integer value gives you the startup ordering hint
WebInitParam[] initParams
5
Array of initialization parameters for this Servlet
Boolean asyncSupported
6
Asynchronous operation supported by this Servlet
String smallIcon
7
Small icon for this Servlet, if present
String largeIcon
8
Large icon for this Servlet, if present
String description
9
Description of this Servlet, if present
String displayName
10
Display name of this Servlet, if present
1 String name
Name of the initialization parameter
String value
2
Value of the initialization parameter
String description
3
Description of the initialization parameter
@Webfilter
This is the annotation used to declare a servlet filter. It is processed by the container at
deployment time, and the corresponding filter applied to the specified URL patterns, servlets,
and dispatcher types.
The @WebFilter annotation defines a filter in a web application. This annotation is specified
on a class and contains metadata about the filter being declared. The annotated filter must
specify at least one URL pattern. The following table lists the attributes used for WebFilter
annotation.
1 String filterName
Name of the filter
String[] urlPatterns
2
Provides array of values or urlPatterns to which the filter applies
DispatcherType[] dispatcherTypes
3
Specifies the types of dispatcher (Request/Response) to which the filter applies
String[] servletNames
4
Provides an array of servlet names
String displayName
5
Name of the filter
String description
6
Description of the filter
WebInitParam[] initParams
7
Array of initialization parameters for this filter
Boolean asyncSupported
8
Asynchronous operation supported by this filter
String smallIcon
9
Small icon for this filter, if present
String largeIcon
10
Large icon for this filter, if present
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −
JDBC API − This provides the application-to-JDBC Manager connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
1. Class.forName("oracle.jdbc.driver.OracleDriver");