0% found this document useful (0 votes)
6 views

Advanced Java Programming Notes Unit 2

Uploaded by

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

Advanced Java Programming Notes Unit 2

Uploaded by

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

UNIT 2

JavaBeans (thereafter referred to as beans) are reusable software components that are
written in the Java programming language and can be manipulated by using beans-aware
builder tools. Because the beans are reusable, you can use them to construct more
complex components, build new applications, or add functionality to existing applications.

JavaBean class in Java


•••
JavaBeans are classes that encapsulate many objects into a single object (the
bean). It is a Java class that should follow the following conventions:
1. Must implement Serializable.
2. It should have a public no-arg constructor.
3. All properties in java bean must be private with public getters and
setter methods.
Illustration of JavaBean Class
A simple example of JavaBean Class is mentioned below:
• JAVA

// Java program to illustrate the


// structure of JavaBean class
public class TestBean {
private String name;

public void setName(String name) {


this.name = name;
}

public String getName() { return name; }


}

Getter and Setter have important roles in the topic. So, let us check on Getter and
Setter below:
Setter and Getter Methods in Java
Setter and Getter Methods in Java properties are mentioned below:
Properties for setter methods:
1. It should be public in nature.
2. The return type a should be void.
3. The setter method should be prefixed with the set.
4. It should take some argument i.e. it should not be a no-arg method.
Properties for getter methods:
1. It should be public in nature.
2. The return type should not be void i.e. according to our
requirement, return type we have to give the return type.
3. The getter method should be prefixed with get.
4. It should not take any argument.
For Boolean properties getter method name can be prefixed with either “get” or
“is”. But recommended to use “is”.
• JAVA

// Java program to illustrate the


// getName() method on boolean type attribute
public class Test {
private boolean empty;

public boolean getName(){


return empty;
}

public boolean isempty(){


return empty;
}
}

Example of JavaBean Class


Example 1:
Below is the implementation of the JavaBean Class:
• JAVA

// Java Program of JavaBean class


package geeks;

public class Student implements java.io.Serializable {


private int id;
private String name;

// Constructor
public Student() {}

// Setter for Id
public void setId(int id) { this.id = id; }

// Getter for Id
public int getId() { return id; }

// Setter for Name


public void setName(String name) { this.name = name; }

// Getter for Name


public String getName() { return name; }
}

Creating a Java Bean: The Basics


To create a Java Bean, you need to follow some rules. A Java Bean is a class that:

o Is serializable (implements the Serializable interface).


o Has a public no-argument constructor.
o Provides methods to set and get the values of properties (known as setter and
getter methods).
Let’s create a simple Java Bean to understand how it works.

import java.io.Serializable;

public class StudentBean implements Serializable {


private String name;
private int age;

public StudentBean() {
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}
Java
Copy
In this example, StudentBean is a Java Bean. It implements the Serializable interface, has a
public no-argument constructor, and provides getter and setter methods for its
properties name and age.
The advantages of using Java Beans include code reusability, encapsulation of logic, and easy
interaction with other components. However, it’s worth noting that Java Beans can sometimes
lead to ‘over-encapsulation’, where simple operations are wrapped into unnecessary methods,
leading to bloated code.
Types of EJB
EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It
encapsulates the business logic of an application. It is a specification for developing a
distributed business application on the Java platform. There are three types of
EJBs: Session Bean, Entity Bean, and Message-Driven Bean. In this section, we will
discuss all types of EJB in detail.

Let's discuss one by one in detail.

Session Bean
The bean sprout business idea that can be systematically used by customer, remote,
and web service. When a client wants to use an application distributed on a server,
then the client uses session bean methods. This session bean provides services to
customers, protecting them from complex problems by performing business
operations within the server.

To get to an application that is conveyed to the worker, the client summons the
meeting bean's strategies. The meeting bean performs work for its client, safeguarding
it from intricacy by executing business errands inside the worker. Remember that
session beans are not persistence.

There are two types of session beans:

o Stateless Session Beans


o Stateful Session Beans
o Singleton Session Beans

Stateless Session Beans


A stateless session bean doesn't keep a conversational state with the customer or
client. When a client invokes the methods for a stateless bean, the bean's instance
variable may contain a state explicitly to that client however only for the span of the
invocation.

At the point when the method has finished, the client explicit state should not be held.
However, the client may change the state of instance variable presented in pooled
stateless beans, and this state is held over to the following invocation of the pooled
stateless bean.

Besides this, during the invocation of the method, all instances of a stateless bean are
the same, permitting the EJB container to assign an instance to any client. Therefore,
the state of a stateless session bean should apply across all clients. It can be
implemented in a web-services.
Since they can maintain various customers, stateless session beans can offer better
adaptability for applications that require large numbers of clients. Ordinarily, an
application requires fewer stateless session beans than stateful session beans to
support the same number of clients.

To improve execution, we may choose a stateless session bean in the event that it has
any of these characteristics.

o The state of the bean has no information or data for a particular client.
o In a private method invocation, the bean performs a generic task for all clients.
o The bean implements a web service.

AD
AD

Stateful Session Beans


A stateful session bean is the same as an interactive session. The state of an object
comprises the values of its instance variables. In a stateful session bean, the instance
variables denote the state of a unique client/bean session. Since, the client interacts
with its bean. The state is usually called the conversational state. It maintains the state
of a client across multiple requests. So, we cannot implement it in the web services
because it cannot be shared. When the client terminates the session, it is no longer
associated with the client.

The state is held for the span of the client/bean session. In case if the client eliminates
the bean, the session closes and the state is omitted. This transient nature of the state
isn't an issue, because the interaction between the client and the beans ends. So, it is
not required to hold the state.
Stateful session beans should be used, if any of the following conditions are valid:

o The bean's state denotes the alliance between the bean and a particular client.
o The bean needs to hold data about the customer across method invocations.
o The bean interferes between the customer and different segments of the
application, introducing an improved visible to the client.
o In the background, the bean deals with the workstream of a few enterprise
beans.

Note: Stateless and stateful both session beans are not persistent.

Singleton Session Beans


A singleton session bean maintains one instance per application and the instance
exists for the lifecycle of the application. It offers the same functionality as the stateless
session beans. But the only difference is that there is only one singleton session bean
per application while in the stateless session bean a pool of beans is used.

From that pool, any of the session beans may respond to the client. We can implement
it in the web-service endpoints. It takes care of the state but does not hold the state if
unexpected crashes or shutdown occur. It can be used if we want to perform cleanup
tasks on closing the application or shut down as well. It is because it operates
throughout the life cycle of the application.
Singleton session beans are suitable for the following conditions:

o The state of the bean must be shared across the application.


o A single enterprise bean should be accessed by multiple threads concurrently.
o The application needs an enterprise bean to perform undertakings upon
application startup and shutdown.
o The bean implements a web service.

Entity Bean
An entity bean is an unpredictable business substance. It models a business substance
or models different activities inside a business interaction. It is used to encourage
business benefits that include data and calculations on that data. It can deal with
various, needy, diligent articles in playing out its essential assignments. A substance
bean is a far-off object that oversees steady information and performs complex
business rationale. It can be extraordinarily distinguished by an essential key.

AD
AD
It is a far-off object that oversees steady information, performs complex business
rationale, possibly utilizes a few ward Java protests, and can be remarkably
distinguished by an essential key. It ordinarily coarse-grained determined items since
they use steady information put away inside a few fine-grained relentless Java objects.
Element beans are diligent on the grounds that they do endure a worker crash or an
organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it
comprises a unique identity that can be fetched if we have a primary key. The type for
the unique key is defined by the bean provider. A client can retrieve the entity bean if
the primary has been misplaced. If the bean is not available, the EJB container first,
instantiates the bean and then re-populates the data for the client.

The diligence for entity bean information is given both to saving state when the bean
is passivated and for improving the state when a failover has detected. It can endure
in light of the fact that the information is put away determinedly by the holder in some
type of information stockpiling framework, like a data set.

Entity beans persist business data by using the following two methods:

o Bean-Managed Persistence (BMP)


o Container-Managed Persistence (CMP)

Bean Managed Persistence


Bean-managed persistence is more complicated in comparison to container-managed
persistence. Because it allows us to write the persistence logic into the bean class,
explicitly. In order to write the persistence handling code into the bean class, we must
know the type of database that is being used and how fields of the bean class are
mapped to the database. Therefore, it provides more flexibility between the database
and the bean instance.

AD
AD
It can be used as an alternative to CMP. If the deployment tools are incompatible for
mapping the bean instance's state to the database. The disadvantage of BMP is that
more work is required to define the bean and it ties the bean to a specific database
type and structure.

Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly
handles the relationship between the bean and the database. Bean developers focus
on the data and the business process. The principal constraint is that the EJB
compartment can most likely not produce information base access articulations with
the proficiency of a programmer.

Unlike BMP, CMP does not allow us to write database access calls in the methods of
the entity bean class. It is because the persistence is handled by the container at run-
time. The following two things are required to support the CMP:

o Mapping: It denotes that how to map an entity bean to a resource.


o Runtime Environment: A CMP runtime environment that uses the mapping
information to perform persistence operations on each bean.

Note: Entity bean has been replaced with Java persistence API.

Message-Driven Bean (MDB)


MDB is a Java Messaging Service (message listener). It consumes messages from a
queue or subscription of a topic. It provides an easy way to create or implement
asynchronous communication using a JMS message listener. An advantage of using
MDB is that it allows us to use the asynchronous nature of a JMS listener. We can
implement message-driven beans with Oracle JMS (Java Messaging Service).
There is an EJB container (contains MDBs pool) that handles the JMS queue and topic.
Each incoming message is handled by a bean that is invoked by the container. Note
that no object invokes an MDB directly. All invocation for MDB originates from the
container. When the container invokes the MDB, it can invoke other EJBs or Java
objects to continue the request.

It is quite similar to stateless session bean. Because it does not save informal state, also
used to handle multiple incoming requests. EJB has the following benefits over the
JMS are as follows:

o It creates a consumer for the listener. It means that the container


creates QueueReceiver or TopicSubscriber is created by the container.
o MDB is registered with the consumer. It means that at deployment time
QueueReceiver, TopicSubscriber, and its factory are registered by the container.
o The message ACK mode is specified.

The primary function of MDB is to read (receive) or write (send) incoming from a JMS
destination (i.e. queue or topic). While using MDB ensure that it is configured and
installed properly. It interacts with JMS and the JMS installed on the Oracle database.
The database retains queue or topic. The following figure depicts how MDB interacts
with the JMS destination.
The working of MDB is as follows:

o MDB creates and opens a JMS connection to the database by using the data
source (JMS resource provider). The JDBC driver is used to facilitate the JMS
connection.
o A JMS session over the JMS connection is opened by the MDB.
o If any message for the MDB is routed to the onMessage() method of the MDB
from the queue o topic. Other clients may also access the same queue and topic
to put the message for the MDB.

Note that it does not handle the requests that are requested by the clients instead it
handles requests that are placed into a queue.

MDB implements the javax.ejb.MessageDriverBean interface and inherits the


javax.jms.MessageListener class that provides the following methods:

Method Description

onMessage(msg) The container dequeues a message from the JMS queue


associated with this MDB and gives it to this instance by invoking
this method. This method must have an implementation for
handling the message appropriately.
setMessageDrivenContext(ctx) After the bean is created, the setMessageDrivenContext method
is invoked. This method is similar to the EJB setSessionContext
and setEntityContext methods.

ejbCreate() This method is used just like the stateless session bean ejbCreate
method. No initialization should be done in this method.
However, any resources that you allocate within this method will
exist for this object.

ejbRemove() Delete any resources allocated within the ejbCreate method.


AD
AD

Difference Between Session and Entity Bean


The following table depicts the key differences between session bean and entity bean.

Basis of Session Bean Entity Bean


Comparison

Primary Key It has no primary key. It is used to It has a primary key that allows us to find
identify and retrieve specific bean instances and can be shared by more
instances. than one client.

Stateless/ It may be stateful or stateless. It is stateful.


Stateful

Span It is relatively short-lived. It is relatively long-lived.

Performance It represents a single conversation It encapsulates persistence business


with a client. data.

Accessibility It is created and used by a single It may be shared by multiple clients.


client.

Recovery It is not recoverable in case if EJB It is recoverable if any failure has


server fails. So, it may be destroyed. occurred.

Persistence of It persists data only for the span of Persistence beyond the life of a client
Data the conversation with the client. instance. Persistence can be container-
managed or bean-managed.

Remote It extends javax.ejb.EJBObject. It extends javax.ejb.EJBObject.


Interface
Home It extends javax.ejb.EJBHome. It extends javax.ejb.EJBHome.
Interface

Bean Class It extends javax.ejb.EJBSessionBean. It extends javax.ejb.EJBEntityBean.

Life Cycle of an Entity Bean


When developing an entity bean you can take advantage of the bean's relationship
with the container to execute logic and optimizations outside the context of the
bean's core logic. As the container creates and pools an instance, assigns data to it,
executes bean methods, and eventually removes the instance, the container
provides opportunities for your code to execute. This topic provides an overview of
an entity bean's life cycle, pointing out some of these opportunities.

The following figure shows the life cycle of an entity bean. An entity bean has the
following three states:

• Does not exist. In this state, the bean instance simply does not exist.
• Pooled state . When WebLogic server is first started, several bean instances
are created and placed in the pool. A bean instance in the pooled state is not
tied to particular data, that is, it does not correspond to a record in a database
table. Additional bean instances can be added to the pool as needed, and a
maximum number of instances can be set (for more information, see
the @Entity Annotation).
• Ready state. A bean instance in the ready state is tied to particular data, that
is, it represents an instance of an actual business object.

The various state transitions as well as the methods available during the various
states are discussed below.
Servlet Architecture
•••
Servlets are grouped under the Advanced Java tree that is used to create
dynamic web applications. Servlets are robust, well scalable, and are
primarily used in developing server-side applications. If we go a little back
in time, we would be able to witness that before the introduction of
servlets, CGI (Common Gateway Interface) was used. Among several
indigenous tasks that a servlet is capable of doing, dynamically performing
client requests and responses are most common. Other tasks that a servlet
can do effectively are:
• Can easily manage/control the application flow.
• Suitable to implement business logic.
• Can effectively balance the load on the server side.
• Easily generate dynamic web content.
• Handle HTTP Request and Response
• Also act as an interceptor or filter for a specific group of requests.

Types of Servlet
• Generic Servlets: These are those servlets that provide
functionality for implementing a servlet. It is a generic class from
which all the customizable servlets are derived. It is protocol-
independent and provides support for HTTP, FTP, and SMTP
protocols. The class used is ‘javax.servlet.Servlet’ and it only has
2 methods – init() to initialize & allocate memory to the servlet and
destroy() to deallocate the servlet.
• HTTP Servlets: These are protocol dependent servlets, that
provides support for HTTP request and response. It is typically
used to create web apps. And has two of the most used methods –
doGET() and doPOST() each serving their own purpose.
There are three potential ways in which we can employ to create a servlet:
• Implementing Servlet Interface
• Extending Generic Servlet
• Extending HTTP Servlet

Components of Servlet Architecture


Servlet Architecture contains the business logic to process all the requests
made by client. Below is the high-level architecture diagram of servlet. Let’s
see in brief, how does each component add to the working of a servlet.

1. Client
The client shown in the architecture above is the web browser and it
primarily works as a medium that sends out HTTP requests over to the web
server and the web server generates a response based on some processing
in the servlet and the client further processes the response.
2. Web Server
Primary job of a web server is to process the requests and responses that a
user sends over time and maintain how a web user would be able to access
the files that has been hosted over the server. The server we are talking
about here is a software which manages access to a centralized resource or
service in a network. There are precisely two types of webservers:
• Static web server
• Dynamic web server
3. Web Container
Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets. Two prime tasks of a web
container are:
• Managing the servlet lifecycle
• URL mapping
Web container sits at the server-side managing and handling all the
requests that are coming in either from the servlets or from some JSP pages
or potentially any other file system.
How does a Servlet Request flow?
Every servlet should override the following 3 methods namely:
1. init(): To initalize/instantiate the servlet container.
2. service(): This method acts like an intermediatory between the
HTTP request and the business logic to serve that particular
request.
3. destroy(): This method is used to deallocate the memory allocated
to the servlet.
These methods are used to process the request from the user.
Following are the steps in which a request flows through a servlet which
can be observed in the architecture diagram:
• The client sends over a request.
• The request is accepted by the web server and forwarded to the
web container.
• In order to obtain the servlet’s address, the web container
traces web.xml file corresponding to the request URL pattern.
• By the time above process takes place, the servlet should have
been instantiated and initialized. The init() method is invoked to
initialize the servlet.
• By passing ServletRequest and Response
object, public service() method is called by the container.
• In the next step, the ServletRequest and ServletResponse objects
are type casted
to HttpServletRequest and HttpServletResponse objects by
the public service() method.
• Now protected service() method is called by the public
service() method.
• The protected service() method dispatches the request to the
correct handler method based on the type of request.
• When servlet container shuts down, it unloads all the servlets and
calls destroy() method for each initialized servlet.
Advantages
• Prime functionality of a servlet is that they are independent of
server configuration, and they are pretty much compatible with any
of the web servers.
• Servlets are also protocol-independent
supporting FTP, HTTP, SMTP, etc. protocols to the fullest.
• Until destroyed manually, servlets can be retained in the memory
helping process several requests over time. Also, once a database
connection is established, it can facilitate process several requests
for a database in the very same database session.
• Servlets inherit Java’s property of portability and hence are
compatible with nearly any web server.
• Servlets are first converted into byte codes and then executed,
which helps in increasing the processing time.
Disadvantages
• Designing a servlet can be pretty laborious.
• Exceptions need to be handled while designing a servlet since they
are not thread safe.
• Developers may need additional skills to program a servlet.

Servlet Life Cycle


Servlet Life Cycle can be described as a series of steps that a servlet goes through during its
life span from loading to destruction.
The Servlet Life Cycle is as follows:

• Servlet class is loaded first when the Web container receives a new request.
• Then the web container creates an instance of the servlet. This instance is created only
once in the whole Servlet Life Cycle.
• The servlet is initialized by the calling init() method.
• service() method is called by the servlet to process the client's request.
• Servlet is destroyed by calling the destroy() method.
• Java Virtual Machine's(JVM) garbage collector clears the destroyed servlet's memory.

Let us see the signature for each of the methods mentioned above:

init()

Whenever a user invokes the URL associated with the particular servlet, the init() method is
called. It is called only once and not each time there is a request. An instance of a servlet is
created through the init() method. Each user request creates a new thread catering
to GET and POST requests.

public void init(ServletConfig config) throws ServletException{


//initialization code
}

service()

The web container calls the service() method each time there is a new request to the servlet.
This is done by spawning a new thread. This method checks the HTTP request type, i.e,
whether it is a GET, POST, DELETE, etc, and calls the doGet, doPost, doDelete, etc methods
as per the request.

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException{
//doGet, doPost, doDelete etc as per request
}

destroy()

This method is called just once at the end of the Life Cycle of Servlet. It helps perform all the
clean-up activities including closing database connections, halting background threads, etc.
Then it removes the servlet from the container.

public void destroy (){


//clean-up code
}

Architecture Diagram of the Servlet Life Cycle in Java


The following represents the Servlet Life Cycle. When a request is sent for a particular web
page, the servlet corresponding to it must be initialized. The servlet container/web container
will load the servlet and create an instance of it through init().
All the subsequent requests to the same web page will result in invoking
the service() method. This method will typecast the ServletRequest and ServletResponse
objects to HttpServletRequest and HttpServletResponse objects respectively. Servlets can
handle multiple requests concurrently since each request results in a new thread.

The destroy() method is only called once all threads within the servlet's service methods have
exited or after a timeout period.
Program Illustrating Java Servlet Implementation
A program illustrating Java Servlet implementation We can implement a Servlet in the
following ways:

1. By implementing Servlet interface


2. By extending GenericServlet class
3. By extending HttpServlet class

The easiest and most common way is to extend HTTPServlet class. Let us see a Hello
World program of a servlet using this method.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
//Set content type
response.setContentType("text/html");
//Get the stream to write data
PrintWriter out = response.getWriter();
//Write HTML in stream
out.println("<html><body>");
out.println("<h1>Hello World</h1>");
out.println("</body></html>");
//Close the stream
out.close();
}
}

The HttpServlet class is extensively used to create servlet since it provides methods to handle
HTTP requests like doGet(),doPost, doDelete() etc. The above code is used to display HTML
content on the web page displaying "Hello World".

Features of Java Servlet Life Cycle


1. Portable

Its portability comes from the fact that Java is portable. This means that the Java code is
compiled into bytecode. The bytecode is platform-independent. Hence it is Write Once Run
Anywhere(WORA).

2. Efficient

Efficient because it creates a new thread for each request and not each process.

3. Scalable
Since Servlets can handle multiple requests due to multithreading, it is scalable to be quite
responsive. Servlets are also amenable to various load distribution architectures. We can scale
the web applications easily with the right load distribution.

4. Robust

JVM handles all the Servlet programs, including garbage collection and prevention
of memory leaks.

Java Servlet Request


The job of a servlet is to handle the request sent by the client and reply with a response. To
handle the client request, Java provides two interfaces
named ServletRequest and HTTPServletRequest. Both these interfaces have several methods
which can allow us to get information in the request. Let us see the various interfaces of
HTTPRequest.

1. HTTP Request Header

HTTP Request header is used to pass additional information about the client/requestor to the
server. These include extra information, metadata that the server can use.
HTTPServletRequest provides getHeaderNames() and getHeader() methods which can be
used to extract header names and header values, respectively. Let us see some of the common
header names sent:

Accept: This specifies the acceptable media types in the response.

Accept-Charset: This indicates the acceptable character sets in the response. E.g., ISO-8859-
1

Accept-Encoding: This restricts the content-coding values that are acceptable in the
response.

Accept-Language: This restricts the set of language that is preferred in the response.

Authorization: This type indicates that the user agent is attempting to authenticate itself with
a server.

User-Agent: This type contains the information about the user agent originating the request.

Content-Length: for POST messages, the length of data attached.

Cookie: From the Email address of the requester. Only used by custom clients, not by
browsers.

Host: Host and port as listed in the original URL.

2. HTTP Request Parameters


HTTP Request parameters are ways in which clients can send user information to the server.
Parameters can be sent in the URL or even in the request body. Any word after the '?' in a
URL contains parameters. For
Example: www.site.com?myparam1={id1}&myparam2={id2} myparam1 and my param2
are the parameters in the above URL request. We can access the parameters from a request in
the following way using getParameter().

protected void doGet(


HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String param1 = request.getParameter("param1");


String param2 = request.getParameter("param2");
}

Typically, if an HTTP GET request is sent, the parameters are included in the query string in
the URL. Whereas, if it is an HTTP POST request, the parameters are included in the body
part of the HTTP request.

3. HTTP Request InputStream

An HTTP Post request can have a lot of data sent to the server in the request body. We can
access all these data using InputStream pointing to the request body.

InputStream requestBodyInput = request.getInputStream();

This will return the raw data from the request which can be separately parsed and used as
necessary.

4. HTTP Request Context

An object of ServletContext is created by the web container when deployed. This object can
be used to get metadata about the web application which is stored in the web.xml file.

ServletContext context = request.getSession().getServletContext();

As you can see, you have to first get the session object, to get access to the ServletContext
object.

5. HTTP Request Session

A session can hold the details about a user between requests, across the application.
An HTTPSession object is used for session management. When a new user accesses the
application for the first time, the HTTPSession object is obtained
through request.getSession().

The user is given a unique ID to identify the session. A particular session is active until a
particular specified timeout value is mentioned in the web.xml file. Let us see the code
snippet to create a session:
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
}

Session user information can be accessed/modified using setAttribute and getAttribute as


follows:

session.setAttribute("name", "Scaler");
String userName = (String) session.getAttribute("name");

Java Servlet Response


Let us explore the HTTP Response object which is used to send appropriate data from server
to client.

1. HTTP Response Header

Headers in response must be set before writing data into it. You can set it as key-value pair in
the following way-

response.setHeader("Header-Name", "Header Value");

2. HTTP Response Content Type

This is a header used to tell the browser, the kind of data being returned. The default for
servlets is text/plain, but text/HTML is usually explicitly specified. This header can be set in
the following way-

response.setHeader("Content-Type", "text/HTML");

3. HTTP Response Content Length

Content length is used to tell the browser how many bytes are being sent by the servlet. This
is needed only when the browser is using a persistent HTTP connection.

response.setHeader("Content-Length", "12908");

4. HTTP Response Write HTML

In order to send HTML as response back to browser, we need to use PrintWriter.

PrintWriter writer = response.getWriter();


writer.write("<html><body>response</body></html>");

5. HTTP Response Redirection

When we need to direct users to a location other than what is requested, redirection is used.
This can happen when the document is moved pointing to a different location. We can do this
by using the following code in doGet()/doPost() method:
response.sendRedirect("https://www.yoursite.com");

Benefits of Servlets
Easy to implement

It is wasy to implement Servlet using Java APIs. It is also easy to implement sessions and
cookies since dedicated interfaces are provided for each use case.

Easy Database Connection

There was no way to connect to the database directly using CGI. But using Servlets, we can
connect to the database directly and track sessions.

Protocol Independent

Servlets are flexible to follow any web protocol including FTP, HTTP.

Better Exception Handling

Earlier, CGI(Common Gateway Interface) scripts which were used before Servlets and
written in C++ did not have good exception handling, for instance, the application might
crash if there was a divide by 0 error. Servlets, written in Java have much better ways to
handle such exceptions and make sure the application doesn't crash. It has provisions for
redirection and forwarding.

Security

The server-side components inherit the security of the webserver. And the Servlet programs
benefit from Java's Security Manager.

Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface

Servlet interface provides commonbehaviorto all the servlets.Servlet interface


defines methods that all servlets must implement.

Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface


There are 5 methods in Servlet interface. The init, service and destroy are the life cycle
methods of servlet. These are invoked by the web container.

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only
once.

public void service(ServletRequest provides response for the incoming request. It is


request,ServletResponse response) invoked at each request by the web container.

public void destroy() is invoked only once and indicates that servlet is
being destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as writer,


copyright, version etc.

Servlet Example by implementing Servlet interface


Let's see the simple example of servlet by implementing the servlet interface.

File: First.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class First implements Servlet{
5. ServletConfig config=null;
6.
7. public void init(ServletConfig config){
8. this.config=config;
9. System.out.println("servlet is initialized");
10. }
11.
12. public void service(ServletRequest req,ServletResponse res)
13. throws IOException,ServletException{
14.
15. res.setContentType("text/html");
16.
17. PrintWriter out=res.getWriter();
18. out.print("<html><body>");
19. out.print("<b>hello simple servlet</b>");
20. out.print("</body></html>");
21.
22. }
23. public void destroy(){System.out.println("servlet is destroyed");}
24. public ServletConfig getServletConfig(){return config;}
25. public String getServletInfo(){return "copyright 2007-1010";}
26.
27. }

Handling GET and POST Requests


To handle HTTP requests in a servlet, extend the HttpServlet class and override
the servlet methods that handle the HTTP requests that your servlet supports. This
lesson illustrates the handling of GET and POST requests. The methods that handle
these requests are doGet and doPost.

Handling GET requests

Handling GET requests involves overriding the doGet method. The following
example shows the BookDetailServlet doing this. The methods discussed in
the Requests and Responses section are shown in bold.

public class BookDetailServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title>Book Description</title></head>" +
...);

//Get the identifier of the book to display


String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...
}

The servlet extends the HttpServlet class and overrides the doGet method.

Within the doGet method, the getParameter method gets the servlet's expected
argument.

To respond to the client, the example doGet method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing
the writer, the example sets the content-type header. At the end of
the doGet method, after the response has been sent, the Writer is closed.

Handling POST Requests

Handling POST requests involves overriding the doPost method. The following
example shows the ReceiptServlet doing this. Again, the methods discussed in
the Requests and Responses section are shown in bold.

public class ReceiptServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title> Receipt </title>" +
...);

out.println("<h3>Thank you for purchasing your books from us " +


request.getParameter("cardname") +
...);
out.close();
}
...
}
The servlet extends the HttpServlet class and overrides the doPost method.

Servlet - Handling HTTP request


In the previous few chapters, we learnt what a Servlet is, what a JSP is, how they fit together in the
bigger picture in a J2EE Application. In this chapter, we are going to see how Servlets handle HTTP
Requests.

So, lets get started!!!

Servlets & Web Pages:

JSP and servlets have greatly enhanced the way in which we can create and manage Web pages.
The difficulty level of coding JSP is between that of coding HTML and pure Java. Servlets are pure
Java. The idea behind having both is providing a way for non-programmers to contribute functionality
through JSP. You can “program” a JSP page almost as easily as you can write an HTML page. For
simple tasks like displaying the current date, you write a normal HTML page and add only a small
amount of Java as a scriptlet. For big tasks like processing a shopping cart, you use JSP as the
mediator between the Web form and a component(s) (bean or servlet) that has all the processing
logic. Most of the code in a Web application will go into servlets. The JSP portion is a just front end to
the application (with little logic of course) that a user can use/navigate comfortably.

We all know that the web (Internet) lives over the Http protocol. The servlet as expected is handle the
http requests. Well, what use would a servlet be if it cannot handle the most commonly used protocol
in the internet.

A lot of things happen when a servlet is invoked because of some user action in a web page. The
sequence of events starts with a browser sending a request to a Web server. The server hands the
request to a Servlet Container. The container loads the servlet (if it isn't already loaded), instantiates a
request and response objects, and then hands these objects to the servlet by calling first its init()
method, then its service() method, and lastly the destroy() method. The service() method will typically
call one of the doXXX() methods such as doGet(). The response based on the output of the doXXX()
methods will be sent back to the browser and will be displayed on screen.

Below is a diagrammatic representation of how data flows from a browser to the servlet and then back
to the browser.

Let’s retrace the sequence of steps:

1. Web Server receives request from the Browser (Http Request)


2. Web Server checks the request and invokes the appropriate Servlet/JSP in the Servlet Container
3. If this is the first time the servlet is invoked its init() method gets called
4. If not, the service() gets called.
5. The service() method in turn delegates the processing to one of the doXXX() methods based on the
request received
6. The output of the doXXX() methods is sent back to the servlet container
7. The container analyzes the response and formats it appropriately
8. If the response is normal a Http Response is sent back to the client
9. Else, an error response is sent back to the client

Now that we know how the requests makes its way to the servlet and then comes back to the client,
lets look at a sample Servlet that will actually compile and produce some output on the browser.

Servlet Source Code:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class OurFirstServlet extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("< html >");


out.println("< head >");
out.println("< title > A simple servlet. ");
out.println("");
out.println("< body >");
out.println("< h1 >Simple Servlet");
out.println("This is a Anand’s First Servlet");
out.println("< / body >");
out.println("< / html >");
}
}
The above is a simple servlet that doesn't do anything great but still displays something on the
browser when invoked.

How Http Servlet works?


As you can see in the diagram below that client (user’s browser) make
requests. These requests can be of any type, for example – Get Request, Post
Request, Head Request etc. Server dispatches these requests to the servlet’s
service() method, this method dispatches these requests to the correct
handler for example if it receives Get requests it dispatches it to the doGet()
method.

Hierarchy of Http Servlet


java.lang.Object
|_extended byjavax.servlet.GenericServlet
|_extended byjavax.servlet.http.HttpServlet
I have already discussed in the Generic Servlet article that you should always
use HttpServlet instead of the GenericServlet. HttpServlet is easier to work
with, and has more methods to work with than GenericServlet.

Session Tracking in Servlets


1. Session Tracking
2. Session Tracking Techniques

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known


as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking


techniques. Each time user requests to the server, server treats the request as the new
request. So we need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown
in the figure given below:
Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.

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

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus,
we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie

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

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides
a lot of useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)

public String getName() Returns the name of the cookie. The name cannot be changed
after creation.

public String getValue() Returns the value of the cookie.

public void setName(String changes the name of the cookie.


name)

public void setValue(String changes the value of the cookie.


value)

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.
How to create Cookie?
Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the
user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and va
lue of cookie
4. }

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing
it in another servlet. As we know well that session corresponds to the particular user.
So if you access it from too many browsers with different values, you will get the
different value.
index.html

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


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse respon
se){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse respons
e){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
download this example (developed using Myeclipse IDE)
download this example (developed using Eclipse IDE)
download this example (developed using Netbeans IDE)

Output
2) Hidden Form Field
1. Hidden Form Field
2. Example of Hidden Form Field

In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the
state of an user.
In such case, we store the information in the hidden field and get it from another
servlet. This approach is better if we have to submit form in all the pages and we don't
want to depend on the browser.

Let's see the code to store value in hidden field.

1. <input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page id or page
name in the hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field

1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

1. It is maintained at server side.


2. Extra form submission is required on each pages.
3. Only textual information can be used.

Example of using Hidden Form Field


In this example, we are storing the name of the user in a hidden textfield and getting
that value from another servlet.
index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response
){
7. try{
8.
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11.
12. String n=request.getParameter("userName");
13. out.print("Welcome "+n);
14.
15. //creating form that have invisible textfield
16. out.print("<form action='servlet2'>");
17. out.print("<input type='hidden' name='uname' value='"+n+"'>");
18. out.print("<input type='submit' value='go'>");
19. out.print("</form>");
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SecondServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response
)
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9.
10. //Getting the value from the hidden field
11. String n=request.getParameter("uname");
12. out.print("Hello "+n);
13.
14. out.close();
15. }catch(Exception e){System.out.println(e);}
16. }
17. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

3)URL Rewriting
1. URL Rewriting
2. Advantage of URL Rewriting
3. Disadvantage of URL Rewriting
4. Example of URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the
next resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair
is separated from another parameter using the ampersand(&). When the user clicks
the hyperlink, the parameter name/value pairs will be passed to the server. From a
Servlet, we can use getParameter() method to obtain a parameter value.
Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser independent).


2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information.

Example of using URL Rewriting


In this example, we are maintaning the state of the user using link. For this purpose,
we are appending the name of the user in the query string and getting the value from
the query string in another page.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response
){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. //appending the username in the query string
18. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
19.
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response
)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

4) HttpSession interface
1. HttpSession interface
2. How to get the HttpSession object
3. Commonly used methods of HttpSession interface
4. Example of using HttpSession

In such case, container creates a session id for each user.The container uses this id to
identify the particular user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of


HttpSession:

1. public HttpSession getSession():Returns the current session associated with


this request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current
HttpSession associated with this request or, if there is no current session and
create is true, returns a new session.

Commonly used methods of HttpSession interface

1. public String getId():Returns a string containing the unique identifier value.


2. public long getCreationTime():Returns the time when this session was
created, measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a
request associated with this session, as the number of milliseconds since
midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects
bound to it.

Example of using HttpSession


In this example, we are setting the attribute in the session scope in one servlet and
getting that value from the session scope in another servlet. To set the attribute in the
session scope, we have used the setAttribute() method of HttpSession interface and to
get the attribute, we have used the getAttribute method.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response
){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. HttpSession session=request.getSession();
18. session.setAttribute("uname",n);
19.
20. out.print("<a href='servlet2'>visit</a>");
21.
22. out.close();
23.
24. }catch(Exception e){System.out.println(e);}
25. }
26.
27. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response
)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. HttpSession session=request.getSession(false);
14. String n=(String)session.getAttribute("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy