Java Unit 3+ 4 Notes IPU
Java Unit 3+ 4 Notes IPU
Java – Applet
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
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.
• A 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.
• init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
• start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
• stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
• destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
• paint − Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.
• java.applet.Applet
• java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context.
These include methods that do the following −
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
• Get applet parameters
• Get the network location of the HTML file that contains the applet
• Get the network location of the applet class directory
• Print a status message in the browser
• Fetch an image
• Fetch an audio clip
• Play an audio clip
• Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may −
• Request information about the author, version, and copyright of the applet
• Request a description of the parameters the applet recognizes
• Initialize the applet
• Destroy the applet
• Start the applet's execution
• Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint
method.
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. Following 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>
Note − You can refer to HTML Applet Tag to understand more about calling applet from
HTML.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and
height are also required to specify the initial size of the panel in which an applet runs. The
applet directive must be closed with an </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param> tags
between <applet> and </applet>. The browser ignores text and other tags between the applet
tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that
appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To
specify otherwise, use the codebase attribute of the <applet> tag as shown −
<applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class"
width = "320" height = "120">
If an applet resides in a package other than the default, the holding package must be specified in
the code attribute using the period character (.) to separate package/class components. For
example −
<applet = "mypackage.subpackage.TestApplet.class"
width = "320" height = "120">
setBackground (Color.black);
setForeground (fg);
}
It is easy to convert a graphical Java application (that is, an application that uses the AWT and
that you can start with the Java program launcher) into an applet that you can embed in a web
page.
Following are the specific steps for converting an application to an applet.
• Make an HTML page with the appropriate tag to load the applet code.
• Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet
cannot be loaded.
• Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
• Move any initialization code from the frame window constructor to the init method of
the applet. You don't need to explicitly construct the applet object. The browser
instantiates it for you and calls the init method.
• Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
• Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates
when the browser exits.
• If the application calls setTitle, eliminate the call to the method. Applets cannot have title
bars. (You can, of course, title the web page itself, using the HTML title tag.)
• Don't call setVisible(true). The applet is displayed automatically.
Output of the above applet program when run using appletviewer tool is:
Applet initialized
Applet execution started
Painting…
Painting…
Applet execution stopped
Applet destroyed
Event Handling
Applets inherit a group of event-handling methods from the Container class. The Container
class defines several methods, such as processKeyEvent and processMouseEvent, for handling
particular types of events, and then one catch-all method called processEvent.
In order to react to an event, an applet must override the appropriate event-specific method.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
Displaying Images
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image
within the applet, you use the drawImage() method found in the java.awt.Graphics class.
Following is an example illustrating all the steps to show images −
import java.applet.*;
import java.awt.*;
import java.net.*;
Playing Audio
An applet can play an audio file represented by the AudioClip interface in the java.applet
package. The AudioClip interface has three methods, including −
• public void play() − Plays the audio clip one time, from the beginning.
• public void loop() − Causes the audio clip to replay continually.
• public void stop() − Stops playing the audio clip.
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class.
The getAudioClip() method returns immediately, whether or not the URL resolves to an actual
audio file. The audio file is not downloaded until an attempt is made to play the audio clip.
Following is an example illustrating all the steps to play an audio −
import java.applet.*;
import java.awt.*;
import java.net.*;
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavyweight i.e. its components are using the resources of
OS.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above example
that sets the position of the awt button.
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
showing Button component on the Frame.
1. import java.awt.*;
2. class First2{
3. First2(){
4. Frame f=new Frame();
5. Button b=new Button("click me");
6. b.setBounds(30,50,80,30);
7. f.add(b);
8. f.setSize(300,300);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. First2 f=new First2();
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
14. }}
1. import java.awt.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. Frame f=new Frame("Button Example");
5. Button b=new Button("Click Here");
6. b.setBounds(50,100,80,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }
Output:
Output:
Output:
Output:
Output:
1. import java.awt.*;
2. public class ListExample
3. {
4. ListExample(){
5. Frame f= new Frame();
6. List l1=new List(5);
7. l1.setBounds(100,100, 75,75);
8. l1.add("Item 1");
9. l1.add("Item 2");
10. l1.add("Item 3");
11. l1.add("Item 4");
12. l1.add("Item 5");
13. f.add(l1);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }
22. }
Output:
Output:
1. import java.awt.*;
2. public class CheckboxExample
3. {
4. CheckboxExample(){
5. Frame f= new Frame("Checkbox Example");
6. Checkbox checkbox1 = new Checkbox("C++");
7. checkbox1.setBounds(100,100, 50,50);
8. Checkbox checkbox2 = new Checkbox("Java", true);
9. checkbox2.setBounds(100,150, 50,50);
10. f.add(checkbox1);
11. f.add(checkbox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckboxExample();
19. }
20. }
Output:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
import java.awt.*;
import javax.swing.*;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
OUTPUT:
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
We can put the event handling code into one of the following places:
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
1. Within class
2. Other class
3. Anonymous class
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.
Event Handling
Event Delegation Model
Concept:
A source generates an event and sends it to one or more listeners. Listener simply waits until it
receives an event. Listener processes events and then returns. User interface element is able to
"delegate" the processing of an event to a separate piece of code. Notifications are sent only to
those listeners that want to receive them.
Event was propagated up the containment hierarchy until it was handled by a component.
Event
In the delegation model, an event is an object that describes a state change in a source.
Event Source
A source is an object that generates an event. This occurs when object changes in some way.
Source may generate more than one type of event. A source must register listeners in order for
the listeners to receive notifications about a specific type of event. Each type of event has its own
registration method.
General form:
When an event occurs, all registered listeners are notified and receive a copy of the event object.
It is called Multicasting the event. Some sources may allow only one listener to register.
General form:
To remove Listener
Event Listener
• Must have registered with one or more sources to receive notifications about specific
types of events
• Must implement methods to receive and process these notifications
Event Classes
Contains 2 methods:
Object getSource()
String toString()
AWT Event class defined in java.awt package is a subclass of Event Object. It is superclass
(directly or indirectly) of all AWT-based events handled by delegation model. Method getID ()
can be used to determine the type of event.
Sources of Events
Event Source
Button
Checkbox
Choice
List
Menu Item
Scrollbar
Text Components
Window
Event Listener
Methods in Interfaces:
AdjustmentListener
ComponentListener
ContainerListener
void componentAdded (ContainerEvent ce)
void componentRemoved (ContainerEvent ce)
FocusListener
void focusGained (FocusEvent fe)
ItemListener
KeyListener
MouseListener
void mouseClicked (MouseEvent me)
void mouseEntered (MouseEvent me)
void mouseExited (MouseEvent me)
void mousePressed (MouseEvent me)
void mouseReleased (MouseEvent me)
MouseMotionListener
WindowListener
Adapter Class
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Sample Code
import java.awt.*;
import java.awt.event.*;
/*
</applet>
AdapterDemo adapterDemo;
this.adapterDemo = adapterDemo;
AdapterDemo adapterDemo;
adapterDemo.showStatus("Mouse Dragged");
Inner Class
Normal Case
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
MousePressedDemo mousePressedDemo;
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
public MyMouseAdapter (MousePressedDemo mousePressedDemo) {
this.mousePressedDemo = mousePressedDemo;
Modified Version
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
addMouseListener(new MyMouseAdapter () {
});
Java Swing
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
Java - Networking
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network protocols −
• TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
• UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
This chapter gives a good understanding on the following two subjects −
• Socket Programming − This is the most widely used concept in Networking and it has
been explained in very detail.
• URL Processing − This would be covered separately. Click here to learn about URL
Processing in Java language.
Socket Programming
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.
When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and reading from
the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using
sockets −
• The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
• The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
• The constructor of the Socket class attempts to connect the client to the specified server
and the port number. If communication is established, the client now has a Socket object
capable of communicating with the server.
• On the server side, the accept() method returns a reference to a new socket on the server
that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams at the
same time. Following are the useful classes providing complete set of methods to implement
sockets.
If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.
Following are some of the common methods of the ServerSocket class −
2 Waits for an incoming client. This method blocks until either a client
connects to the server on the specified port or the socket times out,
assuming that the time-out value has been set using the setSoTimeout()
method. Otherwise, this method blocks indefinitely.
When the ServerSocket invokes accept(), the method does not return until a client connects.
After a client does connect, the ServerSocket creates a new Socket on an unspecified port and
returns a reference to this new Socket. A TCP connection now exists between the client and the
server, and communication can begin.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Socket Class Methods
The java.net.Socket class represents the socket that both the client and the server use to
communicate with each other. The client obtains a Socket object by instantiating one, whereas
the server obtains a Socket object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server −
public Socket()
5
Creates an unconnected socket. Use the connect() method to connect this
socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it
actually attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and the
server have a Socket object, so these methods can be invoked by both the client and the server.
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Sr.No. Method & Description
4 String getHostAddress()
Returns the IP address string in textual presentation.
5 String getHostName()
Gets the host name for this IP address.
7 String toString()
Converts this IP address to a String.
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
JDBC
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac
OS, and the various versions of UNIX.
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent 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.
Applications of JDBC
Fundamentally, 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.
Example
The following SQL statement creates a Database named EMP −
SQL> CREATE DATABASE EMP;
Drop Database
The DROP DATABASE statement is used for deleting an existing database. The syntax is −
SQL> DROP DATABASE DATABASE_NAME;
Note: To create or drop a database you should have administrator privilege on your database
server. Be careful, deleting a database would loss all the data stored in the database.
Create Table
The CREATE TABLE statement is used for creating a new table. The syntax is −
SQL> CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);
Example
The following SQL statement creates a table named Employees with four columns −
SQL> CREATE TABLE Employees
(
id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);
Drop Table
The DROP TABLE statement is used for deleting an existing table. The syntax is −
SQL> DROP TABLE table_name;
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
Example
The following SQL statement deletes a table named Employees −
SQL> DROP TABLE Employees;
INSERT Data
The syntax for INSERT, looks similar to the following, where column1, column2, and so on
represents the new data to appear in the respective columns −
SQL> INSERT INTO table_name VALUES (column1, column2, ...);
Example
The following SQL INSERT statement inserts a new row in the Employees database created
earlier −
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
SELECT Data
The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as
the BETWEEN and LIKE operators.
Example
The following SQL statement selects the age, first and last columns from the Employees table,
where id column is 100 −
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from the Employees table
where first column contains Zara −
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';
UPDATE Data
The UPDATE statement is used to update data. The syntax for UPDATE is −
SQL> UPDATE table_name
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as
the BETWEEN and LIKE operators.
Example
The following SQL UPDATE statement changes the age column of the employee whose id is
100 −
SQL> UPDATE Employees SET age=20 WHERE id=100;
DELETE Data
The DELETE statement is used to delete data from tables. The syntax for DELETE is −
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as
the BETWEEN and LIKE operators.
Example
The following SQL DELETE statement deletes the record of the employee whose id is 100 −
SQL> DELETE FROM Employees WHERE id=100;
Servlets
Servlets provide a component-based, platform-independent method for building Webbased
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial
will teach you how to use Java Servlets to develop your web based applications in simple and
easy steps.
Applications of Servlet
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images),
Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
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.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not called
for any user requests afterwards. 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...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and
is specially designed to handle HTTP requests.
Sample Code
Following is the sample source code structure of a servlet example to show Hello World −
// Import required java libraries
JAVA NOTES Dr. SHILPI SINGH, UGI, GREATER NOIDA
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this file at
C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location must be
added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and compile
HelloWorld.java as follows −
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any
other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java
Software Development Kit (JDK). For this command to work properly, you have to include the
location of the Java SDK that you are using in the PATH environment variable.
Servlet Deployment
By default, a servlet application is located at the path <Tomcat-
installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must
be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat installationdirectory>/webapps/ROOT/WE
B-INF/classes and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml file.
There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
type http://localhost:8080/HelloWorld in the browser's address box. If everything goes fine,
you would get the following result
// Initializing servelet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}
The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
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.
The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests s
doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inhe
the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the d
request.
DemoServlet.java
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
1. set classpath
2. paste the jar file in JRE/lib/ext folder
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 file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>
There are too many elements in the web.xml file. Here is the illustration of some elements that is
used in the above web.xml file. The elements are as follows:
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.
To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.
To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment
variables.
Go to My Computer properties -> Click on advanced tab then environment variables -> Click on
the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk
folder in variable value -> ok -> ok -> ok.
Go to My Computer properties:
Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:
After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.
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.
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:
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:
Creating war file has an advantage that moving the project from one location to another takes
less time.