SlideShare a Scribd company logo
UNIT-4
Applet
ADDING IMAGES TO AN APPLET
• An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet,
you use the drawlmage() method found in the java.awt.Graphics class.
• Following is the example showing all the steps to show images:
import java.applet. *;
Import java.awt. *;
import java.net.*;
public class ImageDemo extends Applet
{
private Image image;
private AppletContext context;
public void init()
{
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{
imageURL = "java.jpg";
}
try
{
URL url = new URL(this.getDocumentBase(), imageURL);
image = context.getImage(url);
}
catch(MalformedURLException e)
{
e.printStackTrace();
//Display in browser status bar
context.showStatus("Could not load image!");
}}
public void paint(Graphics g)
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.java2s.com", 10, 20);
}}
Now,let us call this applet as follows:
<html>
<title>The ImageDemo applet</title>
<hr>
<applet code="ImageDemo.class" width="300" height="200">
<param name="image" value="java.jpg">
</appIet><hr></html>
• MalformedURLException is a checked
exception. It is inherited from IOException.
MalformedURLException is raised by JVM in
two occasions.
1. The protocol given in the address as URL may
not be a correct (valid) one for the job.
2. The address given in the URL constructor
may not be evaluated successfully (due to
wrong format etc) by the networking software.
Life cycle of a servlet
• 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.
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... }
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.
The service() Method
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
}
web program -Life cycle of a servlet.ppt
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... }
Architectural 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.
Sample Code
Following is the sample source code structure
of a servlet example to show Hello World
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet
{
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
// do nothing.
} }
Passing Parameter to Applets with example
• Java applet has the feature of retrieving the parameter
values passed from the html page. So, you can pass the
parameters from your html page to the applet
embedded in your page.
• The param tag(<parma name="" value=""></param>)
is used to pass the parameters to an applet.
• There are three methods commonly used by applets:
– String getParameter(String name)-Returns the value for the
specified parameter string
– URL getCodeBase()-Returns the URL of the applet
– URL getDocumentBase()-Returns the URL of the document
containing the applet
Example( hai.java)
import java.applet.*;
import java.awt.*;
/*<APPLET code="hai" width="300" height="250">
<PARAM name="Message" value="Hai friend how are you ..?">
</APPLET>*/
public class hai extends Applet
{
private String defaultMessage = "Hello!“;
public void paint(Graphics g)
{
String inputFromPage = this.getParameter("Message");
if (inputFromPage == null)
inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 55);
}}
Output
• You only need to change the HTML, not the Java source code. PARAMs let you
customize applets without changing or recompiling the code.
• This applet is very similar to the HelloWorldApplet.
• You pass getParameter() a string that names the parameter you want. This string
should match the name of a PARAM element in the HTML page.
• getParameter() returns the value of the parameter. All values are passed as strings.
• If you want to get another type like an integer, then you'll need to pass it as a string
and convert it to the type you really want.
• The PARAM element is also straightforward. It occurs between <APPLET> and
</APPLET>.
• It has two attributes of its own, NAME and VALUE.
• NAME identifies which PARAM this is. VALUE is the string value of the PARAM.
• Both should be enclosed in double quote marks if they contain white space.
An applet is not limited to one PARAM.
• You can pass as many named PARAMs to an applet as you like. An applet does not
necessarily need to use all the PARAMs that are in the HTML. Additional PARAMs can
be safely ignored.
Displaying Graphics in Applet
• java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
• public abstract void drawString(String str, int x, int y): is used to draw the specified string.
• public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height.
• public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and
specified width and height.
• public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and
height.
• public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified
width and height.
• public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2).
• public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image.
• public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or
elliptical arc.
• public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or
elliptical arc.
• public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
• public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
Example of Graphics in applet:
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);
} }
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
AWT Layouts
• The LayoutManagers are used to arrange components in a particular
manner.
• LayoutManager is an interface that is implemented by all the classes of
layout managers. When you add a component to an applet or a container,
the container uses its layout manager to decide where to put the
component.
• Different LayoutManager classes use different rules to place components.
java.awt.LayoutManager is an interface. Five classes in the java packages
implement it:
– FlowLayout
– BorderLayout
– CardLayout
– GridLayout
– GridBagLayout
FlowLayout
Java FlowLayout
• The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default
layout of applet or panel.
Fields of FlowLayout class
– public static final int LEFT
– public static final int RIGHT
– public static final int CENTER
– public static final int LEADING
– public static final int TRAILING
Constructors of FlowLayout class
• FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
• FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and
vertical gap.
• FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given
horizontal and vertical gap.
Example of FlowLayout class
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
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:
– public static final int NORTH
– public static final int SOUTH
– public static final int EAST
– public static final int WEST
– public static final int CENTER
Constructors of BorderLayout class:
• BorderLayout(): creates a border layout but with no gaps between the components.
• JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
• Example of BorderLayout class:
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
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(); } }
Java Card Layout
• The CardLayout class manages the components in such a manner that only one component
is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class
• CardLayout(): creates a card layout with zero horizontal and vertical gap.
• CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.
Commonly used methods of CardLayout class
• public void next(Container parent): is used to flip to the next card of the given container.
• public void previous(Container parent): is used to flip to the previous card of the given
container.
• public void first(Container parent): is used to flip to the first card of the given container.
• public void last(Container parent): is used to flip to the last card of the given container.
• public void show(Container parent, String name): is used to flip to the specified card with
the given name.
Example of CardLayout class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3); }
public void actionPerformed(ActionEvent e) {
card.next(c); }
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
GridLayout
• The GridLayout is used to arrange the components in rectangular grid. One component
is displayed in each rectangle.
Constructors of GridLayout class
• GridLayout(): creates a grid layout with one column per component in a row.
• GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
• GridLayout(int rows, int columns, int hgap, int vgap):creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.
• Example of GridLayout class
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Java GridBagLayout
• The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline.
• The components may not be of same size.
• Each GridBagLayout object maintains a dynamic, rectangular grid of
cells.
• Each component occupies one or more cells known as its display
area.
• Each component associates an instance of GridBagConstraints.
• With the help of constraints object we arrange component's display
area on the grid.
• The GridBagLayout manages each component's minimum and
preferred sizes in order to determine component's size.
web program -Life cycle of a servlet.ppt
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
•
Applet for calculator application
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class calc extends Applet implements
ActionListener{
Label l1,l2;
TextField t1,t2,t3;
Button addition,subtraction,multiplication,division;
public void init(){
l1=new Label("enter first no");
add(l1);
l2=new Label("enter second no");
add(l2);
t1=new TextField(10);
add(t1);
t2=new TextField(10);
add(t2);
t3=new TextField(10);
add(t3);
addition=new Button("+");
add(addition);
addition.addActionListener(this);
subtraction=new Button("-");
add(subtraction);
subtraction.addActionListener(this);
multiplication=new Button("*");
add(multiplication);
multiplication.addActionListener(this);
division=new Button("/");
add(division);
division.addActionListener(this);}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==addition){
int sum=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(sum));
}
if(ae.getSource()==subtraction)
{
int sub=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(sub));
}
if(ae.getSource()==multiplication)
{
int mul=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(mul));
}
if(ae.getSource()==division)
{
int div=Integer.parseInt(t1.getText()) +
Integer.parseInt(t2.getText());
t3.setText(String.valueOf(div));
}}}
/*
<applet code="calc" width=200 height=200>
</applet>
*/
JSP
What is JavaServer Pages?
• JavaServer Pages (JSP) is a technology for developing Webpages that
supports dynamic content. This helps developers insert java code in HTML
pages by making use of special JSP tags, most of which start with <% and
end with %>.
• A JavaServer Pages component is a type of Java servlet that is designed to
fulfill the role of a user interface for a Java web application.
• Web developers write JSPs as text files that combine HTML or XHTML code,
XML elements, and embedded JSP actions and commands.
• Using JSP, you can collect input from users through Webpage forms, present
records from a database or another source, and create Webpages
dynamically.
• JSP tags can be used for a variety of purposes, such as retrieving information
from a database or registering user preferences, accessing JavaBeans
components, passing control between pages, and sharing information
between requests, pages etc.
• JavaServer Pages often serve the same purpose as programs
implemented using the Common Gateway Interface (CGI).
• But JSP offers several advantages in comparison with the CGI.
– Performance is significantly better because JSP allows
embedding Dynamic Elements in HTML Pages itself instead of
having separate CGI files.
– JSP are always compiled before they are processed by the server
unlike CGI/Perl which requires the server to load an interpreter
and the target script each time the page is requested.
– JavaServer Pages are built on top of the Java Servlets API, so like
Servlets, JSP also has access to all the powerful Enterprise Java
APIs, including JDBC, JNDI, EJB, JAXP, etc.
– JSP pages can be used in combination with servlets that handle
the business logic, the model supported by Java servlet template
engines.
Advantages of JSP
• Following table lists out the other advantages of using JSP over other technologies −
• vs. Active Server Pages (ASP)
• The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS
specific language, so it is more powerful and easier to use. Second, it is portable to other operating
systems and non-Microsoft Web servers.
• vs. Pure Servlets
• It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements
that generate the HTML.
• vs. Server-Side Includes (SSI)
• SSI is really only intended for simple inclusions, not for "real" programs that use form data, make
database connections, and the like.
• vs. JavaScript
• JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to
perform complex tasks like database access and image processing etc.
• vs. Static HTML
• Regular HTML, of course, cannot contain dynamic information.
Event Handling
Event:
• Change in the state of an object is known as event i.e. event describes the change in state
of source.
• Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page are the activities that
causes an event to happen.
Types of Event
• The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
Event Handling:
• Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs.
• These mechanisms have the code which is known as event handler that is executed when an
event occurs.
• Java Uses the Delegation EventModel to handle the events. This model defines the standard
mechanism to generate and handle the events.
The Delegation Event Model has the following key participants namely:
• Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source
object.
• Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received, the listener processes the event a
then returns.
Steps involved in event handling
• The User clicks the button and the event is
generated.
• Now the object of concerned event class is
created automatically and information about
the source and the event get populated with in
same object.
• Event object is forwarded to the method of
registered listener class.
• The method is now get executed and returns.
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");
}
}
• http://mrbool.com/how-to-use-image-and-
sound-in-an-java-applet/22500

More Related Content

PPTX
Applets in Java. Learn java program with applets
PPT
PPT
Applets
PDF
Lecture 22
PPTX
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
PPT
Basic of Applet
PPT
Applets
PPT
Applets(1)cusdhsiohisdhfshihfsihfohf.ppt
Applets in Java. Learn java program with applets
Applets
Lecture 22
JAVA SERVLETS acts as a middle layer between a request coming from a web brow...
Basic of Applet
Applets
Applets(1)cusdhsiohisdhfshihfsihfohf.ppt

Similar to web program -Life cycle of a servlet.ppt (20)

PPT
Appletsbjhbjiibibibikbibibjibjbibbjb.ppt
PDF
27 applet programming
PPT
Applets
PPTX
Introduction To Applets methods and simple examples
PPTX
PPTX
PPTX
L18 applets
PPTX
Applet in java new
PPT
Applets
PDF
PPTX
Applet and graphics programming
PDF
Java Servlets.pdf
PPT
Advanced Programming, Java Programming, Applets.ppt
PPTX
PDF
6applets And Graphics
PPT
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
PPT
Jsp applet
PPTX
Applets
PPT
Applet ppt for higher understanding education
PPTX
java.pptx
Appletsbjhbjiibibibikbibibjibjbibbjb.ppt
27 applet programming
Applets
Introduction To Applets methods and simple examples
L18 applets
Applet in java new
Applets
Applet and graphics programming
Java Servlets.pdf
Advanced Programming, Java Programming, Applets.ppt
6applets And Graphics
Module 4.pptModule 4.pptModule 4.pptModule 4.ppt
Jsp applet
Applets
Applet ppt for higher understanding education
java.pptx
Ad

More from mcjaya2024 (20)

PPT
cyber forensics Email Investigations.ppt
PPT
Cell Phone and Mobile Devices Forensics.ppt
PPT
Computer Forensics Analysis and Validation.ppt
PPT
cyber forensics Footprinting and Scanning.ppt
PPT
cyber forensics-enum,sniffing,malware threat.ppt
PPT
Classless Interdomain Data Routing CIDR.ppt
PPT
Computer Network in Network software.ppt
PPT
web program-Extended MARKUP Language XML.ppt
PPTX
Web programming-Introduction to JSP.pptx
PPT
web programmimg- concpt in JAVABEANS.ppt
PPT
web program-Inheritance,pack&except in Java.ppt
PPT
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
PPT
web programming-Multithreading concept in Java.ppt
PPT
Processing Crime and Incident Scenes.ppt
PPT
Working with Windows and DOS Systems (1).ppt
PDF
enterprise resource plnning ERP vendors.pdf
PPT
ERP and elctronic commerce online12.ppt
PPT
Enterprise resourse planning ERPlife cycle.ppt
PPT
Project Management Issues in ERP IS 6006.ppt
PDF
mySAP_Supply_Chain_Management_Solution_Map.pdf
cyber forensics Email Investigations.ppt
Cell Phone and Mobile Devices Forensics.ppt
Computer Forensics Analysis and Validation.ppt
cyber forensics Footprinting and Scanning.ppt
cyber forensics-enum,sniffing,malware threat.ppt
Classless Interdomain Data Routing CIDR.ppt
Computer Network in Network software.ppt
web program-Extended MARKUP Language XML.ppt
Web programming-Introduction to JSP.pptx
web programmimg- concpt in JAVABEANS.ppt
web program-Inheritance,pack&except in Java.ppt
123 JAVA CLASSES, OBJECTS AND METHODS.ppt
web programming-Multithreading concept in Java.ppt
Processing Crime and Incident Scenes.ppt
Working with Windows and DOS Systems (1).ppt
enterprise resource plnning ERP vendors.pdf
ERP and elctronic commerce online12.ppt
Enterprise resourse planning ERPlife cycle.ppt
Project Management Issues in ERP IS 6006.ppt
mySAP_Supply_Chain_Management_Solution_Map.pdf
Ad

Recently uploaded (20)

PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Welding lecture in detail for understanding
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
composite construction of structures.pdf
PDF
PPT on Performance Review to get promotions
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
UNIT 4 Total Quality Management .pptx
DOCX
573137875-Attendance-Management-System-original
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Sustainable Sites - Green Building Construction
PPTX
Lecture Notes Electrical Wiring System Components
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Welding lecture in detail for understanding
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
R24 SURVEYING LAB MANUAL for civil enggi
Internet of Things (IOT) - A guide to understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
composite construction of structures.pdf
PPT on Performance Review to get promotions
bas. eng. economics group 4 presentation 1.pptx
additive manufacturing of ss316l using mig welding
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Operating System & Kernel Study Guide-1 - converted.pdf
UNIT 4 Total Quality Management .pptx
573137875-Attendance-Management-System-original
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Sustainable Sites - Green Building Construction
Lecture Notes Electrical Wiring System Components

web program -Life cycle of a servlet.ppt

  • 2. ADDING IMAGES TO AN APPLET • An applet can display images of the format GIF, JPEG, BMP, and others. To display an image within the applet, you use the drawlmage() method found in the java.awt.Graphics class. • Following is the example showing all the steps to show images: import java.applet. *; Import java.awt. *; import java.net.*; public class ImageDemo extends Applet { private Image image; private AppletContext context; public void init() { context = this.getAppletContext(); String imageURL = this.getParameter("image"); if(imageURL == null) { imageURL = "java.jpg"; }
  • 3. try { URL url = new URL(this.getDocumentBase(), imageURL); image = context.getImage(url); } catch(MalformedURLException e) { e.printStackTrace(); //Display in browser status bar context.showStatus("Could not load image!"); }} public void paint(Graphics g) { context.showStatus("Displaying image"); g.drawImage(image, 0, 0, 200, 84, null); g.drawString("www.java2s.com", 10, 20); }} Now,let us call this applet as follows: <html> <title>The ImageDemo applet</title> <hr> <applet code="ImageDemo.class" width="300" height="200"> <param name="image" value="java.jpg"> </appIet><hr></html>
  • 4. • MalformedURLException is a checked exception. It is inherited from IOException. MalformedURLException is raised by JVM in two occasions. 1. The protocol given in the address as URL may not be a correct (valid) one for the job. 2. The address given in the URL constructor may not be evaluated successfully (due to wrong format etc) by the networking software.
  • 5. Life cycle of a servlet • 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.
  • 6. 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... }
  • 7. 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.
  • 8. The service() Method 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 }
  • 10. 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... }
  • 11. Architectural 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.
  • 12. Sample Code Following is the sample source code structure of a servlet example to show Hello World // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } }
  • 13. Passing Parameter to Applets with example • Java applet has the feature of retrieving the parameter values passed from the html page. So, you can pass the parameters from your html page to the applet embedded in your page. • The param tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. • There are three methods commonly used by applets: – String getParameter(String name)-Returns the value for the specified parameter string – URL getCodeBase()-Returns the URL of the applet – URL getDocumentBase()-Returns the URL of the document containing the applet
  • 14. Example( hai.java) import java.applet.*; import java.awt.*; /*<APPLET code="hai" width="300" height="250"> <PARAM name="Message" value="Hai friend how are you ..?"> </APPLET>*/ public class hai extends Applet { private String defaultMessage = "Hello!“; public void paint(Graphics g) { String inputFromPage = this.getParameter("Message"); if (inputFromPage == null) inputFromPage = defaultMessage; g.drawString(inputFromPage, 50, 55); }}
  • 16. • You only need to change the HTML, not the Java source code. PARAMs let you customize applets without changing or recompiling the code. • This applet is very similar to the HelloWorldApplet. • You pass getParameter() a string that names the parameter you want. This string should match the name of a PARAM element in the HTML page. • getParameter() returns the value of the parameter. All values are passed as strings. • If you want to get another type like an integer, then you'll need to pass it as a string and convert it to the type you really want. • The PARAM element is also straightforward. It occurs between <APPLET> and </APPLET>. • It has two attributes of its own, NAME and VALUE. • NAME identifies which PARAM this is. VALUE is the string value of the PARAM. • Both should be enclosed in double quote marks if they contain white space. An applet is not limited to one PARAM. • You can pass as many named PARAMs to an applet as you like. An applet does not necessarily need to use all the PARAMs that are in the HTML. Additional PARAMs can be safely ignored.
  • 17. Displaying Graphics in Applet • java.awt.Graphics class provides many methods for graphics programming. Commonly used methods of Graphics class: • public abstract void drawString(String str, int x, int y): is used to draw the specified string. • public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width and height. • public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the default color and specified width and height. • public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the specified width and height. • public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default color and specified width and height. • public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the points(x1, y1) and (x2, y2). • public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw the specified image. • public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used draw a circular or elliptical arc. • public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a circular or elliptical arc. • public abstract void setColor(Color c): is used to set the graphics current color to the specified color. • public abstract void setFont(Font font): is used to set the graphics current font to the specified font.
  • 18. Example of Graphics in applet: 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); } } myapplet.html <html> <body> <applet code="GraphicsDemo.class" width="300" height="300"> </applet> </body> </html>
  • 19. AWT Layouts • The LayoutManagers are used to arrange components in a particular manner. • LayoutManager is an interface that is implemented by all the classes of layout managers. When you add a component to an applet or a container, the container uses its layout manager to decide where to put the component. • Different LayoutManager classes use different rules to place components. java.awt.LayoutManager is an interface. Five classes in the java packages implement it: – FlowLayout – BorderLayout – CardLayout – GridLayout – GridBagLayout
  • 20. FlowLayout Java FlowLayout • The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel. Fields of FlowLayout class – public static final int LEFT – public static final int RIGHT – public static final int CENTER – public static final int LEADING – public static final int TRAILING Constructors of FlowLayout class • FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap. • FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap. • FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap. Example of FlowLayout class
  • 21. import java.awt.*; import javax.swing.*; public class MyFlowLayout{ JFrame f; MyFlowLayout(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.setLayout(new FlowLayout(FlowLayout.RIGHT)); //setting flow layout of right alignment f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyFlowLayout(); } }
  • 22. 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: – public static final int NORTH – public static final int SOUTH – public static final int EAST – public static final int WEST – public static final int CENTER Constructors of BorderLayout class: • BorderLayout(): creates a border layout but with no gaps between the components. • JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.
  • 23. • Example of BorderLayout class:
  • 24. import java.awt.*; import javax.swing.*; public class Border { JFrame f; Border(){ f=new JFrame(); JButton b1=new JButton("NORTH");; JButton b2=new JButton("SOUTH");; JButton b3=new JButton("EAST");; JButton b4=new JButton("WEST");; JButton b5=new JButton("CENTER");; 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(); } }
  • 25. Java Card Layout • The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout. Constructors of CardLayout class • CardLayout(): creates a card layout with zero horizontal and vertical gap. • CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap. Commonly used methods of CardLayout class • public void next(Container parent): is used to flip to the next card of the given container. • public void previous(Container parent): is used to flip to the previous card of the given container. • public void first(Container parent): is used to flip to the first card of the given container. • public void last(Container parent): is used to flip to the last card of the given container. • public void show(Container parent, String name): is used to flip to the specified card with the given name.
  • 27. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CardLayoutExample extends JFrame implements ActionListener{ CardLayout card; JButton b1,b2,b3; Container c; CardLayoutExample(){ c=getContentPane(); card=new CardLayout(40,30); //create CardLayout object with 40 hor space and 30 ver space c.setLayout(card); b1=new JButton("Apple"); b2=new JButton("Boy"); b3=new JButton("Cat"); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); c.add("a",b1);c.add("b",b2);c.add("c",b3); } public void actionPerformed(ActionEvent e) { card.next(c); } public static void main(String[] args) { CardLayoutExample cl=new CardLayoutExample(); cl.setSize(400,400); cl.setVisible(true); cl.setDefaultCloseOperation(EXIT_ON_CLOSE); } }
  • 28. GridLayout • The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Constructors of GridLayout class • GridLayout(): creates a grid layout with one column per component in a row. • GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. • GridLayout(int rows, int columns, int hgap, int vgap):creates a grid layout with the given rows and columns along with given horizontal and vertical gaps. • Example of GridLayout class
  • 29. import java.awt.*; import javax.swing.*; public class MyGridLayout{ JFrame f; MyGridLayout(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyGridLayout(); } }
  • 30. Java GridBagLayout • The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. • The components may not be of same size. • Each GridBagLayout object maintains a dynamic, rectangular grid of cells. • Each component occupies one or more cells known as its display area. • Each component associates an instance of GridBagConstraints. • With the help of constraints object we arrange component's display area on the grid. • The GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size.
  • 32. import java.awt.Button; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.*; public class GridBagLayoutExample extends JFrame{ public static void main(String[] args) { GridBagLayoutExample a = new GridBagLayoutExample(); } public GridBagLayoutExample() { GridBagLayoutgrid = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); setLayout(grid); setTitle("GridBag Layout Example"); GridBagLayout layout = new GridBagLayout(); this.setLayout(layout); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; this.add(new Button("Button One"), gbc); gbc.gridx = 1; gbc.gridy = 0; this.add(new Button("Button two"), gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.ipady = 20; gbc.gridx = 0; gbc.gridy = 1; this.add(new Button("Button Three"), gbc); gbc.gridx = 1; gbc.gridy = 1; this.add(new Button("Button Four"), gbc); gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; this.add(new Button("Button Five"), gbc); setSize(300, 300); setPreferredSize(getSize()); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } }
  • 33.
  • 34. Applet for calculator application
  • 35. import java.awt.*; import java.applet.*; import java.awt.event.*; public class calc extends Applet implements ActionListener{ Label l1,l2; TextField t1,t2,t3; Button addition,subtraction,multiplication,division; public void init(){ l1=new Label("enter first no"); add(l1); l2=new Label("enter second no"); add(l2); t1=new TextField(10); add(t1); t2=new TextField(10); add(t2); t3=new TextField(10); add(t3); addition=new Button("+"); add(addition); addition.addActionListener(this); subtraction=new Button("-"); add(subtraction); subtraction.addActionListener(this); multiplication=new Button("*"); add(multiplication); multiplication.addActionListener(this); division=new Button("/"); add(division); division.addActionListener(this);} public void actionPerformed(ActionEvent ae){ if(ae.getSource()==addition){ int sum=Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText()); t3.setText(String.valueOf(sum)); } if(ae.getSource()==subtraction) { int sub=Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText()); t3.setText(String.valueOf(sub)); } if(ae.getSource()==multiplication) { int mul=Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText()); t3.setText(String.valueOf(mul)); } if(ae.getSource()==division) { int div=Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText()); t3.setText(String.valueOf(div)); }}} /* <applet code="calc" width=200 height=200> </applet> */
  • 36. JSP What is JavaServer Pages? • JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content. This helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>. • A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. • Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands. • Using JSP, you can collect input from users through Webpage forms, present records from a database or another source, and create Webpages dynamically. • JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages, and sharing information between requests, pages etc.
  • 37. • JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). • But JSP offers several advantages in comparison with the CGI. – Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having separate CGI files. – JSP are always compiled before they are processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested. – JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc. – JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
  • 38. Advantages of JSP • Following table lists out the other advantages of using JSP over other technologies − • vs. Active Server Pages (ASP) • The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers. • vs. Pure Servlets • It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. • vs. Server-Side Includes (SSI) • SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like. • vs. JavaScript • JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc. • vs. Static HTML • Regular HTML, of course, cannot contain dynamic information.
  • 39. Event Handling Event: • Change in the state of an object is known as event i.e. event describes the change in state of source. • Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen. Types of Event • The events can be broadly classified into two categories: Foreground Events - Those events which require the direct interaction of user. They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page etc. Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.
  • 40. Event Handling: • Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. • These mechanisms have the code which is known as event handler that is executed when an event occurs. • Java Uses the Delegation EventModel to handle the events. This model defines the standard mechanism to generate and handle the events. The Delegation Event Model has the following key participants namely: • Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object. • Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received, the listener processes the event a then returns.
  • 41. Steps involved in event handling • The User clicks the button and the event is generated. • Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object. • Event object is forwarded to the method of registered listener class. • The method is now get executed and returns.
  • 42. 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"); } }