0% found this document useful (0 votes)
14 views167 pages

Servlet Technology Overview and Benefits

Uploaded by

Nitin Meshram
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)
14 views167 pages

Servlet Technology Overview and Benefits

Uploaded by

Nitin Meshram
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

1|Page Code MicroSystem Arvind Sir 9822939054

Servlet Tutorial

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

Servet technology is robust and scalable as it uses the java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was used as a server-side programming
language. But there were many disadvantages of this technology. We have discussed these
disadvantages below.

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

What is a Servlet?
Servlet can be described in many ways, depending on the context.

 Servlet is a technology i.e. used to create web application.


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

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
2|Page Code MicroSystem Arvind Sir 9822939054

 What is the web application and what is the difference between Get and Post request ?
 What information is received by the web server if we request for a servlet ?
 How to run servlet in Eclipse, MyEclipse and Netbeans IDE ?
 What are the ways for servlet collaboration and what is the difference between
RequestDispatcher and sendRedirect() method ?
 What is the difference between ServletConfig and ServletContext interface?
 How many ways we can maintain state of an user ? Which approach is mostly used in
web development ?
 How to count total number of visitors and total response time for a request using Filter ?
 How to run servlet with annotation ?
 How to create registration form using Servlet and Oracle database ?
 How can we upload and download file from the server ?

What is web application?

A web application is an application accessible from the web. A web application is composed of
web components like Servlet, JSP, Filter etc. and other components such as HTML. The web
components typically execute in Web Server and respond to HTTP request.

CGI(Commmon Gateway Interface)

CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
3|Page Code MicroSystem Arvind Sir 9822939054

Disadvantages of CGI

There are many problems in CGI technology:

1. If number of clients increases, it takes more time for sending response.


2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantage of Servlet

There are many advantages of Servlet over CGI. The web container creates threads for handling
the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they
share a common memory area, lighweight, cost of communication between the threads are low.
The basic benefits of servlet are as follows:

1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about momery leak, garbage
collection etc.
4. Secure: because it uses java language..

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
4|Page Code MicroSystem Arvind Sir 9822939054

Servlet Terminology
There are some key points that must be known by the servlet programmer like server, container,
get request, post request etc. Let's first discuss these points before starting the servlet technology.

The basic terminology used in servlet are given below:

1. HTTP
2. HTTP Request Types
3. Difference between Get and Post method
4. Container
5. Server and Difference between web server and application server
6. Content Type
7. Introduction of XML
8. Deployment

HTTP (Hyper Text Transfer Protocol)

1. Http is the protocol that allows web servers and browsers to exchange data over the web.
2. It is a request response protocol.
3. Http uses reliable TCP connections bydefault on TCP port 80.
4. It is stateless means each request is considered as the new request. In other words, server
doesn't recognize the user bydefault.

Http Request Methods

Every request has a header that tells the status of the client. There are many request methods. Get
and Post requests are mostly used.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
5|Page Code MicroSystem Arvind Sir 9822939054

The http request methods are:

 GET
 POST
 HEAD
 PUT
 DELETE
 OPTIONS
 TRACE

HTTP
Description
Request
GET Asks to get the resource at the requested URL.
Asks the server to accept the body info attached. It is like GET request with extra
POST
info sent with the request.
Asks for only the header part of whatever a GET would return. Just like GET but
HEAD
with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
Asks for a list of the HTTP methods to which the thing at the request URL can
OPTIONS
respond

What is the difference between Get and Post?

There are many differences between the Get and Post request. Let's see these differences:

GET POST
In case of post request, large amount of
1) In case of Get request, only limited amount of
data can be sent because data is sent in
data can be sent because data is sent in header.
body.
2) Get request is not secured because data is exposed Post request is secured because data is not
in URL bar. exposed in URL bar.
3) Get request can be bookmarked Post request cannot be bookmarked
4) Get request is idempotent. It means second
request will be ignored until response of first request Post request is non-idempotent
is delivered.
5) Get request is more efficient and used more than Post request is less efficient and used less
Post than get.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
6|Page Code MicroSystem Arvind Sir 9822939054

Anatomy of Get Request

As we know that data is sent in request header in case of get request. It is the default request
type. Let's see what informations are sent to the server.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
7|Page Code MicroSystem Arvind Sir 9822939054

Anatomy of Post Request

As we know, in case of post request original data is sent in message body. Let's see how
informations are passed to the server in case of post request.

Container

It provides runtime environment for JavaEE (j2ee) applications.

It performs many operations that are given below:

1. Life Cycle Management


2. Multithreaded support
3. Object Pooling
4. Security etc.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
8|Page Code MicroSystem Arvind Sir 9822939054

Server

It is a running program or software that provides services.

There are two types of servers:

1. Web Server
2. Application Server

Web Server

Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It
can't be used for EJB.

Example of Web Servers are: Apache Tomcat and Resin.

Application Server

Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf,
ejb etc.

Example of Application Servers are:

1. JBoss Open-source server from JBoss community.


2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic provided by Oracle. It more secured.
4. Websphere provided by IBM.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
9|Page Code MicroSystem Arvind Sir 9822939054

Content Type

Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a
HTTP header that provides the description about what are you sending to the browser.

There are many content types:

 text/html
 text/plain
 application/msword
 application/[Link]-excel
 application/jar
 application/pdf
 application/octet-stream
 application/x-zip
 images/jpeg
 video/quicktime etc.

Servlet API
The [Link] and [Link] packages represent interfaces and classes for servlet api.

The [Link] package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.

The [Link] package contains interfaces and classes that are responsible for http
requests only.

Let's see what are the interfaces of [Link] package.

Interfaces in [Link] package

There are many interfaces in [Link] package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
10 | P a g e Code MicroSystem Arvind Sir 9822939054

9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in [Link] package

There are many classes in [Link] package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in [Link] package

There are many interfaces in [Link] package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in [Link] package

There are many classes in [Link] package. They are as follows:

1. HttpServlet
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
11 | P a g e Code MicroSystem Arvind Sir 9822939054

2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Servlet Interface
Servlet interface provides common behaviour to all the servlets.

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
initializes the servlet. It is the life cycle method of
public void init(ServletConfig config) 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.
is invoked only once and indicates that servlet is
public void destroy()
being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
returns information about servlet such as writer,
public String getServletInfo()
copyright, version etc.

Servlet Example by implementing Servlet interface

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

It will be better if you learn it after visiting steps to create a servlet.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
12 | P a g e Code MicroSystem Arvind Sir 9822939054

File: [Link]

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

GenericServlet class

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It


provides the implementaion of all the methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
13 | P a g e Code MicroSystem Arvind Sir 9822939054

Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse response)
provides service for the incoming request. It is invoked at each time when user requests
for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no
need to call [Link](config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
[Link] file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet
log file and a stack trace.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
14 | P a g e Code MicroSystem Arvind Sir 9822939054

Servlet Example by inheriting the GenericServlet class

Let's see the simple example of servlet by inheriting the GenericServlet class.

It will be better if you learn it after visiting steps to create a servlet.

File: [Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class First extends GenericServlet{
5. public void service(ServletRequest req,ServletResponse res)
6. throws IOException,ServletException{
7.
8. [Link]("text/html");
9.
10. PrintWriter out=[Link]();
11. [Link]("<html><body>");
12. [Link]("<b>hello Arvind Sir</b>");
13. [Link]("</body></html>");
14.
15. }
16. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
15 | P a g e Code MicroSystem Arvind Sir 9822939054

HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the request to


the protected service method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives
the request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles
the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles
the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the
PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles
the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles
the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
16 | P a g e Code MicroSystem Arvind Sir 9822939054

Life Cycle of a Servlet (Servlet Life Cycle)


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

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
17 | P a g e Code MicroSystem Arvind Sir 9822939054

1) Servlet class is loaded

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

2) Servlet instance is created

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

3) init method is invoked

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

1. public void init(ServletConfig config) throws ServletException

4) service method is invoked

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

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked

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

1. public void destroy()

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
18 | P a g e Code MicroSystem Arvind Sir 9822939054

Steps to create a servlet example


There are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

1)Create a directory structures

The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's
see the directory structure that must be followed to create the servlet.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
19 | P a g e Code MicroSystem Arvind Sir 9822939054

As you can see that the servlet class file must be in the classes folder. The [Link] file must be
under the WEB-INF folder.

2)Create a Servlet

There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http
requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this example, we
are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice
that get request is the default request.

[Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
20 | P a g e Code MicroSystem Arvind Sir 9822939054

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. [Link]("text/html");//setting the content type
9. PrintWriter pw=[Link]();//get the stream to write the data
10.
11. //writing html in the stream
12. [Link]("<html><body>");
13. [Link]("Welcome to servlet");
14. [Link]("</body></html>");
15.
16. [Link]();//closing the stream
17. }}

3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:

Jar file Server

1) [Link] Apache Tomacat

2) [Link] Weblogic

3) [Link] Glassfish

4) [Link] JBoss

Two ways to load the jar file

1. set classpath
2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in
WEB-INF/classes directory.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
21 | P a g e Code MicroSystem Arvind Sir 9822939054

4)Create the deployment descriptor ([Link] file)

The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.

The web container uses the Parser to get the information from the [Link] file. There are many
xml parsers such as SAX, DOM and Pull.

There are many elements in the [Link] file. Here is given some necessary elements to run the
simple servlet program.

[Link] file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>microsystem</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>microsystem</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Description of the elements of [Link] file

There are too many elements in the [Link] file. Here is the illustration of some elements that is
used in the above [Link] file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
22 | P a g e Code MicroSystem Arvind Sir 9822939054

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the [Link] file under apache-tomcat/bin
directory.

One Tsime Configuration for Apache Tomcat Server

You need to perform 2 tasks:

1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).


2. Change the port number of tomcat (optional). It is required if another server is running on same
port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment
variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on
the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk
folder in variable value -> ok -> ok -> ok.

Go to My Computer properties:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
23 | P a g e Code MicroSystem Arvind Sir 9822939054

Click on advanced system settings tab then environment variables:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
24 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
25 | P a g e Code MicroSystem Arvind Sir 9822939054

Click on the new tab of user variable or system variable:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
26 | P a g e Code MicroSystem Arvind Sir 9822939054

Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
27 | P a g e Code MicroSystem Arvind Sir 9822939054

There must not be semicolon (;) at the end of the path.

After setting the JAVA_HOME double click on the [Link] file in apache tomcat/bin.

Note: There are two types of tomcat available:

1. Apache tomcat that needs to extract only (no need to install)


2. Apache tomcat that needs to install

It is the example of apache tomcat that needs to extract only.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
28 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
29 | P a g e Code MicroSystem Arvind Sir 9822939054

Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with
same port [Link] you have installed oracle, you need to change the port number of
apache tomcat because both have the default port number 8080.

Open [Link] file in notepad. It is located inside the apache-tomcat/conf directory . Change
the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us
replace it by 9999 and save this file.

5) How to deploy the servlet project

Copy the project and paste it in the webapps folder under apache tomcat.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
30 | P a g e Code MicroSystem Arvind Sir 9822939054

But there are several ways to deploy the project. They are as follows:

 By copying the context(project) folder into the webapps directory


 By copying the war folder into the webapps directory
 By selecting the folder path from the server
 By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use
jar tool to create the war file. Go inside the project directory (before the WEB-INF), then write:

1. projectfolder> jar cvf [Link] *

Creating war file has an advantage that moving the project from one location to another takes
less time.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
31 | P a g e Code MicroSystem Arvind Sir 9822939054

6) How to access the servlet

Open broser and write [Link] For example:

1. [Link]

How Servlet works?


It is important to learn how servlet works for understanding the servlet well. Here, we are going
to get the internal detail about the first servlet program.

The server checks if the servlet is requested for the first time.

If yes, web container does the following tasks:

 loads the servlet class.


 instantiates the servlet class.
 calls the init method passing the ServletConfig object

else

 calls the service method passing request and response objects

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
32 | P a g e Code MicroSystem Arvind Sir 9822939054

The web container calls the destroy method when it needs to remove the servlet such as at time
of stopping server or undeploying the project.

How web container handles the servlet request?

The web container is responsible to handle the request. Let's see how it handles the request.

 maps the request with the servlet in the [Link] file.


 creates request and response objects for this request
 calls the service method on the thread
 The public service method internally calls the protected service method
 The protected service method calls the doGet method depending on the type of request.
 The doGet method generates the response and it is passed to the client.
 After sending the response, the web container deletes the request and response objects.
The thread is contained in the thread pool or deleted depends on the server
implementation.

What is written inside the public service method?

The public service method converts the ServletRequest object into the HttpServletRequest type
and ServletResponse object into the HttpServletResponse type. Then, calls the service method
passing these objects. Let's see the internal code:

1. public void service(ServletRequest req, ServletResponse res)


2. throws ServletException, IOException
3. {
4. HttpServletRequest request;
5. HttpServletResponse response;
6. try
7. {
8. request = (HttpServletRequest)req;
9. response = (HttpServletResponse)res;
10. }
11. catch(ClassCastException e)
12. {
13. throw new ServletException("non-HTTP request or response");
14. }
15. service(request, response);
16. }

What is written inside the protected service method?


Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
33 | P a g e Code MicroSystem Arvind Sir 9822939054

The protected service method checks the type of request, if request type is get, it calls doGet
method, if request type is post, it calls doPost method, so on. Let's see the internal code:

1. protected void service(HttpServletRequest req, HttpServletResponse resp)


2. throws ServletException, IOException
3. {
4. String method = [Link]();
5. if([Link]("GET"))
6. {
7. long lastModified = getLastModified(req);
8. if(lastModified == -1L)
9. {
10. doGet(req, resp);
11. }
12. ....
13. //rest of the code
14. }
15. }

War File
A war (web archive) File contains files of a web project. It may have servlet, xml, jsp, image,
html, css, js etc. files.

Here, we will discuss what is war file, how to create war file, how to deploy war file and how to
extract war file.

What is war file?


web archive (war) file contains all the contents of a web application. It reduces the time duration
for transferring file.

Advantage of war file


saves time: The war file combines all the files into a single unit. So it takes less time while
transferring file from client to server.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
34 | P a g e Code MicroSystem Arvind Sir 9822939054

How to create war file?


To create war file, you need to use jar tool of JDK. You need to use -c switch of jar, to create
the war file.

Go inside the project directory of your project (outside the WEB-INF), then write the following
command:

1. jar -cvf [Link] *.*

Here, -c is used to create file, -v to generate the verbose output and -f to specify the arhive file
name.

The * (asterisk) symbol signifies that all the files of this directory (including sub directory).

How to deploy the war file?


There are two ways to deploy the war file.

1. By server console panel


2. By manually having the war file in specific folder of server.

If you want to deploy the war file in apache tomcat server manually, go to the webapps
directory of apache tomcat and paste the war file here.

Now, you are able to access the web project through browser.

Note: server will extract the war file internally.

How to extract war file manually?


To extract the war file, you need to use -x switch of jar tool of JDK. Let's see the command to
extract the war file.

1. jar -xvf [Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
35 | P a g e Code MicroSystem Arvind Sir 9822939054

welcome-file-list in [Link]
The welcome-file-list element of web-app, is used to define a list of welcome files. Its sub
element is welcome-file that is used to define the welcome file.

A welcome file is the file that is invoked automatically by the server, if you don't specify any file
name.

By default server looks for the welcome file in following order:

1. welcome-file-list in [Link]
2. [Link]
3. [Link]
4. [Link]

If none of these files are found, server renders 404 error.

If you have specified welcome-file in [Link], and all the files [Link], [Link] and
[Link] exists, priority goes to welcome-file.

If welcome-file-list entry doesn't exist in [Link] file, priority goes to [Link] file then
[Link] and at last [Link] file.

Let's see the [Link] file that defines the welcome files.

[Link]

1. <web-app>
2. ....
3.
4. <welcome-file-list>
5. <welcome-file>[Link]</welcome-file>
6. <welcome-file>[Link]</welcome-file>
7. </welcome-file-list>
8. </web-app>

Now, [Link] and [Link] will be the welcome files.

If you have the welcome file, you can directory invoke the project as given below:

1. [Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
36 | P a g e Code MicroSystem Arvind Sir 9822939054

load on startup in [Link]


The load-on-startup element of web-app loads the servlet at the time of deployment or server
start if value is positive. It is also known as pre initialization of servlet.

You can pass positive and negative value for the servlet.

Advantage of load-on-startup element

As you know well, servlet is loaded at first request. That means it consumes more time at first
request. If you specify the load-on-startup in [Link], servlet will be loaded at project
deployment time or server start. So, it will take less time for responding to first request.

Passing positive value

If you pass the positive value, the lower integer value servlet will be loaded before the higher
integer value servlet. In other words, container loads the servlets in ascending integer value. The
0 value will be loaded first then 1, 2, 3 and so on.

Let's try to understand it by the example given below:

[Link]

1. <web-app>
2. ....
3.
4. <servlet>
5. <servlet-name>servlet1</servlet-name>
6. <servlet-class> [Link]</servlet-class>
7. <load-on-startup>0</load-on-startup>
8. </servlet>
9.
10. <servlet>
11. <servlet-name>servlet2</servlet-name>
12. <servlet-class>[Link]</servlet-class>
13. <load-on-startup>1</load-on-startup>
14. </servlet>
15.
16. ...
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
37 | P a g e Code MicroSystem Arvind Sir 9822939054

17. </web-app>

There are defined 2 servlets, both servlets will be loaded at the time of project deployment or
server start. But, servlet1 will be loaded first then servlet2.

Passing negative value

If you pass the negative value, servlet will be loaded at request time, at first request.

Creating Servlet Example in Eclipse


Eclipse is an open-source ide for developing JavaSE and JavaEE (J2EE) applications. You can
download the eclipse ide from the eclipse website [Link]

You need to download the eclipse ide for JavaEE developers.

Creating servlet example in eclipse ide, saves a lot of work to be done. It is easy and simple to
create a servlet example. Let's see the steps, you need to follow to create the first servlet
example.

 Create a Dynamic web project


 create a servlet
 add [Link] file
 Run the servlet

1) Create the dynamic web project:

For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic
web project -> write your project name e.g. first -> Finish.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
38 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
39 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
40 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
41 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
42 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
43 | P a g e Code MicroSystem Arvind Sir 9822939054

2) Create the servlet in eclipse IDE:

For creating a servlet, explore the project by clicking the + icon -> explore the Java
Resources -> right click on src -> New -> servlet -> write your servlet name e.g. Hello ->
uncheck all the checkboxes except doGet() -> next -> Finish.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
44 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
45 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
46 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
47 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
48 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
49 | P a g e Code MicroSystem Arvind Sir 9822939054

3) add jar file in eclipse IDE:

For adding a jar file, right click on your project -> Build Path -> Configure Build Path ->
click on Libraries tab in Java Build Path -> click on Add External JARs button -> select
the [Link] file under tomcat/lib -> ok.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
50 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
51 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
52 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
53 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
54 | P a g e Code MicroSystem Arvind Sir 9822939054

Now servlet has been created, Let's write the first servlet code.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
55 | P a g e Code MicroSystem Arvind Sir 9822939054

4) Start the server and deploy the project:

For starting the server and deploying the project in one step, Right click on your project ->
Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
56 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
57 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
58 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
59 | P a g e Code MicroSystem Arvind Sir 9822939054

Now tomcat server has been started and project is deployed. To access the servlet write the url
pattern name in the URL bar of the browser. In this case Hello then enter.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
60 | P a g e Code MicroSystem Arvind Sir 9822939054

How to configure tomcat server in Eclipse ? (One time Requirement)

If you are using Eclipse IDE first time, you need to configure the tomcat server First.

For configuring the tomcat server in eclipse IDE, click on servers tab at the bottom side of the
IDE -> right click on blank area -> New -> Servers -> choose tomcat then its version ->
next -> click on Browse button -> select the apache tomcat root folder previous to bin ->
next -> addAll -> Finish.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
61 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
62 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
63 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
64 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
65 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
66 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
67 | P a g e Code MicroSystem Arvind Sir 9822939054

Now tomcat7 server has been configured in eclipse IDE.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
68 | P a g e Code MicroSystem Arvind Sir 9822939054

ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a servlet such as
content type, content length, parameter names and values, header informations, attributes etc.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
69 | P a g e Code MicroSystem Arvind Sir 9822939054

Methods of Servlet

Request interface

There are many methods defined in the ServletRequest interface. Some of them are as follows:

Method Description
public String getParameter(String
is used to obtain the value of a parameter by name.
name)
returns an array of String containing all values of
public String[]
given parameter name. It is mainly used to obtain
getParameterValues(String name)
values of a Multi select list box.
[Link] returns an enumeration of all of the request
getParameterNames() parameter names.
Returns the size of the request entity data, or -1 if not
public int getContentLength()
known.
Returns the character set encoding for the input of
public String getCharacterEncoding()
this request.
Returns the Internet Media Type of the request entity
public String getContentType()
data, or null if not known.
public ServletInputStream Returns an input stream for reading binary data in the
getInputStream() throws IOException request body.
Returns the host name of the server that received the
public abstract String getServerName()
request.
Returns the port number on which this request was
public int getServerPort()
received.

Example of ServletRequest to display the name of the user

In this example, we are displaying the name of the user in the servlet. For this purpose, we have
used the getParameter method that returns the value for the given request parameter name.

[Link]

1. <form action="welcome" method="get">


2. Enter your name<input type="text" name="name"><br>
3. <input type="submit" value="login">
4. </form>

[Link]
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
70 | P a g e Code MicroSystem Arvind Sir 9822939054

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class DemoServ extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. [Link]("text/html");
9. PrintWriter pw=[Link]();
10.
11. String name=[Link]("name");//will return value
12. [Link]("Welcome "+name);
13.
14. [Link]();
15. }}

RequestDispatcher in Servlet
The RequestDispacher interface provides the facility of dispatching the request to another
resource it may be html, servlet or [Link] interface can also be used to include the content of
antoher resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse response)throws


ServletException,[Link]:Forwards a request from a servlet to another resource
(servlet, JSP file, or HTML file) on the server.
2. public void include(ServletRequest request,ServletResponse response)throws
ServletException,[Link]:Includes the content of a resource (servlet, JSP page, or
HTML file) in the response.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
71 | P a g e Code MicroSystem Arvind Sir 9822939054

As you see in the above figure, response of second servlet is sent to the client. Response of the
first servlet is not displayed to the user.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
72 | P a g e Code MicroSystem Arvind Sir 9822939054

As you can see in the above figure, response of second servlet is included in the response of the first
servlet that is being sent to the client.

How to get the object of RequestDispatcher

The getRequestDispatcher() method of ServletRequest interface returns the object of


RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method

1. public RequestDispatcher getRequestDispatcher(String resource);

Example of using getRequestDispatcher method

1. RequestDispatcher rd=[Link]("servlet2");
2. //servlet2 is the url-pattern of the second servlet
3.
4. [Link](request, response);//method may be include or forward

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
73 | P a g e Code MicroSystem Arvind Sir 9822939054

Example of RequestDispatcher interface

In this example, we are validating the password entered by the user. If password is servlet, it will
forward the request to the WelcomeServlet, otherwise will show an error message: sorry
username or password error!. In this program, we are cheking for hardcoded information. But
you can check it to the database also that we will see in the development chapter. In this
example, we have created following files:

 [Link] file: for getting input from the user.


 [Link] file: a servlet class for processing the response. If password is servet, it will forward
the request to the welcome servlet.
 [Link] file: a servlet class for displaying the welcome message.
 [Link] file: a deployment descriptor file that contains the information about the servlet.

[Link]

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


2. Name:<input type="text" name="userName"/><br/>
3. Password:<input type="password" name="userPass"/><br/>
4. <input type="submit" value="login"/>
5. </form>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
74 | P a g e Code MicroSystem Arvind Sir 9822939054

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class Login extends HttpServlet {
7.

8. public void doPost(HttpServletRequest request, HttpServletResponse response)


9. throws ServletException, IOException {
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. String n=[Link]("userName");
15. String p=[Link]("userPass");
16.
17. if([Link]("servlet"){
18. RequestDispatcher rd=[Link]("servlet2");
19. [Link](request, response);
20. }
21. else{
22. [Link]("Sorry UserName or Password Error!");
23. RequestDispatcher rd=[Link]("/[Link]");
24. [Link](request, response);
25.
26. }
27. }
28.
29. }

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5. public class WelcomeServlet extends HttpServlet {
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
75 | P a g e Code MicroSystem Arvind Sir 9822939054

6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response)
8. throws ServletException, IOException {
9.
10. [Link]("text/html");
11. PrintWriter out = [Link]();
12.
13. String n=[Link]("userName");
14. [Link]("Welcome "+n);
15. }
16.
17. }

[Link]

1. <web-app>
2. <servlet>
3. <servlet-name>Login</servlet-name>
4. <servlet-class>Login</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>WelcomeServlet</servlet-name>
8. <servlet-class>WelcomeServlet</servlet-class>
9. </servlet>
10.
11.
12. <servlet-mapping>
13. <servlet-name>Login</servlet-name>
14. <url-pattern>/servlet1</url-pattern>
15. </servlet-mapping>
16. <servlet-mapping>
17. <servlet-name>WelcomeServlet</servlet-name>
18. <url-pattern>/servlet2</url-pattern>
19. </servlet-mapping>
20.
21. <welcome-file-list>
22. <welcome-file>[Link]</welcome-file>
23. </welcome-file-list>
24. </web-app>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
76 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
77 | P a g e Code MicroSystem Arvind Sir 9822939054

SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response
to another resource, it may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
78 | P a g e Code MicroSystem Arvind Sir 9822939054

Difference between forward() and sendRedirect() method


There are many differences between the forward() method of RequestDispatcher and
sendRedirect() method of HttpServletResponse interface. They are given below:

forward() method sendRedirect() method

The sendRedirect() method works


The forward() method works at server side.
at client side.

It sends the same request and response objects to another servlet. It always sends a new request.

It can be used within and outside


It can work within the server only.
the server.

Example: Example:
[Link]("servlet2").forward(request,response) [Link]("servlet2")
; ;

Syntax of sendRedirect() method

public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method

[Link]("[Link]

Full example of sendRedirect method in servlet

In this example, we are redirecting the request to the google server. Notice that sendRedirect method
works at client side, that is why we can our request to anywhere. We can send our request within and
outside the server.

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
79 | P a g e Code MicroSystem Arvind Sir 9822939054

5. public class DemoServlet extends HttpServlet{


6. public void doGet(HttpServletRequest req,HttpServletResponse res)
7. throws ServletException,IOException
8. {
9. [Link]("text/html");
10. PrintWriter pw=[Link]();
11.
12. [Link]("[Link]
13.
14. [Link]();
15. }}

Creating custom google search using sendRedirect

In this example, we are using sendRedirect method to send request to google server with the
request data.

[Link]

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>sendRedirect example</title>
6. </head>
7. <body>
8.
9.
10. <form action="MySearcher">
11. <input type="text" name="name">
12. <input type="submit" value="Google Search">
13. </form>
14.
15. </body>
16. </html>

[Link]

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6.
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
80 | P a g e Code MicroSystem Arvind Sir 9822939054

7. public class MySearcher extends HttpServlet {


8. protected void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. String name=[Link]("name");
12. [Link]("[Link]
13. }
14. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
81 | P a g e Code MicroSystem Arvind Sir 9822939054

Output

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
82 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
83 | P a g e Code MicroSystem Arvind Sir 9822939054

ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This object can be
used to get configuration information from [Link] file.

If the configuration information is modified from the [Link] file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from
time to time.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
84 | P a g e Code MicroSystem Arvind Sir 9822939054

Advantage of ServletConfig

The core advantage of ServletConfig is that you don't need to edit the servlet file if information
is modified from the [Link] file.

Methods of ServletConfig interface

1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization
parameter names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of ServletContext.

How to get the object of ServletConfig

getServletConfig() method of Servlet interface returns the object of ServletConfig.

Syntax of getServletConfig() method

public ServletConfig getServletConfig();

Example of getServletConfig() method

ServletConfig config=getServletConfig();

//Now we can call the methods of ServletConfig interface

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.

1. <web-app>
2. <servlet>
3. ......
4.
5. <init-param>
6. <param-name>parametername</param-name>
7. <param-value>parametervalue</param-value>
8. </init-param>
9. </servlet>
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
85 | P a g e Code MicroSystem Arvind Sir 9822939054

10. </web-app>

Example of ServletConfig to get initialization parameter

In this example, we are getting the one initialization parameter from the [Link] file and
printing this information in the servlet.

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5. public class DemoServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8.
9. [Link]("text/html");
10. PrintWriter out = [Link]();
11.
12. ServletConfig config=getServletConfig();
13. String driver=[Link]("driver");
14. [Link]("Driver is: "+driver);
15.
16. [Link]();
17. }
18.
19. }

[Link]

1. <web-app>
2.
3. <servlet>
4. <servlet-name>DemoServlet</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6.
7. <init-param>
8. <param-name>driver</param-name>
9. <param-value>[Link]</param-value>
10. </init-param>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
86 | P a g e Code MicroSystem Arvind Sir 9822939054

11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>DemoServlet</servlet-name>
16. <url-pattern>/servlet1</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>

Example of ServletConfig to get all the initialization parameters

In this example, we are getting all the initialization parameter from the [Link] file and printing
this information in the servlet.

[Link]

1. import [Link];
2. import [Link];
3. import [Link];
4.
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10.
11.
12. public class DemoServlet extends HttpServlet {
13. public void doGet(HttpServletRequest request, HttpServletResponse response)
14. throws ServletException, IOException {
15.
16. [Link]("text/html");
17. PrintWriter out = [Link]();
18.
19. ServletConfig config=getServletConfig();
20. Enumeration<String> e=[Link]();
21.
22. String str="";
23. while([Link]()){
24. str=[Link]();
25. [Link]("<br>Name: "+str);

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
87 | P a g e Code MicroSystem Arvind Sir 9822939054

26. [Link](" value: "+[Link](str));


27. }
28.
29. [Link]();
30. }
31.
32. }

[Link]

1. <web-app>
2.
3. <servlet>
4. <servlet-name>DemoServlet</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6.
7. <init-param>
8. <param-name>username</param-name>
9. <param-value>system</param-value>
10. </init-param>
11.
12. <init-param>
13. <param-name>password</param-name>
14. <param-value>oracle</param-value>
15. </init-param>
16.
17. </servlet>
18.
19. <servlet-mapping>
20. <servlet-name>DemoServlet</servlet-name>
21. <url-pattern>/servlet1</url-pattern>
22. </servlet-mapping>
23.
24. </web-app>

ServletContext Interface

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
88 | P a g e Code MicroSystem Arvind Sir 9822939054

An object of ServletContext is created by the web container at time of deploying the project.
This object can be used to get configuration information from [Link] file. There is only one
ServletContext object per web application.

If any information is shared to many servlet, it is better to provide it from the [Link] file using
the <context-param> element.

Advantage of ServletContext

Easy to maintain if any information is shared to all the servlet, it is better to make it available
for all the servlet. We provide this information from the [Link] file, so if the information is
changed, we don't need to modify the servlet. Thus it removes maintenance problem.

Usage of ServletContext Interface

There can be a lot of usage of ServletContext object. Some of them are as follows:

1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the [Link] file.
3. The ServletContext object can be used to set, get or remove attribute from the [Link] file.
4. The ServletContext object can be used to provide inter-application communication.

Commonly used methods of ServletContext interface

There is given some commonly used methods of ServletContext interface.

1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's initialization

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
89 | P a g e Code MicroSystem Arvind Sir 9822939054

parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application
scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.
5. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given name from the
servlet context.

How to get the object of ServletContext interface

1. getServletContext() method of ServletConfig interface returns the object of ServletContext.


2. getServletContext() method of GenericServlet class returns the object of ServletContext.

Syntax of getServletContext() method

1. public ServletContext getServletContext()

Example of getServletContext() method

1. //We can get the ServletContext object from ServletConfig object


2. ServletContext application=getServletConfig().getServletContext();
3.
4. //Another convenient way to get the ServletContext object
5. ServletContext application=getServletContext();

Syntax to provide the initialization parameter in Context scope

The context-param element, subelement of web-app, is used to define the initialization parameter in
the application scope. The param-name and param-value are the sub-elements of the context-param.
The param-name element defines parameter name and and param-value defines its value.

1. <web-app>
2. ......
3.
4. <context-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </context-param>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
90 | P a g e Code MicroSystem Arvind Sir 9822939054

8. ......
9. </web-app>

Example of ServletContext to get the initialization parameter

In this example, we are getting the initialization parameter from the [Link] file and printing the value
of the initialization parameter. Notice that the object of ServletContext represents the application
scope. So if we change the value of the parameter from the [Link] file, all the servlet classes will get
the changed value. So we don't need to modify the servlet. So it is better to have the common
information for most of the servlets in the [Link] file by context-param element. Let's see the simple
example:

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class DemoServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. throws ServletException,IOException
9. {
10. [Link]("text/html");
11. PrintWriter pw=[Link]();
12.
13. //creating ServletContext object
14. ServletContext context=getServletContext();
15.
16. //Getting the value of the initialization parameter and printing it
17. String driverName=[Link]("dname");
18. [Link]("driver name is="+driverName);
19.
20. [Link]();
21.
22. }}

[Link]

1. <web-app>
2.
3. <servlet>
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
91 | P a g e Code MicroSystem Arvind Sir 9822939054

4. <servlet-name>microsystem</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>[Link]</param-value>
11. </context-param>
12.
13. <servlet-mapping>
14. <servlet-name>microsystem</servlet-name>
15. <url-pattern>/context</url-pattern>
16. </servlet-mapping>
17.
18. </web-app>

Example of ServletContext to get all the initialization parameters

In this example, we are getting all the initialization parameter from the [Link] file. For getting all the
parameters, we have used the getInitParameterNames() method in the servlet class.

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class DemoServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. throws ServletException,IOException
9. {
10. [Link]("text/html");
11. PrintWriter out=[Link]();
12.
13. ServletContext context=getServletContext();
14. Enumeration<String> e=[Link]();
15.
16. String str="";
17. while([Link]()){
18. str=[Link]();
19. [Link]("<br> "+[Link](str));

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
92 | P a g e Code MicroSystem Arvind Sir 9822939054

20. }
21. }}

[Link]

1. <web-app>
2.
3. <servlet>
4. <servlet-name>microsystem</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>[Link]</param-value>
11. </context-param>
12.
13. <context-param>
14. <param-name>username</param-name>
15. <param-value>system</param-value>
16. </context-param>
17.
18. <context-param>
19. <param-name>password</param-name>
20. <param-value>oracle</param-value>
21. </context-param>
22.
23. <servlet-mapping>
24. <servlet-name>microsystem</servlet-name>
25. <url-pattern>/context</url-pattern>
26. </servlet-mapping>
27.
28. </web-app>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
93 | P a g e Code MicroSystem Arvind Sir 9822939054

Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one of the following
scopes:

1. request scope
2. session scope
3. application scope

The servlet programmer can pass informations from one servlet to another using attributes. It is
just like passing object from one class to another so that we can reuse the same object again and
again.

Attribute specific methods of ServletRequest, HttpSession and ServletContext


interface

There are following 4 attribute specific methods. They are as follows:

1. public void setAttribute(String name,Object object):sets the given object in the


application scope.
2. public Object getAttribute(String name):Returns the attribute for the specified name.
3. public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters as an Enumeration of String objects.
4. public void removeAttribute(String name):Removes the attribute with the given name
from the servlet context.

Example of ServletContext to set and get attribute

In this example, we are setting the attribute in the application scope and getting that value from
another servlet.

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class DemoServlet1 extends HttpServlet{

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
94 | P a g e Code MicroSystem Arvind Sir 9822939054

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

[Link]("text/html");
PrintWriter out=[Link]();
ServletContext sc=getServletContext();
[Link]("companyName", "Code MicroSystem");
[Link]("<a href='NextServlet'> Visit</a>");
[Link]();

}}

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class NextServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. {
9. try{
10.
11. [Link]("text/html");
12. PrintWriter out=[Link]();
13.
14. ServletContext context=getServletContext();
15. String n=(String)[Link]("companyName ");
16.
17. [Link]("Welcome to "+n);
18. [Link]();
19.
20. }catch(Exception e){[Link](e);}
21.
22. }}

[Link]

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
95 | P a g e Code MicroSystem Arvind Sir 9822939054

5. <servlet-class>DemoServlet1</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>DemoServlet2</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>

Difference between ServletConfig and ServletContext

The servletconfig object refers to the single servlet whereas servletcontext object refers to the
whole web application.

Session Tracking in Servlets


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:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
96 | P a g e Code MicroSystem Arvind Sir 9822939054

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

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
97 | P a g e Code MicroSystem Arvind Sir 9822939054

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
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
98 | P a g e Code MicroSystem Arvind Sir 9822939054

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

Cookie class

[Link] 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)

Returns the name of the cookie. The name cannot be changed after
public String getName()
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


Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
99 | P a g e Code MicroSystem Arvind Sir 9822939054

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","Code MicroSystem");//creating cookie object


2. [Link](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. [Link](0);//changing the maximum age to 0 seconds
3. [Link](ck);//adding cookie in the response

How to get Cookies?

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

1. Cookie ck[]=[Link]();
2. for(int i=0;i<[Link];i++){
3. [Link]("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }

Simple example of Servlet Cookies

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
100 | P a g e Code MicroSystem Arvind Sir 9822939054

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.

[Link]

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


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

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. String n=[Link]("userName");
15. [Link]("Welcome "+n);
16.
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
101 | P a g e Code MicroSystem Arvind Sir 9822939054

17. Cookie ck=new Cookie("uname",n);//creating cookie object


18. [Link](ck);//adding cookie in the response
19.
20. //creating submit button
21. [Link]("<form action='servlet2'>");
22. [Link]("<input type='submit' value='go'>");
23. [Link]("</form>");
24.
25. [Link]();
26.
27. }catch(Exception e){[Link](e);}
28. }
29. }

[Link]

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

[Link]

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
102 | P a g e Code MicroSystem Arvind Sir 9822939054

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>

Output::

Servlet Login and Logout Example using


Cookies
A cookie is a kind of information that is stored at client side.

In the previous page, we learned a lot about cookie e.g. how to create cookie, how to delete
cookie, how to get cookie etc.

Here, we are going to create a login and logout example using servlet cookies.

In this example, we are creating 3 links: login, logout and profile. User can't go to profile page
until he/she is logged in. If user is logged out, he need to login again to visit profile.

In this application, we have created following files.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
103 | P a g e Code MicroSystem Arvind Sir 9822939054

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]

File: [Link]

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Servlet Login Example</title>
6. </head>
7. <body>
8.
9. <h1>Welcome to Login App by Cookie</h1>
10. <a href="[Link]">Login</a>|
11. <a href="LogoutServlet">Logout</a>|
12. <a href="ProfileServlet">Profile</a>
13.
14. </body>
15. </html>

File: [Link]

1. <a href="[Link]">Login</a> |
2. <a href="LogoutServlet">Logout</a> |
3. <a href="ProfileServlet">Profile</a>
4. <hr>

File: [Link]

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


2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
5. </form>

File: [Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
104 | P a g e Code MicroSystem Arvind Sir 9822939054

1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. public class LoginServlet extends HttpServlet {
11. protected void doPost(HttpServletRequest request, HttpServletResponse response)
12. throws ServletException, IOException {
13. [Link]("text/html");
14. PrintWriter out=[Link]();
15.
16. [Link]("[Link]").include(request, response);
17.
18. String name=[Link]("name");
19. String password=[Link]("password");
20.
21. if([Link]("admin123")){
22. [Link]("You are successfully logged in!");
23. [Link]("<br>Welcome, "+name);
24.
25. Cookie ck=new Cookie("name",name);
26. [Link](ck);
27. }else{
28. [Link]("sorry, username or password error!");
29. [Link]("[Link]").include(request, response);
30. }
31.
32. [Link]();
33. }
34.
35. }

File: [Link]

1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
105 | P a g e Code MicroSystem Arvind Sir 9822939054

8. import [Link];
9. import [Link];
10. public class LogoutServlet extends HttpServlet {
11. protected void doGet(HttpServletRequest request, HttpServletResponse response)
12. throws ServletException, IOException {
13. [Link]("text/html");
14. PrintWriter out=[Link]();
15.
16.
17. [Link]("[Link]").include(request, response);
18.
19. Cookie ck=new Cookie("name","");
20. [Link](0);
21. [Link](ck);
22.
23. [Link]("you are successfully logged out!");
24. }
25. }

File: [Link]

1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. public class ProfileServlet extends HttpServlet {
11. protected void doGet(HttpServletRequest request, HttpServletResponse response)
12. throws ServletException, IOException {
13. [Link]("text/html");
14. PrintWriter out=[Link]();
15.
16. [Link]("[Link]").include(request, response);
17.
18. Cookie ck[]=[Link]();
19. if(ck!=null){
20. String name=ck[0].getValue();
21. if(![Link]("")||name!=null){
22. [Link]("<b>Welcome to Profile</b>");
23. [Link]("<br>Welcome, "+name);
24. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
106 | P a g e Code MicroSystem Arvind Sir 9822939054

25. }else{
26. [Link]("Please login first");
27. [Link]("[Link]").include(request, response);
28. }
29. [Link]();
30. }
31. }

File: [Link]

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app xmlns:xsi="[Link]
3. xmlns="[Link] xsi:schemaLocation="[Link]
avaee
4. [Link] id="WebApp_ID" version="2.5">
5.
6. <servlet>
7. <description></description>
8. <display-name>LoginServlet</display-name>
9. <servlet-name>LoginServlet</servlet-name>
10. <servlet-class>[Link]</servlet-class>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>LoginServlet</servlet-name>
14. <url-pattern>/LoginServlet</url-pattern>
15. </servlet-mapping>
16. <servlet>
17. <description></description>
18. <display-name>ProfileServlet</display-name>
19. <servlet-name>ProfileServlet</servlet-name>
20. <servlet-class>[Link]</servlet-class>
21. </servlet>
22. <servlet-mapping>
23. <servlet-name>ProfileServlet</servlet-name>
24. <url-pattern>/ProfileServlet</url-pattern>
25. </servlet-mapping>
26. <servlet>
27. <description></description>
28. <display-name>LogoutServlet</display-name>
29. <servlet-name>LogoutServlet</servlet-name>
30. <servlet-class>[Link]</servlet-class>
31. </servlet>
32. <servlet-mapping>
33. <servlet-name>LogoutServlet</servlet-name>
34. <url-pattern>/LogoutServlet</url-pattern>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
107 | P a g e Code MicroSystem Arvind Sir 9822939054

35. </servlet-mapping>
36. </web-app>

download this example (developed using Eclipse IDE)

Output

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
108 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
109 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
110 | P a g e Code MicroSystem Arvind Sir 9822939054

2) 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.

<input type="hidden" name="uname" value="Code MicroSystem ">

Here, uname is the hidden field name and Code Microsyste 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.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
111 | P a g e Code MicroSystem Arvind Sir 9822939054

[Link]

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

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5. public class FirstServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response){
7. try{
8.
9. [Link]("text/html");
10. PrintWriter out = [Link]();
11.
12. String n=[Link]("userName");
13. [Link]("Welcome "+n);
14.
15. //creating form that have invisible textfield
16. [Link]("<form action='servlet2'>");
17. [Link]("<input type='hidden' name='uname' value='"+n+"'>");
18. [Link]("<input type='submit' value='go'>");
19. [Link]("</form>");
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
112 | P a g e Code MicroSystem Arvind Sir 9822939054

20. [Link]();
21.
22. }catch(Exception e){[Link](e);}
23. }
24.
25. }

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class SecondServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response)
6. try{
7. [Link]("text/html");
8. PrintWriter out = [Link]();
9.
10. //Getting the value from the hidden field
11. String n=[Link]("uname");
12. [Link]("Hello "+n);
13.
14. [Link]();
15. }catch(Exception e){[Link](e);}
16. }
17. }

[Link]

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>
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
113 | P a g e Code MicroSystem Arvind Sir 9822939054

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
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.
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
114 | P a g e Code MicroSystem Arvind Sir 9822939054

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.

[Link]

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

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. String n=[Link]("userName");
15. [Link]("Welcome "+n);
16.
17. //appending the username in the query string
18. [Link]("<a href='servlet2?uname="+n+"'>visit</a>");
19.
20. [Link]();
21.
22. }catch(Exception e){[Link](e);}
23. }
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
115 | P a g e Code MicroSystem Arvind Sir 9822939054

24.
25. }

[Link]

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

[Link]

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>
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
116 | P a g e Code MicroSystem Arvind Sir 9822939054

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
In such case, container creates a session id for each [Link] container uses this id to identify the
particular [Link] 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:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
117 | P a g e Code MicroSystem Arvind Sir 9822939054

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.

[Link]

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

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. [Link]("text/html");
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
118 | P a g e Code MicroSystem Arvind Sir 9822939054

12. PrintWriter out = [Link]();


13.
14. String n=[Link]("userName");
15. [Link]("Welcome "+n);
16.
17. HttpSession session=[Link]();
18. [Link]("uname",n);
19.
20. [Link]("<a href='servlet2'>visit</a>");
21.
22. [Link]();
23.
24. }catch(Exception e){[Link](e);}
25. }
26.
27. }

[Link]

1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. [Link]("text/html");
11. PrintWriter out = [Link]();
12.
13. HttpSession session=[Link](false);
14. String n=(String)[Link]("uname");
15. [Link]("Hello "+n);
16.
17. [Link]();
18.
19. }catch(Exception e){[Link](e);}
20. }
21.
22.
23. }

[Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
119 | P a g e Code MicroSystem Arvind Sir 9822939054

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>

Servlet HttpSession Login and Logout


Example
We can bind the objects on HttpSession instance and get the objects by using setAttribute and
getAttribute methods.

In the previous page, we have learnt about what is HttpSession, How to store and get data from
session object etc.

Here, we are going to create a real world login and logout application without using database
code. We are assuming that password is admin123.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
120 | P a g e Code MicroSystem Arvind Sir 9822939054

Visit here for login and logout application using cookies only servlet login and logout example
using cookies

In this example, we are creating 3 links: login, logout and profile. User can't go to profile page
until he/she is logged in. If user is logged out, he need to login again to visit profile.

In this application, we have created following files.

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]

File: [Link]

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Servlet Login Example</title>
6. </head>
7. <body>
8.
9. <h1>Login App using HttpSession</h1>
10. <a href="[Link]">Login</a>|
11. <a href="LogoutServlet">Logout</a>|
12. <a href="ProfileServlet">Profile</a>
13.
14. </body>
15. </html>

File: [Link]

1. <a href="[Link]">Login</a> |
2. <a href="LogoutServlet">Logout</a> |
3. <a href="ProfileServlet">Profile</a>
4. <hr>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
121 | P a g e Code MicroSystem Arvind Sir 9822939054

File: [Link]

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


2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
5. </form>

File: [Link]

1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. public class LoginServlet extends HttpServlet {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. [Link]("text/html");
13. PrintWriter out=[Link]();
14. [Link]("[Link]").include(request, response);
15.
16. String name=[Link]("name");
17. String password=[Link]("password");
18.
19. if([Link]("admin123")){
20. [Link]("Welcome, "+name);
21. HttpSession session=[Link]();
22. [Link]("name",name);
23. }
24. else{
25. [Link]("Sorry, username or password error!");
26. [Link]("[Link]").include(request, response);
27. }
28. [Link]();
29. }
30. }

File: [Link]

1. import [Link];
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
122 | P a g e Code MicroSystem Arvind Sir 9822939054

2. import [Link];
3.
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. public class LogoutServlet extends HttpServlet {
10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. [Link]("text/html");
13. PrintWriter out=[Link]();
14.
15. [Link]("[Link]").include(request, response);
16.
17. HttpSession session=[Link]();
18. [Link]();
19.
20. [Link]("You are successfully logged out!");
21.
22. [Link]();
23. }
24. }

File: [Link]

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. public class ProfileServlet extends HttpServlet {
9. protected void doGet(HttpServletRequest request, HttpServletResponse response)
10. throws ServletException, IOException {
11. [Link]("text/html");
12. PrintWriter out=[Link]();
13. [Link]("[Link]").include(request, response);
14.
15. HttpSession session=[Link](false);
16. if(session!=null){
17. String name=(String)[Link]("name");
18.
19. [Link]("Hello, "+name+" Welcome to Profile");

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
123 | P a g e Code MicroSystem Arvind Sir 9822939054

20. }
21. else{
22. [Link]("Please login first");
23. [Link]("[Link]").include(request, response);
24. }
25. [Link]();
26. }
27. }

File: [Link]

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app xmlns:xsi="[Link]
3. xmlns="[Link] xsi:schemaLocation="[Link]
avaee
4. [Link] id="WebApp_ID" version="2.5">
5.
6. <servlet>
7. <description></description>
8. <display-name>LoginServlet</display-name>
9. <servlet-name>LoginServlet</servlet-name>
10. <servlet-class>LoginServlet</servlet-class>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>LoginServlet</servlet-name>
14. <url-pattern>/LoginServlet</url-pattern>
15. </servlet-mapping>
16. <servlet>
17. <description></description>
18. <display-name>ProfileServlet</display-name>
19. <servlet-name>ProfileServlet</servlet-name>
20. <servlet-class>ProfileServlet</servlet-class>
21. </servlet>
22. <servlet-mapping>
23. <servlet-name>ProfileServlet</servlet-name>
24. <url-pattern>/ProfileServlet</url-pattern>
25. </servlet-mapping>
26. <servlet>
27. <description></description>
28. <display-name>LogoutServlet</display-name>
29. <servlet-name>LogoutServlet</servlet-name>
30. <servlet-class>LogoutServlet</servlet-class>
31. </servlet>
32. <servlet-mapping>
33. <servlet-name>LogoutServlet</servlet-name>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
124 | P a g e Code MicroSystem Arvind Sir 9822939054

34. <url-pattern>/LogoutServlet</url-pattern>
35. </servlet-mapping>
36. </web-app>

download this example (developed using Eclipse IDE)

Output

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
125 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
126 | P a g e Code MicroSystem Arvind Sir 9822939054

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
127 | P a g e Code MicroSystem Arvind Sir 9822939054

Event and Listener in Servlet


Events are basically occurrence of something. Changing the state of an object is known as an
event.
We can perform some important tasks at the occurrence of these exceptions, such as counting
total and current logged-in users, creating tables of the database at time of deploying the project,
creating database connection object etc.
There are many Event classes and Listener interfaces in the [Link] and [Link]
packages.

Event classes

The event classes are as follows:

1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent

Event interfaces

The event interfaces are as follows:

1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener

Upcoming topics in Servlet Events and Listeners

ServletContextEvent

Let's see the simple example of ServletContextEvent and ServletContextListener

HttpSessionEvent
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
128 | P a g e Code MicroSystem Arvind Sir 9822939054

Let's see the simple example of HttpSessionEvent and HttpSessionListener

ServletRequestEvent

Let's see the simple example of ServletRequestEvent and ServletRequestListener

ServletContext AttributeEvent

Let's see the simple example of ServletContextAttributeEvent and


ServletContextAttributeListener

HttpSessionBindingEvent

Let's see the simple example of HttpSessionBindingEvent and HttpSessionAttributeListener

Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a request.

It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption
and decryption, input validation etc.

The servlet filter is pluggable, i.e. its entry is defined in the [Link] file, if we remove the
entry of filter from the [Link] file, filter will be removed automatically and we don't need to
change the servlet.

So maintenance cost will be less.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
129 | P a g e Code MicroSystem Arvind Sir 9822939054

Note: Unlike Servlet, One filter doesn't have dependency on another filter.

Usage of Filter

 recording all incoming requests


 logs the IP addresses of the computers from which the requests originate
 conversion
 data compression
 encryption and decryption
 input validation etc.

Advantage of Filter

1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance

Filter API

Like servlet filter have its own API. The [Link] package contains the three interfaces of
Filter API.

1. Filter
2. FilterChain
3. FilterConfig

1) Filter interface

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
130 | P a g e Code MicroSystem Arvind Sir 9822939054

For creating any filter, you must implement the Filter interface. Filter interface provides the life
cycle methods for a filter.

Method Description

init() method is invoked only once. It is used to


public void init(FilterConfig config)
initialize the filter.

public void doFilter(HttpServletRequest doFilter() method is invoked every time when user
request,HttpServletResponse response, FilterChain request to any resource, to which the filter is
chain) [Link] is used to perform filtering tasks.

This is invoked only once when filter is taken out of


public void destroy()
the service.

2) FilterChain interface

The object of FilterChain is responsible to invoke the next filter or resource in the [Link]
object is passed in the doFilter method of Filter [Link] FilterChain interface contains only
one method:

1. public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the


control to the next filter or resource.

How to define Filter

We can define filter same as servlet. Let's see the elements of filter and filter-mapping.

1. <web-app>
2.
3. <filter>
4. <filter-name>...</filter-name>
5. <filter-class>...</filter-class>
6. </filter>
7.
8. <filter-mapping>
9. <filter-name>...</filter-name>
10. <url-pattern>...</url-pattern>
11. </filter-mapping>
12.
13. </web-app>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
131 | P a g e Code MicroSystem Arvind Sir 9822939054

For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an
advantage over servlet-name element i.e. it can be applied on servlet, JSP or HTML.

Simple Example of Filter

In this example, we are simply displaying information that filter is invoked automatically after
the post processing of the request.

[Link]

1. <a href="servlet1">click here</a>

[Link]

1. import [Link];
2. import [Link];
3.
4. import [Link].*;
5.
6. public class MyFilter implements Filter{
7.
8. public void init(FilterConfig arg0) throws ServletException {}
9.
10. public void doFilter(ServletRequest req, ServletResponse resp,
11. FilterChain chain) throws IOException, ServletException {
12.
13. PrintWriter out=[Link]();
14. [Link]("filter is invoked before");
15.
16. [Link](req, resp);//sends request to next resource
17.
18. [Link]("filter is invoked after");
19. }
20. public void destroy() {}
21. }

[Link]

1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link].*;

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
132 | P a g e Code MicroSystem Arvind Sir 9822939054

6.
7. public class HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. [Link]("<br>welcome to servlet<br>");
15.
16. }
17.
18. }

[Link]
For defining the filter, filter element of web-app must be defined just like servlet.

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

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
133 | P a g e Code MicroSystem Arvind Sir 9822939054

Authentication Filter
We can perform authentication in filter. Here, we are going to check to password given by the
user in filter class, if given password is admin, it will forward the request to the WelcomeAdmin
servlet otherwise it will display error message.

Example of authenticating user using filter

Let's see the simple example of authenticating user using filter.

Here, we have created 4 files:

 [Link]
 [Link]
 [Link]
 [Link]

[Link]

1. <form action="servlet1">
2. Name:<input type="text" name="name"/><br/>
3. Password:<input type="password" name="password"/><br/>
4.
5. <input type="submit" value="login">
6.
7. </form>

[Link]

1. import [Link];
2. import [Link];
3. import [Link].*;
4.
5. public class MyFilter implements Filter{
6.
7. public void init(FilterConfig arg0) throws ServletException {}
8.
9. public void doFilter(ServletRequest req, ServletResponse resp,
10. FilterChain chain) throws IOException, ServletException {
11.
12. PrintWriter out=[Link]();
13.
14. String password=[Link]("password");

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
134 | P a g e Code MicroSystem Arvind Sir 9822939054

15. if([Link]("admin")){
16. [Link](req, resp);//sends request to next resource
17. }
18. else{
19. [Link]("username or password error!");
20. RequestDispatcher rd=[Link]("[Link]");
21. [Link](req, resp);
22. }
23.
24. }
25. public void destroy() {}
26.
27. }

[Link]

1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link].*;
6.
7. public class AdminServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. [Link]("welcome ADMIN");
15. [Link]();
16. }
17. }

[Link]

1. <web-app>
2. <servlet>
3. <servlet-name>AdminServlet</servlet-name>
4. <servlet-class>AdminServlet</servlet-class>
5. </servlet>
6.
7. <servlet-mapping>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
135 | P a g e Code MicroSystem Arvind Sir 9822939054

8. <servlet-name>AdminServlet</servlet-name>
9. <url-pattern>/servlet1</url-pattern>
10. </servlet-mapping>
11.
12. <filter>
13. <filter-name>f1</filter-name>
14. <filter-class>MyFilter</filter-class>
15. </filter>
16. <filter-mapping>
17. <filter-name>f1</filter-name>
18. <url-pattern>/servlet1</url-pattern>
19. </filter-mapping>
20.
21. </web-app>

FilterConfig
An object of FilterConfig is created by the web container. This object can be used to get the
configuration information from the [Link] file.

Methods of FilterConfig interface


There are following 4 methods in the FilterConfig interface.

1. public void init(FilterConfig config): init() method is invoked only once it is used to
initialize the filter.
2. public String getInitParameter(String parameterName): Returns the parameter value
for the specified parameter name.
3. public [Link] getInitParameterNames(): Returns an enumeration
containing all the parameter names.
4. public ServletContext getServletContext(): Returns the ServletContext object.

Example of FilterConfig

In this example, if you change the param-value to no, request will be forwarded to the servlet
otherwise filter will create the response with the message: this page is underprocessing. Let's see
the simple example of FilterConfig. Here, we have created 4 files:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
136 | P a g e Code MicroSystem Arvind Sir 9822939054

 [Link]
 [Link]
 [Link]
 [Link]

[Link]

1. <a href="servlet1">click here</a>

[Link]

1. import [Link];
2. import [Link];
3.
4. import [Link].*;
5.
6. public class MyFilter implements Filter{
7. FilterConfig config;
8.
9. public void init(FilterConfig config) throws ServletException {
10. [Link]=config;
11. }
12.
13. public void doFilter(ServletRequest req, ServletResponse resp,
14. FilterChain chain) throws IOException, ServletException {
15.
16. PrintWriter out=[Link]();
17.
18. String s=[Link]("construction");
19.
20. if([Link]("yes")){
21. [Link]("This page is under construction");
22. }
23. else{
24. [Link](req, resp);//sends request to next resource
25. }
26.
27. }
28. public void destroy() {}
29. }

[Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
137 | P a g e Code MicroSystem Arvind Sir 9822939054

1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link].*;
6.
7. public class HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. [Link]("<br>welcome to servlet<br>");
15.
16. }
17.
18. }

[Link]

1. <web-app>
2.
3. <servlet>
4. <servlet-name>HelloServlet</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>HelloServlet</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. <init-param>
17. <param-name>construction</param-name>
18. <param-value>no</param-value>
19. </init-param>
20. </filter>
21. <filter-mapping>
22. <filter-name>f1</filter-name>
23. <url-pattern>/servlet1</url-pattern>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
138 | P a g e Code MicroSystem Arvind Sir 9822939054

24. </filter-mapping>
25.
26.
27. </web-app>

Useful Filter Examples


There is given some useful examples of filter.

Example of sending response by filter only

[Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6.
7. public void doFilter(ServletRequest req, ServletResponse res,
8. FilterChain chain) throws IOException, ServletException {
9.
10. PrintWriter out=[Link]();
11.
12. [Link]("<br/>this site is underconstruction..");
13. [Link]();
14.
15. }
16. public void destroy() {}
17. }

Example of counting number of visitors for a single page

[Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class MyFilter implements Filter{
5. static int count=0;
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
139 | P a g e Code MicroSystem Arvind Sir 9822939054

6. public void init(FilterConfig arg0) throws ServletException {}


7.
8. public void doFilter(ServletRequest req, ServletResponse res,
9. FilterChain chain) throws IOException, ServletException {
10.
11. PrintWriter out=[Link]();
12. [Link](request,response);
13.
14. [Link]("<br/>Total visitors "+(++count));
15. [Link]();
16.
17. }
18. public void destroy() {}
19. }

Example of checking total response time in filter

[Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class MyFilter implements Filter{
5. static int count=0;
6. public void init(FilterConfig arg0) throws ServletException {}
7.
8. public void doFilter(ServletRequest req, ServletResponse res,
9. FilterChain chain) throws IOException, ServletException {
10.
11. PrintWriter out=[Link]();
12. long before=[Link]();
13.
14. [Link](request,response);
15.
16. long after=[Link]();
17. [Link]("<br/>Total response time "+(after-before)+" miliseconds");
18. [Link]();
19.
20. }
21. public void destroy() {}
22. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
140 | P a g e Code MicroSystem Arvind Sir 9822939054

ServletInputStream class
ServletInputStream class provides stream to read binary data such as image etc. from the
request object. It is an abstract class.

The getInputStream() method of ServletRequest interface returns the instance of


ServletInputStream class. So can be get as:

1. ServletInputStream sin=[Link]();

Method of ServletInputStream class

There are only one method defined in the ServletInputStream class.

1. int readLine(byte[] b, int off, int len) it reads the input stream.

ServletOutputStream class
ServletOutputStream class provides a stream to write binary data into the response. It is an
abstract class.

The getOutputStream() method of ServletResponse interface returns the instance of


ServletOutputStream class. It may be get as:

1. ServletOutputStream out=[Link]();

Methods of ServletOutputStream class

The ServletOutputStream class provides print() and println() methods that are overloaded.

1. void print(boolean b){}


2. void print(char c){}
3. void print(int i){}
4. void print(long l){}
5. void print(float f){}
6. void print(double d){}
7. void print(String s){}
8. void println{}
9. void println(boolean b){}
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
141 | P a g e Code MicroSystem Arvind Sir 9822939054

10. void println(char c){}


11. void println(int i){}
12. void println(long l){}
13. void println(float f){}
14. void println(double d){}
15. void println(String s){}

Example of ServletOutputStream class

Example to display image using Servlet


In this example, we are using FileInputStream class to read image and ServletOutputStream
class for writing this image content as a response. To make the performance faster, we have used
BufferedInputStream and BufferedOutputStream class.

You need to use the content type image/jpeg.

In this example, we are assuming that you have [Link] image inside the c:\test directory. You
may change the location accordingly.

To create this application, we have created three files:

1. [Link]
2. [Link]
3. [Link]

[Link]

This file creates a link that invokes the servlet. The url-pattern of the servlet is servlet1.

1. <a href="servlet1">click for photo</a>

[Link]

This servlet class reads the image from the mentioned directory and writes the content in the
response object using ServletOutputStream and BufferedOutputStream classes.

1. package [Link];
2. import [Link].*;
3. import [Link].*;
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
142 | P a g e Code MicroSystem Arvind Sir 9822939054

4. import [Link].*;
5. public class DisplayImage extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request,HttpServletResponse response)
8. throws IOException
9. {
10. [Link]("image/jpeg");
11. ServletOutputStream out;
12. out = [Link]();
13. FileInputStream fin = new FileInputStream("c:\\test\\[Link]");
14.
15. BufferedInputStream bin = new BufferedInputStream(fin);
16. BufferedOutputStream bout = new BufferedOutputStream(out);
17. int ch =0; ;
18. while((ch=[Link]())!=-1)
19. {
20. [Link](ch);
21. }
22.
23. [Link]();
24. [Link]();
25. [Link]();
26. [Link]();
27. }
28. }

Servlet with Annotation (feature of servlet3):


1. Servlet with Annotation
2. Example of simple servlet by annotation

Annotation represents the metadata. If you use annotation, deployment descriptor ([Link] file)
is not required. But you should have tomcat7 as it will not run in the previous versions of tomcat.
@WebServlet annotation is used to map the servlet with the specified name.

Example of simple servlet by annotation

There is given the simple example of servlet with annotation.

[Link]

1. import [Link];
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
143 | P a g e Code MicroSystem Arvind Sir 9822939054

2. import [Link];
3.
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. @WebServlet("/Simple")
11. public class Simple extends HttpServlet {
12. private static final long serialVersionUID = 1L;
13.
14. protected void doGet(HttpServletRequest request, HttpServletResponse response)
15. throws ServletException, IOException {
16.
17.
18. [Link]("text/html");
19. PrintWriter out=[Link]();
20.
21. [Link]("<html><body>");
22. [Link]("<h3>Hello Servlet</h3>");
23. [Link]("</body></html>");
24. }
25. }

SingleThreadModel interface
1. SingleThreadModel interface
2. Example of SingleThreadModel interface

The servlet programmer should implement SingleThreadModel interface to ensure that servlet
can handle only one request at a time. It is a marker interface, means have no methods.

This interface is currently deprecated since Servlet API 2.4 because it doesn't solves all the
thread-safety issues such as static variable and session attributes can be accessed by multiple
threads at the same time even if we have implemented the SingleThreadModel interface. So it is
recommended to use other means to resolve these thread safety issues such as synchronized
block etc.

Example of SingleThreadModel interface


Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
144 | P a g e Code MicroSystem Arvind Sir 9822939054

Let's see the simple example of implementing the SingleThreadModel interface.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8.
9.
10. public class MyServlet extends HttpServlet implements SingleThreadModel{
11.
12. public void doGet(HttpServletRequest request, HttpServletResponse response)
13. throws ServletException, IOException {
14.
15. [Link]("text/html");
16. PrintWriter out = [Link]();
17.
18. [Link]("welcome");
19. try{[Link](10000);}catch(Exception e){[Link]();}
20. [Link](" to servlet");
21.
22.
23. [Link]();
24. }
25.
26. }

Example of Registration form in servlet


Here, you will learn that how to create simple registration form in servlet. We are using
oracle10g database. So you need to create a table first as given below:

1. CREATE TABLE "REGISTERUSER"


2. ( "NAME" VARCHAR2(4000),
3. "PASS" VARCHAR2(4000),
4. "EMAIL" VARCHAR2(4000),
5. "COUNTRY" VARCHAR2(4000)
6. )
7. /

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
145 | P a g e Code MicroSystem Arvind Sir 9822939054

To create the registration page in servlet, we can separate the database logic from the servlet. But
here, we are mixing the database logic in the servlet only for simplicity of the program. We will
develop this page in JSP following DAO, DTO and Singleton design pattern later.

Example of Registration form in servlet

In this example, we have created the three pages.

 [Link]
 [Link]
 [Link]

[Link]

In this page, we have getting input from the user using text fields and combobox. The
information entered by the user is forwarded to Register servlet, which is responsible to store the
data into the database.

1. <html>
2. <body>
3. <form action="servlet/Register" method="post">
4.
5. Name:<input type="text" name="userName"/><br/><br/>
6. Password:<input type="password" name="userPass"/><br/><br/>
7. Email Id:<input type="text" name="userEmail"/><br/><br/>
8. Country:
9. <select name="userCountry">
10. <option>India</option>
11. <option>Pakistan</option>
12. <option>other</option>
13. </select>
14.
15. <br/><br/>
16. <input type="submit" value="register"/>
17.
18. </form>
19. </body>
20. </html>

[Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
146 | P a g e Code MicroSystem Arvind Sir 9822939054

This servlet class receives all the data entered by user and stores it into the database. Here, we
are performing the database logic. But you may separate it, which will be better for the web
application.

1. import [Link].*;
2. import [Link].*;
3. import [Link];
4. import [Link].*;
5.
6. public class Register extends HttpServlet {
7. public void doPost(HttpServletRequest request, HttpServletResponse response)
8. throws ServletException, IOException {
9.
10. [Link]("text/html");
11. PrintWriter out = [Link]();
12.
13. String n=[Link]("userName");
14. String p=[Link]("userPass");
15. String e=[Link]("userEmail");
16. String c=[Link]("userCountry");
17.
18. try{
19. [Link]("[Link]");
20. Connection con=[Link](
21. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
22.
23. PreparedStatement ps=[Link](
24. "insert into registeruser values(?,?,?,?)");
25.
26. [Link](1,n);
27. [Link](2,p);
28. [Link](3,e);
29. [Link](4,c);
30.
31. int i=[Link]();
32. if(i>0)
33. [Link]("You are successfully registered...");
34.
35.
36. }catch (Exception e2) {[Link](e2);}
37.
38. [Link]();
39. }
40.
41. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
147 | P a g e Code MicroSystem Arvind Sir 9822939054

[Link] file

The is the configuration file, providing information about the servlet.

1. <web-app>
2.
3. <servlet>
4. <servlet-name>Register</servlet-name>
5. <servlet-class>Register</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>Register</servlet-name>
10. <url-pattern>/servlet/Register</url-pattern>
11. </servlet-mapping>
12.
13. <welcome-file-list>
14. <welcome-file>[Link]</welcome-file>
15. </welcome-file-list>
16.
17. </web-app>

Example of Fetching Result for the given


rollno
Here, you will learn that how to fetch result for the given rollno. I am assuming that there is a
table as given below:

1. CREATE TABLE "RESULT"


2. ( "ROLLNO" NUMBER,
3. "NAME" VARCHAR2(40),
4. "RESULT" VARCHAR2(40),
5. "GRADE" VARCHAR2(40),
6. CONSTRAINT "RESULT_PK" PRIMARY KEY ("ROLLNO") ENABLE
7. )
8. /

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
148 | P a g e Code MicroSystem Arvind Sir 9822939054

We are assuming there are many records in this table. In this example, we are getting the data
from the database in servlet and printing it. We are doing all the database logic in servlet for
simplicity of the program. But it will be better to separate it from the servlet file.

Example of Fetching Result for the given rollno

In this example, we have create three files

 [Link]
 [Link]
 [Link]

[Link]

This page gets rollno from the user and forwards this data to servlet which is responsible to show
the records based on the given rollno.

1. <html>
2. <body>
3. <form action="servlet/Search">
4. Enter your Rollno:<input type="text" name="roll"/><br/>
5.
6. <input type="submit" value="search"/>
7. </form>
8. </body>
9. </html>

[Link]

This is the servlet file which gets the input from the user and maps this data with the database
and prints the record for the matched data. In this page, we are displaying the column name of
the database along with data, so we are using ResultSetMetaData interface.

1. import [Link].*;
2. import [Link].*;
3. import [Link];
4. import [Link].*;
5.
6. public class Search extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response)

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
149 | P a g e Code MicroSystem Arvind Sir 9822939054

9. throws ServletException, IOException {


10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. String rollno=[Link]("roll");
15. int roll=[Link](rollno);
16.
17. try{
18. [Link]("[Link]");
19. Connection con=[Link](
20. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
21.
22. PreparedStatement ps=[Link]("select * from result where rollno=?");
23. [Link](1,roll);
24.
25. [Link]("<table width=50% border=1>");
26. [Link]("<caption>Result:</caption>");
27.
28. ResultSet rs=[Link]();
29.
30. /* Printing column names */
31. ResultSetMetaData rsmd=[Link]();
32. int total=[Link]();
33. [Link]("<tr>");
34. for(int i=1;i<=total;i++)
35. {
36. [Link]("<th>"+[Link](i)+"</th>");
37. }
38.
39. [Link]("</tr>");
40.
41. /* Printing result */
42.
43. while([Link]())
44. {
45. [Link]("<tr><td>"+[Link](1)+"</td><td>"+[Link](2)+"
46. </td><td>"+[Link](3)+"</td><td>"+[Link](4)+"</td></tr>");
47.
48. }
49.
50. [Link]("</table>");
51.
52. }catch (Exception e2) {[Link]();}
53.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
150 | P a g e Code MicroSystem Arvind Sir 9822939054

54. finally{[Link]();}
55.
56. }
57. }

[Link] file

This is the configuration file which provides information of the servlet to the container.

1. <web-app>
2.
3. <servlet>
4. <servlet-name>Search</servlet-name>
5. <servlet-class>Search</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>Search</servlet-name>
10. <url-pattern>/servlet/Search</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Improving Servlet performance to fetch


records from database
In this example, we are going to improve the performance of web application to fetch records
from the database. To serve this, we are storing the data of the table in a collection, and reusing
this collection in our servlet. So, we are not directly hitting the database again and again. By this,
we are improving the performance.

To run this application, you need to create following table with some records.

1. CREATE TABLE "CSUSER"


2. ( "USERID" NUMBER,
3. "USERNAME" VARCHAR2(4000),
4. "USERPASS" VARCHAR2(4000),
5. "USEREMAIL" VARCHAR2(4000),

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
151 | P a g e Code MicroSystem Arvind Sir 9822939054

6. "USERCOUNTRY" VARCHAR2(4000),
7. "CONTACT" NUMBER,
8. CONSTRAINT "CSUSER_PK" PRIMARY KEY ("USERID") ENABLE
9. )
10. /

Example to Improve the performance of servlet to fetch records from database

In this example, we have created 6 pages.

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]

1) [Link]

This html file contains two links that sends request to the servlet.

1. <a href="servlet1">first servlet</a>|


2. <a href="servlet2">second servlet</a>

2) [Link]

This is simple bean class containing 3 properties with its getters and setters. This class represents
the table of the database.

1. public class User {


2. private int id;
3. private String name,password;
4.
5. public int getId() {
6. return id;
7. }
8. public void setId(int id) {
9. [Link] = id;
10. }
11. public String getName() {
12. return name;
13. }
14. public void setName(String name) {
15. [Link] = name;

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
152 | P a g e Code MicroSystem Arvind Sir 9822939054

16. }
17. public String getPassword() {
18. return password;
19. }
20. public void setPassword(String password) {
21. [Link] = password;
22. }
23.
24.
25. }

3) [Link]

It is the listener class. When the project will be deployed, contextInitialized method of
ServletContextListener is invoked by default. Here, we are getting the records of the table and
storing it in the User class object which is added in the ArrayList class object. At last, all the
records of the table will be stored in the ArrayList class object (collection). Finally, we are
storing the ArrayList object in the ServletConext object as an attribute so that we can get it in the
servlet and use it.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link].*;
5. import [Link];
6.
7. public class MyListener implements ServletContextListener{
8.
9. public void contextInitialized(ServletContextEvent e) {
10.
11. ArrayList list=new ArrayList();
12. try{
13. [Link]("[Link]");
14. Connection con=[Link](
15. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
16.
17. PreparedStatement ps=[Link]("select * from csuser");
18. ResultSet rs=[Link]();
19. while([Link]()){
20. User u=new User();
21. [Link]([Link](1));
22. [Link]([Link](2));
23. [Link]([Link](3));
24. [Link](u);
25. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
153 | P a g e Code MicroSystem Arvind Sir 9822939054

26. [Link]();
27.
28. }catch(Exception ex){[Link](ex);}
29.
30. //storing the ArrayList object in ServletContext
31. ServletContext context=[Link]();
32. [Link]("data",list);
33.
34. }
35. public void contextDestroyed(ServletContextEvent arg0) {
36. [Link]("project undeployed...");
37. }
38.
39. }

4) [Link]

This servlet gets the information from the servlet context object and prints it.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. import [Link];
11. import [Link];
12. import [Link];
13. import [Link];
14. import [Link];
15.
16.
17. public class MyServlet1 extends HttpServlet {
18. public void doGet(HttpServletRequest request, HttpServletResponse
19. response)throws ServletException, IOException {
20.
21. [Link]("text/html");
22. PrintWriter out = [Link]();
23.
24. long before=[Link]();
25.
26. ServletContext context=getServletContext();

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
154 | P a g e Code MicroSystem Arvind Sir 9822939054

27. List list=(List)[Link]("data");


28.
29. Iterator itr=[Link]();
30. while([Link]()){
31. User u=(User)[Link]();
32. [Link]("<br>"+[Link]()+" "+[Link]()+" "+[Link]());
33. }
34.
35. long after=[Link]();
36. [Link]("<br>total time :"+(after-before));
37.
38. [Link]();
39. }
40.
41. }

5) [Link]

It is same as MyServlet1. This servlet gets the information from the servlet context object and
prints it.

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. import [Link];
11. import [Link];
12. import [Link];
13. import [Link];
14. import [Link];
15.
16.
17. public class MyServlet2 extends HttpServlet {
18. public void doGet(HttpServletRequest request, HttpServletResponse
19. response)throws ServletException, IOException {
20.
21. [Link]("text/html");
22. PrintWriter out = [Link]();
23.
24. long before=[Link]();

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
155 | P a g e Code MicroSystem Arvind Sir 9822939054

25.
26. ServletContext context=getServletContext();
27. List list=(List)[Link]("data");
28.
29. Iterator itr=[Link]();
30. while([Link]()){
31. User u=(User)[Link]();
32. [Link]("<br>"+[Link]()+" "+[Link]()+" "+[Link]());
33. }
34.
35. long after=[Link]();
36. [Link]("<br>total time :"+(after-before));
37.
38. [Link]();
39. }
40.
41. }

6) [Link]

Here we are containing the information about servlets and listener.

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app version="2.5"
3. xmlns="[Link]
4. xmlns:xsi="[Link]
5. xsi:schemaLocation="[Link]
6. [Link]
7.
8. <listener>
9. <listener-class>MyListener</listener-class>
10. </listener>
11.
12. <servlet>
13. <servlet-name>MyServlet1</servlet-name>
14. <servlet-class>MyServlet1</servlet-class>
15.
16. </servlet>
17. <servlet>
18. <servlet-name>MyServlet2</servlet-name>
19. <servlet-class>MyServlet2</servlet-class>
20.
21. </servlet>
22.
23. <servlet-mapping>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
156 | P a g e Code MicroSystem Arvind Sir 9822939054

24. <servlet-name>MyServlet1</servlet-name>
25. <url-pattern>/servlet1</url-pattern>
26. </servlet-mapping>
27. <servlet-mapping>
28. <servlet-name>MyServlet2</servlet-name>
29. <url-pattern>/servlet2</url-pattern>
30. </servlet-mapping>
31.
32. </web-app>

Example of uploading file to the server in


servlet
Here, we will learn how to upload file to the server. For uploading a file to the server, method
must be post and enctype must be multipart/form-data in html file. For Example:

[Link]

1. <html>
2. <body>
3. <form action="go" method="post" enctype="multipart/form-data">
4. Select File:<input type="file" name="fname"/><br/>
5. <input type="submit" value="upload"/>
6. </form>
7. </body>
8. </html>

Example of uploading file to the server in servlet

Now, for uploading a file to the server, there can be various ways. But, I am going to use
MultipartRequest class provided by oreilly. For using this class you must have [Link] file. If you
will download this example, we will the [Link] file alongwith code.

[Link]

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
157 | P a g e Code MicroSystem Arvind Sir 9822939054

1. import [Link].*;
2. import [Link];
3. import [Link].*;
4. import [Link];
5.
6. public class UploadServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. [Link]("text/html");
12. PrintWriter out = [Link]();
13.
14. MultipartRequest m=new MultipartRequest(request,"d:/new");
15. [Link]("successfully uploaded");
16. }
17. }

There are two arguments passed in MultipartRequest class constructor, first one is
HttpServletRequest object and second one is String object (for location). Here I am supposing
that you have new folder in D driver.

[Link] file

This configuration file provides information about the servlet.

1. <web-app>
2.
3. <servlet>
4. <servlet-name>UploadServlet</servlet-name>
5. <servlet-class>UploadServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>UploadServlet</servlet-name>
10. <url-pattern>/go</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
158 | P a g e Code MicroSystem Arvind Sir 9822939054

Example of downloading file from the server


in servlet
For downloading a file from the server, here is the simple example. I am supposing you have
[Link] file in E drive that you want to download. If there is any jar or zip file, you can direct
provide a link to that file. So there is no need to write the program to download. But if there is
any java file or jsp file etc, you need to create a program to download that file.

Example of downloading file from the server in servlet

In this example, we are creating three files:

 [Link]
 [Link]
 [Link]

[Link]

This file provides a link to download the file.

1. <a href="servlet/DownloadServlet">download the jsp file</a>

[Link]

This is the servlet file that reads the content of the file and writes it into the stream to send as a
response. For this purpose, we need to inform the server, so we are setting the content type as
APPLICATION/OCTET-STREAM .

1. import [Link].*;
2. import [Link];
3. import [Link].*;
4.
5. public class DownloadServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. throws ServletException, IOException {
9.
10. [Link]("text/html");
11. PrintWriter out = [Link]();
12. String filename = "[Link]";
13. String filepath = "e:\\";

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
159 | P a g e Code MicroSystem Arvind Sir 9822939054

14. [Link]("APPLICATION/OCTET-STREAM");
15. [Link]("Content-
Disposition","attachment; filename=\"" + filename + "\"");
16.
17. FileInputStream fileInputStream = new FileInputStream(filepath + filename);
18.
19. int i;
20. while ((i=[Link]()) != -1) {
21. [Link](i);
22. }
23. [Link]();
24. [Link]();
25. }
26.
27. }

[Link] file

This configuration file provides informations to the server about the servlet.

1. <web-app>
2.
3. <servlet>
4. <servlet-name>DownloadServlet</servlet-name>
5. <servlet-class>DownloadServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>DownloadServlet</servlet-name>
10. <url-pattern>/servlet/DownloadServlet</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Sending email through JavaMail API in


Servlet

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
160 | P a g e Code MicroSystem Arvind Sir 9822939054

The JavaMail API provides many classes that can be used to send email from java. The
[Link] and [Link] packages contains all the classes required for sending and
receiving emails.

For better understanding of this example click steps for sending email from javamail api

For sending the email using JavaMail API, you need to load the two jar files:

 [Link]
 [Link]

download these jar files or go to the Oracle site to download the latest version.

Example of Sending email through JavaMail API in Servlet

Here is the simple example of sending email from servlet. For this example we are creating 3
files:

 [Link] file for input


 [Link] , a servlet file for handling the request and providing the response to the
user. It uses the send method of Mailer class to send the email.
 [Link] , a java class that contains send method to send the emails to the mentioned
recipient.

[Link]

1. <form action="servlet/SendMail">
2. To:<input type="text" name="to"/><br/>
3. Subject:<input type="text" name="subject"><br/>
4. Text:<textarea rows="10" cols="70" name="msg"></textarea><br/>
5. <input type="submit" value="send"/>
6. </form>

[Link]

1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8.

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
161 | P a g e Code MicroSystem Arvind Sir 9822939054

9.
10. public class SendMail extends HttpServlet {
11. public void doGet(HttpServletRequest request,
12. HttpServletResponse response)
13. throws ServletException, IOException {
14.
15. [Link]("text/html");
16. PrintWriter out = [Link]();
17.
18. String to=[Link]("to");
19. String subject=[Link]("subject");
20. String msg=[Link]("msg");
21.
22. [Link](to, subject, msg);
23. [Link]("message has been sent successfully");
24. [Link]();
25. }
26.
27. }

[Link]

1. import [Link];
2.
3. import [Link].*;
4. import [Link];
5. import [Link];
6.
7. public class Mailer {
8. public static void send(String to,String subject,String msg){
9.
10. final String user="microsystem@[Link]";//change accordingly
11. final String pass="xxxxx";
12.
13. //1st step) Get the session object
14. Properties props = new Properties();
15. [Link]("[Link]", "[Link]");//change accordingly
16. [Link]("[Link]", "true");
17.
18. Session session = [Link](props,
19. new [Link]() {
20. protected PasswordAuthentication getPasswordAuthentication() {
21. return new PasswordAuthentication(user,pass);
22. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
162 | P a g e Code MicroSystem Arvind Sir 9822939054

23. });
24. //2nd step)compose message
25. try {
26. MimeMessage message = new MimeMessage(session);
27. [Link](new InternetAddress(user));
28. [Link]([Link],new InternetAddress(to));
29. [Link](subject);
30. [Link](msg);
31.
32. //3rd step)send message
33. [Link](message);
34.
35. [Link]("Done");
36.
37. } catch (MessagingException e) {
38. throw new RuntimeException(e);
39. }
40.
41. }
42. }

How to write data into PDF using Servlet


Here, we are going to see how we can write data into PDF using servlet technology. We are
simply writing some data using servlet and it will get displayed in the PDF.

To create such application, you need to have the [Link] file. If you download this example, you
will get the example with jar file.

Example to write data into PDF using servlet

Let's see the simple example of writing data into PDF using servlet. In this example, we have
mentioned the content type application/pdf that must be specified to display data in the PDF
format.

[Link]

1. package [Link];
2. import [Link].*;
3. import [Link].*;
4. import [Link].*;
5. import [Link].*;
Project Training on Java,DotNet,Php,Andorid Contact:9822939054
Email:codemicrosystem@[Link]
163 | P a g e Code MicroSystem Arvind Sir 9822939054

6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10.
11. public class ServletPDF extends HttpServlet {
12.
13. public void doGet(HttpServletRequest request,
14. HttpServletResponse response) throws IOException {
15.
16. PrintWriter out = [Link]();
17. [Link]("application/pdf");
18.
19. [Link]("Content-disposition","inline; filename='[Link]'");
20.
21. PDF p = new PDF(out);
22. Page p1 = new Page(p);
23. [Link](new MoveTo(p, 200, 700));
24. [Link](new Text(p, "[Link]"));
25. [Link](new Text(p, "by Arvind"));
26.
27. [Link](p1);
28. [Link]("Code MicroSystem");
29.
30. [Link]();
31.
32. }
33. }

Example of Login Form in Servlet Tutorial


Here, we are going to create the simple example to create the login form using servlet. We have
used oracle10g as the database. There are 5 files required for this application.

 [Link]
 [Link]
 [Link]
 [Link]
 [Link]

You must need to create a table userreg with name and pass fields. Moreover, it must have
contained some data. The table should be as:

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
164 | P a g e Code MicroSystem Arvind Sir 9822939054

1. create table userreg(name varchar2(40),pass varchar2(40));

[Link]

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


2. Name:<input type="text" name="username"/><br/><br/>
3. Password:<input type="password" name="userpass"/><br/><br/>
4. <input type="submit" value="login"/>
5. </form>

[Link]

1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10.
11. public class FirstServlet extends HttpServlet {
12. public void doPost(HttpServletRequest request, HttpServletResponse response)
13. throws ServletException, IOException {
14.
15. [Link]("text/html");
16. PrintWriter out = [Link]();
17.
18. String n=[Link]("username");
19. String p=[Link]("userpass");
20.
21. if([Link](n, p)){
22. RequestDispatcher rd=[Link]("servlet2");
23. [Link](request,response);
24. }
25. else{
26. [Link]("Sorry username or password error");
27. RequestDispatcher rd=[Link]("[Link]");
28. [Link](request,response);
29. }
30.
31. [Link]();
32. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
165 | P a g e Code MicroSystem Arvind Sir 9822939054

33. }

[Link]

1. import [Link].*;
2.
3. public class LoginDao {
4. public static boolean validate(String name,String pass){
5. boolean status=false;
6. try{
7. [Link]("[Link]");
8. Connection con=[Link](
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=[Link](
12. "select * from userreg where name=? and pass=?");
13. [Link](1,name);
14. [Link](2,pass);
15.
16. ResultSet rs=[Link]();
17. status=[Link]();
18.
19. }catch(Exception e){[Link](e);}
20. return status;
21. }
22. }

[Link]

1. import [Link];
2. import [Link];
3.
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8.
9. public class WelcomeServlet extends HttpServlet {
10. public void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12.
13. [Link]("text/html");
14. PrintWriter out = [Link]();
15.
16. String n=[Link]("username");

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
166 | P a g e Code MicroSystem Arvind Sir 9822939054

17. [Link]("Welcome "+n);


18.
19. [Link]();
20. }
21.
22. }

Example to display image using Servlet


In this example, we are using FileInputStream class to read image and ServletOutputStream
class for writing this image content as a response. To make the performance faster, we have used
BufferedInputStream and BufferedOutputStream class.

You need to use the content type image/jpeg.

In this example, we are assuming that you have [Link] image inside the c:\test directory. You
may change the location accordingly.

To create this application, we have created three files:

1. [Link]
2. [Link]
3. [Link]

[Link]

This file creates a link that invokes the servlet. The url-pattern of the servlet is servlet1.

1. <a href="servlet1">click for photo</a>

[Link]

This servlet class reads the image from the mentioned directory and writes the content in the
response object using ServletOutputStream and BufferedOutputStream classes.

1. package [Link];
2. import [Link].*;
3. import [Link].*;
4. import [Link].*;
5. public class DisplayImage extends HttpServlet {

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]
167 | P a g e Code MicroSystem Arvind Sir 9822939054

6.
7. public void doGet(HttpServletRequest request,HttpServletResponse response)
8. throws IOException
9. {
10. [Link]("image/jpeg");
11. ServletOutputStream out;
12. out = [Link]();
13. FileInputStream fin = new FileInputStream("c:\\test\\[Link]");
14.
15. BufferedInputStream bin = new BufferedInputStream(fin);
16. BufferedOutputStream bout = new BufferedOutputStream(out);
17. int ch =0; ;
18. while((ch=[Link]())!=-1)
19. {
20. [Link](ch);
21. }
22.
23. [Link]();
24. [Link]();
25. [Link]();
26. [Link]();
27. }
28. }

Project Training on Java,DotNet,Php,Andorid Contact:9822939054


Email:codemicrosystem@[Link]

You might also like