You are on page 1of 123

Chapter 3

JAVA APPLET & SERVLET

Applet
Applet is a special type of program that is
embedded in the webpage to generate the
dynamic content. It runs inside the browser and
works at client side.

Advantage of Applet
It

works at client side so less response time.


Secured
It can be executed by browsers running under many
platforms, including Linux, Windows, Mac Os etc.

Drawback of Applet
Plug-in

is required at client browser to execute applet.

Hierarchy of Applet

There are some important differences between an


applet and a standalone Java application,
including the following:
An

applet is a Java class that extends the java.applet.Applet


class.
A main() method is not invoked on an applet, and an applet
class will not define main().
Applets are designed to be embedded within an HTML
page.
When a user views an HTML page that contains an applet,
the code for the applet is downloaded to the user's machine.

JVM is required to view an applet. The JVM can be


either a plug-in of the Web browser or a separate
runtime environment.
The JVM on the user's machine creates an instance of
the applet class and invokes various methods during the
applet's lifetime.
Applets have strict security rules that are enforced by
the Web browser. The security of an applet is often
referred to as sandbox security, comparing the applet to
a child playing in a sandbox with various rules that must
be followed.
Other classes that the applet needs can be downloaded in
a single Java Archive (JAR) file.

Life Cycle of an Applet:


The java.applet.Applet class provides 4 life cycle methods
and java.awt.Component class provides 1 life cycle methods
for an applet.

A "Hello, World" Applet:


import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}}

java.applet.Applet class
For creating any applet java.applet.Applet class must be
inherited. It provides 4 life cycle methods of applet.
public void init(): is used to initialized the Applet. It is
invoked only once.
public void start(): is invoked after the init() method or
browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked
when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is
invoked only once.
java.awt.Component class
public void paint(Graphics g): is used to paint the
Applet. It provides Graphics class object that can be used
for drawing oval, rectangle, arc etc.

Who is responsible to manage the life


cycle of an applet?
Java Plug-in software.

How to run an Applet?


There are two ways to run an applet
By html file.
By appletViewer tool (for testing purpose).

myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Example of Applet by html file:


To execute the applet by html file, create an applet and compile it.
After that create an html file and place the applet code in html file.
Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}

Example of Applet by appletviewer tool:


//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{ public void paint(Graphics g)
{ g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute

the applet by appletviewer tool,


write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">

Displaying Image in Applet


Syntax of drawImage() method:
public abstract boolean drawImage(Image img,
int x, int y, ImageObserver observer): is used
draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage()
method that returns the object of Image.

Syntax:
public Image getImage(URL u, String image){}

Other required methods of Applet


class to display image:
public

URL getDocumentBase(): is used


to return the URL of the document in
which applet is embedded.

public

URL getCodeBase(): is used to


return the base URL.

import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}

<html>
<body>
<applet code="DisplayImage.class" width="300"
height="300">
</applet>
</body>
</html>
OUTPUT

Getting Applet Parameters:


We can get any information from the HTML
file as a parameter.
For this purpose, Applet class provides a
method named getParameter().
Syntax:
public String getParameter(String parameter
Name)

import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g)
{ String str=getParameter("msg");
g.drawString(str,50, 50); }
}

<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet"> </applet>
</body>
</html>
OUTPUT

Animation in applet:
import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}catch(Exception e){}
}
}
}
OUTPUT

EventHandling
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
OUTPUT

Invoking an Applet:
An applet may be invoked by embedding directives in an
HTML file and viewing the file through an applet viewer
or Java-enabled browser.
The

<applet> tag is the basis for embedding an applet in


an HTML file. Below is an example that invokes the
"Hello, World" applet:
<html> <title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320"
height="120"> If your browser was Java-enabled, a
"Hello, World" message would appear here.
</applet> <hr> </html>

Examples of Web-based Applets


include:
QuickTime

movies
Flash movies
Windows Media Player applets, used to display
embedded video files in Internet Explorer (and
other browsers that support the plugin)
3D modeling display applets, used to rotate and
zoom a model
Browser games can be applet-based, though some
may develop into fully functional applications that
require installation.

Difference between Application and Applet

What Applet can't do Security Limitations

Applets are treated as untrusted because they are developed by somebody and
placed on some unknown Web server. When downloaded, they may harm the
system resources or steal passwords and valuable information available on the
system. As applets are untrusted, the browsers come with many security
restrictions. Security policies are browser dependent. Browser does not allow
the applet to access any of the system resources (applet is permitted to use
browser resources, infact, applet execution goes within the browser only).

Applets are not permitted to use any system resources like file system as they
are untrusted and can inject virus into the system.

Applets cannot read from or write to hard disk files.

Applets should not attempt to create socket connections

Applets cannot read system properties

Applets cannot use any software available on the system (except browser
execution area)

Cannot create objects of applications available on the system by composition

The JRE throws SecurityException if the applet violates the browser


restrictions.

Question
Create a Applet that can Draw.

Painting in Applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}

JAVA SERVLET

What Is a Servlet?
A servlet

is a Java programming language class that is used to


extend the capabilities of servers that host applications
accessed by means of a request-response programming model.
Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by web
servers. For such applications, Java Servlet technology
defines HTTP-specific servlet classes.

E.g.

Mail Server

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

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.

Disadvantages of CGI
If

number of clients increases, it takes more time


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

Advantage of Servlets Over "Traditional"


CGI?

Efficient. With traditional CGI, a new process is started for


each HTTP request. If the CGI program does a relatively fast
operation, the overhead of starting the process can dominate
the execution time. With servlets, the Java Virtual Machine
stays up, and each request is handled by a lightweight Java
thread, not a heavyweight operating system process. Similarly,
in traditional CGI, if there are N simultaneous request to the
same CGI program, then the code for the CGI program is
loaded into memory N times. With servlets, however, there are
N threads but only a single copy of the servlet class. Servlets
also have more alternatives than do regular CGI programs for
optimizations such as caching previous computations, keeping
database connections open, and the like.

Convenient. Hey, you already know Java. Why learn


Perl too? Besides the convenience of being able to use a
familiar language, servlets have an extensive
infrastructure for automatically parsing and decoding
HTML form data, reading and setting HTTP headers,
handling cookies, tracking sessions, and many other such
utilities.

Powerful. Java servlets let you easily do several things


that are difficult or impossible with regular CGI. For one
thing, servlets can talk directly to the Web server (regular
CGI programs can't). This simplifies operations that need
to look up images and other data stored in standard places.
Servlets can also share data among each other, making
useful things like database connection pools easy to
implement. They can also maintain information from
request to request, simplifying things like session tracking
and caching of previous computations.

Portable. Servlets are written in Java and follow a


well-standardized API. Consequently, servlets
written for, say I-Planet Enterprise Server can run
virtually unchanged on Apache, Microsoft IIS, or
WebStar. Servlets are supported directly or via a
plugin on almost every major Web server.

Inexpensive. There are a number of free or very


inexpensive Web servers available that are good for
"personal" use or low-volume Web sites. However,
with the major exception of Apache, which is free,
most commercial-quality Web servers are relatively
expensive. Nevertheless, once you have a Web
server, no matter the cost of that server, adding
servlet support to it (if it doesn't come
preconfigured to support servlets) is generally free
or cheap.

Servlet Terminology
1.
2.
3.
4.
5.
6.

HTTP
HTTP Request Types
Difference between Get and Post method
Container
Server and Difference between web server
and application server
Content Type

HTTP
Http

is the protocol that allows web servers and browsers to


exchange data over the web.
It is a request response protocol.
Http uses reliable TCP connections by default on TCP port
80.
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:
GET
POST
HEAD
PUT
DELETE
OPTIONS
TRACE

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 information's 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 information's 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:
Life

Cycle Management
Multithreaded support
Object Pooling
Security etc.

How web container handles the servlet


request?
The web container is responsible to handle the request.
maps the request with the servlet in the web.xml 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.

Server
It is a running program or software that provides
services.
There are two types of servers:
Web Server
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:
JBoss Open-source server from JBoss community.
Glassfish provided by Sun Microsystem. Now acquired by
Oracle.
Weblogic provided by Oracle. It more secured.
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:
text/html
text/plain
application/msword
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
video/quicktime etc.

Life Cycle of a Servlet


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

class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy

method is invoked.

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 javax.servlet.Servlet interface. Syntax of
the init method is given below:
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:
public void service(ServletRequest request, ServletResponse response)
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:
public void destroy()

How Servlet works?


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

Servlet Class Hierarchy

Implementation
Servlet use Classes and Interfaces from 2 packages
javax.servlet
It contains classes to support generic protocol
javax.servlet.http

It extends classes in servlet package to add HTTP specific


functionality.
All servlets must implement the Servlet interface, which
defines life-cycle methods.

javax.servlet package

Interfaces in javax.servlet package


There are many interfaces in javax.servlet package. They are as follows:
Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener

Classes in javax.servlet package


There are many classes in javax.servlet package. They are as follows:
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException

Javax.servlet.http package

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package.
They are as follows:
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)

Classes in javax.servlet.http package


There are many classes in javax.servlet.http package. They
are as follows:
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
HttpUtils

(deprecated now)

Servlet Example by implementing Servlet


interface
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";}
}

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.

Methods of ServletRequest interface


Method

Description

public String getParameter(String name)

is used to obtain the value of a parameter by name.

public String[] getParameterValues(String


name)

returns an array of String containing all values of given


parameter name. It is mainly used to obtain values of a
Multi select list box.

java.util.Enumeration getParameterNames()

returns an enumeration of all of the request parameter


names.

public int getContentLength()

Returns the size of the request entity data, or -1 if not


known.

public String getCharacterEncoding()

Returns the character set encoding for the input of this


request.

public String getContentType()

Returns the Internet Media Type of the request entity data,


or null if not known.

public ServletInputStream getInputStream() Returns an input stream for reading binary data in the
throws IOException
request body.
public abstract String getServerName()

Returns the host name of the server that received the


request.

public int getServerPort()

Returns the port number on which this request was


received.

Example of ServletRequest to display the


name of the user
index.html
<form action="welcome" method="get">
Enter your name<input type="text" name="name">
<br>
<input type="submit" value="login">
</form>

DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String name=req.getParameter("name");//will return value
pw.println("Welcome "+name);
pw.close();
}}

Servlet Collaboration
The Servlet collaboration is all about sharing information among
the servlets. Collaborating servlets is to pass the common
information that is to be shared directly by one servlet to
another through various invocations of the methods. To perform
these operations, each servlet need to know the other servlet
with which it is collaborated.
Here are several ways to communicate with one another:
Using RequestDispatchers include() and forward() method;
Using HttpServletResponse sendRedirect() method;
Using ServletContext setAttribute() and getAttribute() methods.

RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility
of dispatching the request to another resource it
may be html, servlet or jsp. This interface can also
be used to include the content of another resource
also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher
interface.

Methods of RequestDispatcher interface


public

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

How to get the object of


RequestDispatcher
The

getRequestDispatcher() method of ServletRequest interface


returns the object of RequestDispatcher.

Syntax

of getRequestDispatcher method
public RequestDispatcher getRequestDispatcher(String resource);
Example

of using getRequestDispatcher method


RequestDispatcher rd=request.getRequestDispatcher("servlet2"); //
servlet2 is the url-pattern of the second servlet
rd.forward(request,

response);//method may be include or forward

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. In
this example, we have created following files:

index.html

file: for getting input from the user.


Login.java file: a servlet class for processing the response. If
password is servet, it will forward the request to the welcome servlet.
WelcomeServlet.java file: a servlet class for displaying the welcome
message.
web.xml file: a deployment descriptor file that contains the
information about the servlet.

index.html

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


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

Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}

WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}

web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

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.

Difference between forward() and


sendRedirect() method

Syntax of sendRedirect() method


public void sendRedirect(String URL)throws IOExcepti
on;
Example of sendRedirect() method
response.sendRedirect("http://www.javatpoint.com");

DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
response.sendRedirect("http://www.google.com");
pw.close();
}}

Creating custom google search using


sendRedirect
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>sendRedirect example</title>
</head>
<body>

<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>

MySearcher.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySearcher extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletRespo
nse response)
throws ServletException, IOException {
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}

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:
By implementing Servlet interface,
By inheriting GenericServlet class, (or)
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.

1.
2.
3.
4.
5.
6.

Create a directory structure


Create a Servlet
Compile the Servlet
Create a deployment descriptor
Start the server and deploy the project
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.

2. Create a Servlet
There are three ways to create the servlet.
By implementing the Servlet interface
By inheriting the GenericServlet class
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.

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}

3. Compile the servlet


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

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.

4. Create the deployment descriptor


(web.xml 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 web.xml file. There are
many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file.
Here is given some necessary elements to run
the simple servlet program.

Web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

5. Start the Server and deploy the


project
To start Apache Tomcat server, double click
on the startup.bat file under apachetomcat/bin directory.

One Time Configuration for Apache


Tomcat Server
You need to perform 2 tasks:
set JAVA_HOME or JRE_HOME in environment
variable (It is required to start server).
Change the port number of tomcat (optional). It is
required if another server is running on same port
(8080).

How to set JAVA_HOME in


environment variable?
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.

After

setting the JAVA_HOME double click on the


startup.bat file in apache tomcat/bin.
Note: There are two types of tomcat available:
Apache tomcat that needs to extract only (no need to
install)
Apache tomcat that needs to install

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
number.Suppose you have installed oracle, you need to
change the port number of apache tomcat because both
have the default port number 8080.
Open server.xml 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.

How to deploy the servlet project


Copy the project and paste it in the webapps folder under apache tomcat.
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:
projectfolder> jar cvf myproject.war *
Creating war file has an advantage that moving the project from one location
to another takes less time.

6. How to access the servlet


Open

broser and write


http://hostname:portno/contextroot/urlpatte
rnofservlet.
For example:
http://localhost:9999/demo/welcome

JDBC

JDBC stands for Java Database Connectivity,


which is a standard Java API for databaseindependent connectivity between the Java
programming language and a wide range of
databases.

The JDBC library includes APIs for each of the


tasks mentioned below that are commonly
associated with database usage.
Making

a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the
database.
Viewing & Modifying the resulting records.

JDBC is a specification that provides a complete set of


interfaces that allows for portable access to an
underlying database. Java can be used to write
different types of executables, such as
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All

of these different executables are able to use a JDBC driver


to access a database, and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java
programs to contain database-independent code.

JDBC Architecture
The

JDBC API supports both two-tier and three-tier processing


models for database access but in general, JDBC Architecture
consists of two layers
JDBC API: This provides the application-to-JDBC Manager
connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver
Connection.
The JDBC API uses a driver manager and database-specific drivers
to provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to
access each data source. The driver manager is capable of
supporting multiple concurrent drivers connected to multiple
heterogeneous databases.

Common JDBC Components


The JDBC API provides the following interfaces and classes
DriverManager: This class manages a list of database drivers.
Matches connection requests from the java application with the
proper database driver using communication sub protocol. The
first driver that recognizes a certain subprotocol under JDBC
will be used to establish a database Connection.
Driver: This interface handles the communications with the
database server. You will interact directly with Driver objects
very rarely. Instead, you use DriverManager objects, which
manages objects of this type. It also abstracts the details
associated with working with Driver objects.
Connection: This interface with all methods for contacting a
database. The connection object represents communication
context, i.e., all communication with database is through
connection object only.

Statement:

You use objects created from this


interface to submit the SQL statements to the
database. Some derived interfaces accept parameters
in addition to executing stored procedures.
ResultSet: These objects hold data retrieved from a
database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you
to move through its data.
SQLException: This class handles any errors that
occur in a database application.

Creating JDBC Application


There are following six steps involved in building a JDBC application:
Import the packages: Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import java.sql.* will suffice.
Register the JDBC driver: Requires that you initialize a driver so
you can open a communication channel with the database.
Open
a
connection:
Requires
using
the
DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with the database.
Execute a query: Requires using an object of type Statement for
building and submitting an SQL statement to the database.
Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.
Clean up the environment: Requires explicitly closing all database
resources versus relying on the JVM's garbage collection.

//STEP 1. Import required packages


import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{

//STEP 2: Register JDBC driver


Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn =
DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: 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");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}

//STEP 6: 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
System.out.println("Goodbye!");
}//end main
}//end FirstExample

Output
Connecting to database...
Creating statement...
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

You might also like