Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Advanced Java

Unit 3 Servlet and JSP


3.1 Introduction
3.2 How It differs from CGI
3.3 Types of Servlet
3.4 Life cycle of Servlet
3.5 Execution process of Servlet Application
3.6 Session Tracking
3.7 Cookie class
3.8 Servlet- JDBC

Introduction
In the early days of the Web, most business Web pages were simply forms of advertising
tools and content providers offering customers useful manuals, brochures and catalogues.
In other words, these business-web-pages had static content and were called "Static
WebPages".
Later, the dot-com revolution enabled businesses to provide online services for their
customers; and instead of just viewing inventory, customers could also purchase it. This new
phase of the evolution created many new requirements;
Web sites had to be reliable, available, secure, and, if it was at all possible, fast. At this time,
the content of the web pages could be generated dynamically, and were called "Dynamic
WebPages".
JSP is a server side technology which helps to create a webpage dynamically using java as
the programming language.
JSP is a specification from Sun Microsystems. It is an extension to Servlet API.
Servlet technology is used to create web application (resides at server side and generates
dynamic web page).

What is a Servlet?
1. Servlet is a technology i.e. used to create web application.
2. Servlet is an API that provides many interfaces and classes including
documentations.
3. Servlet is an interface that must be implemented for creating any servlet.
4. Servlet is a class that extends the capabilities of the servers and responds to the
incoming request. It can respond to any type of requests.
5. Servlet is a web component that is deployed on the server to create dynamic web
page.

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.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 1


www.vertexitservices.com
Advanced Java

What is CGI?
CGI is not the program itself. CGI is simply the interface between the Web page or browser
and the Web server that runs the program.
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.

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.

Advantages 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, lightweight, cost of communication
between the threads are low. The basic benefits of servlet are as follows:
The advantages of servlets are discussed below.
1. Portability
2. Powerful
3. Efficiency
4. Safety
5. Integration
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 2
www.vertexitservices.com
Advanced Java

6. Extensibility
7. Inexpensive
8. Secure
9. Performance

Portability
Servlets are highly portable crosswise operating systems and server implementations
because the servlets are written in java and follow well known standardized APIs. Servlets
are writing once, run anywhere (WORA) program, because we can develop a servlet on
Windows machine running the tomcat server or any other server and later we can deploy
that servlet simply on any other operating system like Unix. Servlets are extremely portable
so we can run in any platform. So we can call servlets are platform independent one.
Servlets are written entirely in java.
Powerful
We can handle several things with the servlets which were difficult or sometimes impossible
to do with CGI. For example the CGI programs can’t talk directly to the web server but the
servlets can directly talk to the web server. Servlets can share data among each other, they
make the database connection pools easy to implement. By using the session tracking
mechanism servlets can maintain the session which helps them to maintain information
from request to request. Servlets can do many things which are difficult to implement in the
CGI programs.
Efficiency
The servlets invocation is highly efficient as compared to CGI programs. The servlet remains
in the server’s memory as a single object instance, when the servlet get loaded in the server.
The servlets are highly scalable because multiple concurrent requests are handled by
separate threads. That is we can handle N number of threads by using a single servlet class
Safety
As servlets are written in java, servlets inherit the strong type safety of java language. In java
automatic garbage collection mechanism and a lack of pointers protect the servlets from
memory management problems. In servlets we can easily handle the errors due to the
exception handling mechanism. If any exception occurs then it will throw an exception by
using the throw statement.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today,
the servlet API support Http Servlets, but in later date it can be extended for another type of
servlets. Java Servlets are developed in java which is robust, well-designed and object
oriented language which can be extended or polymorphed into new objects. So the java
servlets take all these advantages and can be extended from existing class to provide the
ideal solutions. So servlets are more extensible and reliable.
Inexpensive
There are number of free web servers available for personal use or for commercial purpose.
Web servers are relatively expensive. So by using the free available web servers you can add
servlet support to it.
Secure
Servlets are server side components, so it inherits the security provided by the web server.
Servlets are also benefited with Java Security Manager.
Performance

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 3


www.vertexitservices.com
Advanced Java

Servlets are faster than CGI programs because each scripts in CGI produces a new process
and these processes takes a lot of time for execution. But in case of servlets it creates only
new thread. Due to interpreted nature of java, programs written in java are slow. But the
java servlets runs very fast. These are due to the way servlets run on web server. For any
program initialization takes significant amount of time. But in case of servlets initialization
takes place first time it receives a request and remains in memory till times out or server
shut downs. After servlet is loaded, to handle a new request it simply creates a new thread
and runs service method of servlet. In comparison to traditional CGI scripts which creates a
new process to serve the request.

Servlet Disadvantage
1. Designing in servlet is difficult and slows down the application.
2. Writing complex business logic makes the application difficult to understand.
3. You need a Java Runtime Environment on the server to run servlets. CGI is a
completely language independent protocol, so you can write CGIs in whatever
languages you have available (including Java if you want to).

Difference between Servlet and CGI


No CGI Servlet
1. CGI are usually executables that are Servlets can also be compiled to the native
native to the server’s operating OS it can be compiled to Java bytecode
system which is then run on a JVM
2. CGI programs are platform Servlets are platform independent
dependent
3. CGI programs run as separate Servlets run on the JVM
processes on the computer
4. CGI can be more vulnerable to Servlets can be less vulnerable to attacks
attacks than servlets than servlets
5. CGI can directly process scripts Scripts needs to be translated and compiled
to before it can be run as a servlet

Difference between Servlet and JSP


No Servlet JSP
1. Servlets are Java programs that are JSP is a webpage scripting language that
already compiled which also creates can generate dynamic content
dynamic web content
2. Servlets can also be compiled to the JSP can be compiled into Java Servlets
native OS it can be compiled to Java
byte code which is then run on a JVM
3. Servlets run faster compared to JSP JSP run slower compared to Servlets
4. It’s difficult to code in Servlets than in It’s easier to code in JSP than in Java
JSP

Types of Servlets
There are mainly two types of servlets
1. Generic Servlet - Generic servlet is protocol independent servlet. It implements the
Servlet and ServletConfig interface. It may be directly extended by the servlet.
Writing a servlet in in GenericServlet is very easy. It has only init() and destroy()

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 4


www.vertexitservices.com
Advanced Java

method of ServletConfig interface in its life cycle. It also implements the log method
of ServletContext interface. They extend javax.servlet.GenericServlet.
2. Http Servlet - HttpServlet is HTTP (Hyper Text Transfer Protocol ) specific servlet. It
provides an abstract class HttpServlet for the developers for extend to create
their own HTTP specific servlets. They extend javax.servlet.HttpServlet. The sub
class of HttpServlet must overwrite at least one method given below-
a. doGet()
b. doPost()
c. doTrace()
d. doDelete()
e. init()
f. destroy()
g. getServiceInfo()

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.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 5


www.vertexitservices.com
Advanced Java

3. Http uses reliable TCP connections by default 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 by default.

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.
The http request methods are:
1. GET
2. POST
3. HEAD
4. PUT
5. DELETE
6. OPTIONS
7. TRACE
HTTP Description
Request
GET Asks to get the resource at the requested URL.
POST Asks the server to accept the body info attached. It is like GET request with extra info
sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET but 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.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can 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
1) In case of Get request, only limited amount of In case of post request, large amount of data
data can be sent because data is sent in header. can be sent because data is sent in 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 Post request is non-idempotent
will be ignored until response of first request is
delivered.
5) Get request is more efficient and used more than Post request is less efficient and used less

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 6


www.vertexitservices.com
Advanced Java

Post than get.


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.

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.
5. 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

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 7


www.vertexitservices.com
Advanced Java

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.

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:
1. text/html
2. text/plain
3. application/msword
4. application/vnd.ms-excel
5. application/jar
6. application/pdf
7. application/octet-stream
8. application/x-zip
9. images/jpeg
10. video/quicktime etc.

Servlet API
1. The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.
2. The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
3. The javax.servlet.http package contains interfaces and classes that are responsible
for http requests only.

Let's see what are the interfaces of javax.servlet package.


Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 8
www.vertexitservices.com
Advanced Java

13. ServletContextListener
14. ServletContextAttributeListener
15. Classes in javax.servlet package
There are many classes in javax.servlet 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 javax.servlet.http package


There are many interfaces in javax.servlet.http 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 javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
HttpServlet
1. Cookie
2. HttpServletRequestWrapper
3. HttpServletResponseWrapper
4. HttpSessionEvent
5. HttpSessionBindingEvent
6. HttpUtils (deprecated now)
Servlet Interface
1. Servlet interface provides common behaviour to all the servlets.
2. Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle
methods of servlet. These are invoked by the web container.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only once.
public void service(ServletRequest provides response for the incoming request. It is
request,ServletResponse response) invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is being
destroyed.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 9


www.vertexitservices.com
Advanced Java

public ServletConfig getServletConfig() returns the object of ServletConfig.


public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.

Servlet Example by implementing Servlet interface


Let's see the simple example of servlet by implementing the servlet interface.
It will be better if you learn it after visiting steps to create a servlet.
File: First.java
import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

GenericServlet class
1. GenericServlet class implements Servlet, ServletConfig andSerializable interfaces. It
provides the implementaion of all the methods of these interfaces except the
service method.
2. GenericServlet class can handle any type of request so it is protocol-independent.
3. You may create a generic servlet by inheriting the GenericServlet class and providing
the implementation of the service method.

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.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 10


www.vertexitservices.com
Advanced Java

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 super.init(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 web.xml 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.

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: First.java
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}

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.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 11


www.vertexitservices.com
Advanced Java

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.

Servlet Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet
1. The servlet is initialized by calling the init () method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.
The following figure depicts a typical servlet life-cycle scenario.
1. First the HTTP requests coming to the server are delegated to the servlet container.
2. The servlet container loads the servlet before invoking the service() method.
3. Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 12


www.vertexitservices.com
Advanced Java

Servlet life cycle methods


The init() method :
The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations,
just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout the life of the
servlet.
The init method definition looks like this:
public void init() throws ServletException {
// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the client(
browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 13
www.vertexitservices.com
Advanced Java

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() method :


The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:
public void destroy() {
// Finalization code...
}

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletLifeCycle extends HttpServlet
{

public ServletLifeCycle()
{
System.out.println("Am from default constructor");
}

public void init(ServletConfig config)


{
System.out.println("Am from Init method...!");
}

public void doGet(HttpServletRequest req,HttpServletResponse res)throws


ServletException,IOException

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 14


www.vertexitservices.com
Advanced Java

{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("I am from doGet method");
pw.close();
}

public void destroy()


{
System.out.println("Am from Destroy methods");
}

}
web.xml

<web-app>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>java4s.ServletLifeCycle</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/lifecycle1</url-pattern>
</servlet-mapping>
</web-app>

Steps to Create Servlet Application using tomcat server


To create a Servlet application you need to follow the below mentioned steps. These steps
are common for all the Web server. In our example we are using Apache Tomcat server.
Apache Tomcat is an open source web server for testing servlets and JSP technology.
Download latest version of Tomcat Server and install it on your machine.
After installing Tomcat Server on your machine follow the below mentioned steps :
1. Create directory structure for your application.
2. Create a Servlet
3. Compile the Servlet
4. Create Deployement Descriptor for your application
5. Start the server and deploy the application
All these 5 steps are explained in details below, lets create our first Servlet Application.

1. Creating the Directory Structure


Sun Microsystem defines a unique directory structure that must be followed to create a
servlet application.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 15


www.vertexitservices.com
Advanced Java

Create the above directory structure inside Apache-Tomcat\webapps directory. All HTML,
static files(images, css etc) are kept directly under Web application folder. While all the
Servlet classes are kept inside classesfolder.
The web.xml (deployement descriptor) file is kept under WEB-INF folder.

Creating a Servlet
There are three different ways to create a servlet.
1. By implementing Servlet interface
2. By extending GenericServlet class
3. By extending HttpServlet class
But mostly a servlet is created by extending HttpServlet abstract class. As discussed
earlier HttpServlet gives the definition of service() method of the Servlet interface. The
servlet class that we will create should not override service() method. Our servlet class will
override only doGet() or doPost() method.
When a request comes in for the servlet, the Web Container calls the
servlet's service() method and depending on the type of request the service() method calls
either the doGet() or doPost() method.
NOTE: By default a request is Get request.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResposne response)
throws ServletException
{
response.setContentType("text/html");
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 16
www.vertexitservices.com
Advanced Java

PrintWriter out = response.getWriter();


out.println("<html><body>");
out.println("<h1>Hello Readers</h1>");
out.println("</body></html>");
}
}
Write above code in a notepad file and save it as MyServlet.java anywhere on your PC.
Compile it(explained in next step) from there and paste the class file into WEB-
INF/classes/ directory that you have to create inside Tomcat/webapps directory.

Compiling a Servlet
To compile a Servlet a JAR file is required. Different servers require different JAR files. In
Apache Tomcat server servlet-api.jar file is required to compile a servlet class.
Steps to compile a Servlet
Set the Class Path.

Download servlet-api.jar file.


Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.

Compile the Servlet class.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 17


www.vertexitservices.com
Advanced Java

NOTE: After compiling your Servlet class you will have to paste the class file into WEB-
INF/classes/directory.

Create Deployment Descriptor


Deployment Descriptor(DD) is an XML document that is used by Web Container to run
Servlets and JSP pages. DD is used for several important purposes such as:
1. Mapping URL to Servlet class.
2. Initializing parameters.
3. Defining Error page.
4. Security roles.
5. Declaring tag libraries.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 18


www.vertexitservices.com
Advanced Java

Start the Server


Double click on the startup.bat file to start your Apache Tomcat Server.
Or, execute the following command on your windows machine using RUN prompt.
C:\apache-tomcat-7.0.14\bin\startup.bat

Starting Tomcat Server for the first time


If you are starting Tomcat Server for the first time you need to set JAVA_HOME in the
Enviroment variable. The following steps will show you how to set it.
Right Click on My Computer, go to Properites.

Go to Advanced Tab and Click on Enviroment Variables... button.

Click on New button, and enter JAVA_HOME inside Variable name text field and path of JDK
inside Variable value text field. Click OK to save.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 19


www.vertexitservices.com
Advanced Java

Run Servlet Application


Open Browser and type http:localhost:8080/First/hello

Hurray! Our first Servlet Application ran successfully.

Session Tracking in Servlets


1. Session simply means a particular interval of time.
2. Session Tracking is a way to maintain state (data) of an user. It is also known
as session management in servlet.
3. 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.
4. HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 20


www.vertexitservices.com
Advanced Java

Why use Session Tracking?


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

Session Tracking Techniques


There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests. A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.

How Cookie works


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

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 21


www.vertexitservices.com
Advanced Java

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

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.
Constructor of Cookie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String constructs a cookie with a specified name and
value) value.
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot
be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)

Other methods required for using Cookies


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

How to create Cookie?


Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 22


www.vertexitservices.com
Advanced Java

How to get Cookies?


Let's see the simple code to get all the cookies.
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
}

Simple example of Servlet Cookies


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

index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 23


www.vertexitservices.com
Advanced Java

out.close();
}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}

web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 24


www.vertexitservices.com
Advanced Java

Servlet Login and Logout Example using Cookies


1. A cookie is a kind of information that is stored at client side.
2. 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.
3. Here, we are going to create a login and logout example using servlet cookies.
4. 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.
5. In this application, we have created following files.
a. index.html
b. link.html
c. login.html
d. LoginServlet.java
e. LogoutServlet.java
f. ProfileServlet.java
g. web.xml
File: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Servlet Login Example</title>
</head>
<body>

<h1>Welcome to Login App by Cookie</h1>


<a href="login.html">Login</a>|
<a href="LogoutServlet">Logout</a>|
<a href="ProfileServlet">Profile</a>

</body>
</html>

File: link.html
<a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr>

File: login.html
<form action="LoginServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>

File: LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 25
www.vertexitservices.com
Advanced Java

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin123")){
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+name);
Cookie ck=new Cookie("name",name);
response.addCookie(ck);
}else{
out.print("sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}

File: LogoutServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();

request.getRequestDispatcher("link.html").include(request, response);
Cookie ck=new Cookie("name","");
ck.setMaxAge(0);
response.addCookie(ck);
out.print("you are successfully logged out!");
}
}

File: ProfileServlet.java
import java.io.IOException;
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 26
www.vertexitservices.com
Advanced Java

import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProfileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck[]=request.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}

File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/
ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.javatpoint.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>com.javatpoint.ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 27
www.vertexitservices.com
Advanced Java

<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.javatpoint.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>

If again you click on the profile link, you need to login first.
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="Vimal Jaiswal">
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field


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

Advantage of Hidden Form Field


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

Disadvantage of Hidden Form Field:


1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.

Example of using Hidden Form Field


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

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 28


www.vertexitservices.com
Advanced Java

index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//creating form that have invisible textfield
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
}

}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 29
www.vertexitservices.com
Advanced Java

PrintWriter out = response.getWriter();


//Getting the value from the hidden field
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</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.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 30


www.vertexitservices.com
Advanced Java

Advantage of URL Rewriting


1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
1. It will work only with links.
2. It can send Only textual information.

Example of using URL Rewriting


In this example, we are maintaning the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query
string in another page.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();

}catch(Exception e){System.out.println(e);}
}

}
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 31
www.vertexitservices.com
Advanced Java

SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}

}
web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id to
identify the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 32


www.vertexitservices.com
Advanced Java

How to get the HttpSession object ?


The HttpServletRequest interface provides two methods to get the object of HttpSession:
public HttpSession getSession():Returns the current session associated with this request, or
if the request does not have a session, creates one.
public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession


In this example, we are setting the attribute in the session scope in one servlet and getting
that value from the session scope in another servlet. To set the attribute in the session
scope, we have used the setAttribute() method of HttpSession interface and to get the
attribute, we have used the getAttribute method.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 33


www.vertexitservices.com
Advanced Java

String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();

}catch(Exception e){System.out.println(e);}
}

web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 34
www.vertexitservices.com
Advanced Java

</web-app>

Servlet and JDBC


Before starting with database access through a servlet, make sure you have proper JDBC
environment setup along with a database.
To start with basic concept, let us create a simple table and create few records in that table
as follows:
Create Table
To create the Employees table in TEST database, use the following steps:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2:
Login to database as follows
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
Step 3:
Create the table Employee in TEST database as follows:
mysql> use TEST;
mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>
Create Data Records
Finally you create few records in Employee table as follows:
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');


Query OK, 1 row affected (0.00 sec)

mysql>
Accessing a Database:
Here is an example which shows how to access TEST database using Servlet.
// Loading required libraries
import java.io.*;
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 35
www.vertexitservices.com
Advanced Java

import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class DatabaseAccess extends HttpServlet{

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// JDBC driver name and database URL
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";

// Database credentials
static final String USER = "root";
static final String PASS = "password";

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Execute SQL query


Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

// Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 36
www.vertexitservices.com
Advanced Java

//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");

// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}
Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
....
Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display
following response:
Database Result

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 37


www.vertexitservices.com
Advanced Java

ID: 100, Age: 18, First: Zara, Last: Ali


ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal

JDBC and Servlet using MySQL


/*

MySQL and Java Developer's Guide

Mark Matthews, Jim Cole, Joseph D. Gradecki


Publisher Wiley,
Published February 2003,
ISBN 0471269239

*/

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JDBCServlet extends HttpServlet {
public void doGet(HttpServletRequest inRequest,
HttpServletResponse outResponse) throws ServletException,
IOException {
PrintWriter out = null;
Connection connection = null;
Statement statement;
ResultSet rs;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
.getConnection("jdbc:mysql://localhost/products");
statement = connection.createStatement();
outResponse.setContentType("test/html");
out = outResponse.getWriter();
rs = statement.executeQuery("SELECT ID, title, price FROM product");
out.println("<HTML><HEAD><TITLE>Products</TITLE></HEAD>");
out.println("<BODY>");
out.println("<UL>");
while (rs.next()) {
out.println("<LI>" + rs.getString("ID") + " "
+ rs.getString("title") + " " + rs.getString("price"));
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 38
www.vertexitservices.com
Advanced Java

}
out.println("</UL>");
out.println("</BODY></HTML>");
} catch (ClassNotFoundException e) {
out.println("Driver Error");
} catch (SQLException e) {
out.println("SQLException: " + e.getMessage());
}
}

public void doPost(HttpServletRequest inRequest,


HttpServletResponse outResponse) throws ServletException,
IOException {
doGet(inRequest, outResponse);
}
}

/***************** Servlet Complete *******************/

Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 39


www.vertexitservices.com

You might also like