You are on page 1of 103

Department of Computer Science and Engineering

Course Code: KCS-602


Course Name: Web Technology
Faculty Name: Sunny Gupta
Email: sunny.gupta@glbitm.ac.in
Syllabus
Unit-1
Introduction: Introduction and Web Development Strategies, History of Web and Internet, Protocols Governing Web, Writing Web Projects, Connecting to
Internet, Introduction to Internet services and tools, Introduction to client-server computing. Core Java: Introduction, Operator, Data type, Variable, Arrays,
Methods & Classes, Inheritance, Package and Interface, Exception Handling, Multithread programming, I/O, Java Applet, String handling, Event handling,
Introduction to AWT, AWT controls, Layout managers

Unit-2
Web Page Designing: HTML: List, Table, Images, Frames, forms, CSS, Document type definition, XML: DTD, XML schemes, Object Models, presenting and
using XML, Using XML Processors: DOM and SAX, Dynamic HTML

Unit-3
Scripting: Java script: Introduction, documents, forms, statements, functions, objects; introduction to AJAX, Networking : Internet Addressing, InetAddress,
Factory Methods, Instance Methods, TCP/IP Client Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram.

Unit-4
Enterprise Java Bean: Preparing a Class to be a JavaBeans, Creating a JavaBeans, JavaBeans Properties, Types of beans, Stateful Session bean, Stateless
Session bean, Entity bean
Java Database Connectivity (JDBC): Merging Data from Multiple Tables: Joining, Manipulating, Databases with JDBC, Prepared Statements,
Transaction Processing, Stored Procedures.

Unit-5
Servlets: Servlet Overview and Architecture, Interface Servlet and the Servlet Life Cycle, Handling HTTP get Requests, Handling HTTP post Requests,
Redirecting Requests to Other Resources, Session Tracking, Cookies, Session Tracking with Http Session
Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First Java Server Page Example, Implicit Objects, Scripting, Standard Actions,
Directives, Custom Tag Libraries..

Subject:Web
Subject: Web Technology
Technology
Exception Handling in Java

Subject: Web Technology


Exception Handling
Real-time Example of Exception in Java
1. Suppose you are watching a video on
Youtube, suddenly, internet connectivity is
disconnected or not working. In this case,
you are not able to continue watching the
video on Youtube. This interruption is
nothing but an exception.

2. Suppose a person is traveling by car from


Mumbai to Pune. After traveling mid-
distance, the tire of his car is punctured. This
unexpected or unwanted event is nothing
but an exception.
The car owner always keeps an extra tire as an alternative on a long-distance journey. He changes the
punctured tire with a new tire. After changing the tire, he continues the rest of the journey. This
alternative way is called exception handling.

Subject: Web Technology


Exception Handling

Subject: Web Technology


Exception Handling
How does Exception Handling Mechanism Work?
• The code that catches the exception thrown by JVM is called
exception handler in Java.
• It is responsible for receiving information about the
exception/error.
• When an exception occurs, exception handling transfers the
control of execution of the program to an appropriate exception
handler.
• For example, suppose we call a method that opens a file, but the
file does not open. In this case, the execution of that method will
stop and the code that we wrote to handle with this situation will
be run.
• Therefore, we need an alternative way to tell JVM what code has
to be executed to maintain the normal flow of the program when
a certain exception occurs. Thus, exception handling is an
alternative way to continue the execution of the rest of the
program normally.

• We can see the flow diagram in the below figure:

Subject: Web Technology


Exception Handling

Wrong Concept
Compile time exceptions occurs at compile time and
runtime exceptions occur at runtime.
Right Concept
All the exceptions occur at runtime

Subject: Web Technology


Exception Handling in Java(Cont.…)
1. Checked Exceptions A checked exception is an exception that is checked (notified) by
the compiler at compilation-time, these are also called as compile time exceptions.
These exceptions cannot simply be ignored, the programmer should take care of
(handle) these exceptions.

2. Unchecked exceptions is an exception that occurs at the time of execution. These are
also called as Runtime Exceptions. These include programming bugs, such as logic
errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.

3. Errors − These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error will
arise. They are also ignored at the time of compilation.

Subject: Web Technology


Exception Handling in Java(Cont.…)

Subject: Web Technology


Exception Handling in Java(Cont.…)
Checked Exceptions Example if you use FileReader class in your program to read data from a
file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs,
and the compiler prompts the programmer to handle the exception.

Subject: Web Technology


Exception Handling in Java(Cont.…)
Unchecked Exceptions

Subject: Web Technology


Exception Handling in Java(Cont.…)
• Exception Hierarchy

Subject: Web Technology


Exception Handling in Java(Cont.…)
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.

Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed whether
an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

Subject: Web Technology


Exception Handling in Java(Cont.…)
Catching Exceptions
• A method catches an exception using a combination of
the try and catch keywords.
• A try/catch block is placed around the code that might
generate an exception.
• Code within a try/catch block is referred to as
protected code or risky code.

Steps
I. Program statements that you think can raise exceptions are contained within a try block.
II. If an exception occurs within the try block, it is thrown. Code can catch this exception(using
catch block) and handle it in some rational manner.
III. In finally, write the code which must necessarily run. For example- Closing files, and database
connection release.
Note: Finally will run mandatory irrespective run of the exception.
Subject: Web Technology
Exception Handling in Java(Cont.…)

Subject: Web Technology


Exception Handling in Java(Cont.…)
Java finally block
• It is a block that is used to execute important code such as closing connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.

Why use java finally


• Finally block in java can be used to
put "cleanup" code such as closing
a file, closing connection etc..

Subject: Web Technology


Exception Handling in Java(Cont.…)

Subject: Web Technology


Exception Handling in Java(Cont.…)

The throw keyword

• The Java throw keyword is used to explicitly throw an exception.


• We can throw either checked or uncheked exception in java by throw keyword.
• The throw keyword is mainly used to throw custom exception.
• The throw statement is used together with an exception type.
• There are many exception types available in Java: ArithmeticException, FileNotFoundException,
ArrayIndexOutOfBoundsException, SecurityException, etc:

• The syntax of java throw keyword is given below.


throw exception;
• Let's see the example of throw IOException.
throw new IOException ("sorry device error);

Subject: Web Technology


Exception Handling in Java(Cont.…)
Throw an exception
• Example creates a subclass of Exception and throws an exception: class MyException extends
Exception { }
class MyClass
{
void oops()
{
if (/* no error occurred */)
{ /* normal processing */ } else
{ /* error occurred */ throw new MyException(); } }
//oops
}
//class MyClass

Subject: Web Technology


Exception Handling in Java(Cont.…)

As exception handling is not


done in this program, program
will terminate unexpectedly
showing user defined exception.

Subject: Web Technology


Exception Handling in Java(Cont.…)

For exception handling try catch


is used in last program.

Subject: Web Technology


Exception Handling in Java(Cont.…)
Java throws keyword
• The Java throws keyword is used to declare an exception.
• Throws keyword is used to declare an exception. It gives information to the caller method that there may occur an
exception so it is better for the caller method to provide the exception handling code so that normal flow can be
maintained.
• Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not performing check up before the code being used.
• Throws keyword is used to declare only for checked exceptions, if there occurs any unchecked exceptions such as
NullPointerException then programmer should handle it by his code.

Advantage of Java throws keyword


• Now Checked Exception can be propagated (forwarded in call stack).
• It provides information to the caller of the method about the exception.

There are two cases:


Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
Case 2: We have declared the exception i.e. specified throws keyword with the method.

Subject: Web Technology


Exception Handling in Java(Cont.…)
Syntax of java throws
return_type method_name() throws exception_class_name
{
//method code
}

Case 1: Handle Exception Using try-catch block

Subject: Web Technology


Exception Handling in Java(Cont.…)

Subject: Web Technology


Exception Handling in Java(Cont.…)

Subject: Web Technology


Difference Between Throw & throws

Subject: Web Technology


Difference Between Final, Finally & Finalize

Subject: Web Technology


Multithread in Java

Subject: Web Technology


Multitasking

Multitasking
• Task means a small work on a computer, if such work is done in multiples at the same time it is known
as multitasking.
• Multitasking is a process of executing multiple tasks simultaneously.
• We use multitasking to utilize the CPU.
• Multitasking can be achieved in two ways:
1) Process-based Multitasking (Multiprocessing)
2) Thread-based Multitasking (Multithreading)

Subject: Web Technology


Multitasking

1) Process-based Multitasking (Multiprocessing)


• Each process has an address in memory. In other words, each process allocates a separate memory
area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading register,
memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.

Subject: Web Technology


Multithread in Java
• Multi means “many” & threading means “ small logic”.
• A multi-threaded program contains two or more parts that can run concurrently and each part can
handle a different task at the same time making optimal use of the available resources specially when
your computer has multiple CPUs.
• Multithreading in Java is a process of executing multiple threads simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing.
• Multiprocessing and multithreading, both are used to achieve multitasking.
• We use multithreading than multiprocessing because threads use a shared memory area. They don't
allocate separate memory area so saves memory, and context-switching between the threads takes less
time than process.
• Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses
a shared memory area.

Subject: Web Technology


Multithread in Java
• As shown in the figure, a thread is executed inside the process. There is context-switching between the
threads. There can be multiple processes inside the OS, and one process can have multiple threads.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple operations
at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Subject: Web Technology


Multithread in Java
What is Thread?
A thread is a small work/task which is performed in the main program with some specific functionality
along with the main program parallel.
i.e., Light-weight process
Thread is a predefined class that is available in java.lang package.
How to create a thread in java?
i. By Extending the thread class
ii. By implementing a runnable interface

Subject: Web Technology


Multithread in Java
By Extending the thread class
class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi(); t1.start();
}
}
OutPut: Thread is running

Subject: Web Technology


Multithread in Java
By Implementing Runnable interface
class Multi3 implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3(); Thread t1 =new Thread(m1);
t1.start();
}
}

Output: thread is running...

Subject: Web Technology


Multithread in Java
The life cycle of a thread
During the lifetime of a thread, there are many states it can enter.
• They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead stat

Subject: Web Technology


Multithread in Java(Cont.…)

There are various stages of the life cycle of thread as shown in the above diagram:
1. New: In this phase, the thread is created using the class “Thread class". It remains in this state till the
program starts the thread. It is also known as the born thread.
2. Runnable: On this page, the instance of the thread is invoked with a start method. The thread control is
given to the scheduler to finish the execution. It depends on the scheduler, and whether to run the
thread.
3. Running: When the thread starts executing, then the state is changed to a “running” state. The scheduler
selects one thread from the thread pool, and it starts executing in the application.
4. Waiting: This is the state in which a thread has to wait. As there multiple threads are running in the
application, there is a need for synchronization between threads. Hence, one thread has to wait, till the
other thread gets executed. Therefore, this state is referred to as a waiting state.
5. Dead: This is the state in which the thread is terminated. The thread is in a running state and as soon as
it completed processing it is in a “dead state”.

Subject: Web Technology


Multithread in Java(Cont.…)
Java Thread class
Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to
create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
Java Thread Methods

S.N. Modifier Method Description


and Type
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static currentThread() It returns a reference to the currently executing thread object.
Thread
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.

Subject: Web Technology


Multithread in Java(Cont.…)
Java Thread Methods

S.N. Modifier Method Description


and Type
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread object to pause and allow other threads
to execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and all of its subgroups.

Subject: Web Technology


Multithread in Java(Cont.…)
Java Thread Methods

S.N. Modifier Method Description


and Type
17) boolean isDaemon() It tests if the thread is a daemon thread.
18) void setDaemon() It marks the thread as daemon or user thread.
19) void interrupt() It interrupts the thread.
20) boolean isinterrupted() It tests whether the thread has been interrupted.
21) static interrupted() It tests whether the current thread has been interrupted.
boolean
22) static int activeCount() It returns the number of active threads in the current thread's thread group.
23) void checkAccess() It determines if the currently running thread has permission to modify the
thread.
24) static holdLock() It returns true if and only if the current thread holds the monitor lock on the
boolean specified object.

Subject: Web Technology


Multithread in Java(Cont.…)
Java Thread Methods

S.N. Modifier Method Description


and Type
25) static void dumpStack() It is used to print a stack trace of the current thread to the standard error
stream.
26) StackTraceEl getStackTrace() It returns an array of stack trace elements representing the stack dump of the
ement[] thread.
27) static int enumerate() It is used to copy every active thread's thread group and its subgroup into the
specified array.
28) Thread.State getState() It is used to return the state of the thread.
29) ThreadGrou getThreadGroup() It is used to return the thread group to which this thread belongs
p
30) String toString() It is used to return a string representation of this thread, including the thread's
name, priority, and thread group.

Subject: Web Technology


Multithread in Java(Cont.…)
Java Thread Methods

S.N. Modifier and Type Method Description


31) void notify() It is used to give the notification for only one thread which is
waiting for a particular object.
32) void notifyAll() It is used to give the notification to all waiting threads of a
particular object.
33) void setContextClassLoader() It sets the context ClassLoader for the Thread.
34) ClassLoader getContextClassLoader() It returns the context ClassLoader for the thread.
35) static getDefaultUncaughtExcep It returns the default handler invoked when a thread abruptly
Thread.UncaughtExc tionHandler() terminates due to an uncaught exception.
eptionHandler
36) static void setDefaultUncaughtExcept It sets the default handler invoked when a thread abruptly
ionHandler() terminates due to an uncaught exception.

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


Multithread in Java(Cont.…)

Subject: Web Technology


INPUT/OUTPUT in Java

Subject: Web Technology


I/O in Java
Java I/O
• (Input and Output) are used to process the input and produce the output.
• Java uses the concept of a stream to make I/O operations fast. The java.io package contains all the
classes required for input and output operations.
• We can perform file handling in Java by Java I/O API.
• Java brings various streams with its I/O package that helps the user to perform all the input-output
operations. These streams support all types of objects, data types, characters, files, etc. to fully executed
the I/O.
Stream
• Stream is nothing but the flow of data/information from a source to a destination.
• A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream

Subject: Web Technology


I/O in Java
Types of Stream
Input Stream
Reading the data/information from source to destination is known as the input stream. Java application
uses an input stream to read data from a source; it may be a file, an array, a peripheral device, or a socket.
// In general, sources are keywords, mouse, file, etc.
For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream, etc.
Types of an input stream: 1. Byte-stream 2. Character stream
Output Stream
Writing the data/information from the source to the destination is known as output- stream.
//In general, destinations are monitor, printer, etc.
For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.

Subject: Web Technology


Subject: Web Technology
Subject: Web Technology
I/O in Java
• In Java, 3 streams are created for us automatically. All these streams are attached to the console.
1) System.out: standard output stream is used to produce results and contains method println(), print(),
printf().
2) System.in: standard input stream is used read characters from keywords or any other input device. The
read () method is used to read data.
3) System.err: standard error stream is used to output all the errors that a program might throw. Println (),
print(), and print () functions are used to output.
For Examples:
System.out.println("simple message");
System.err.println("error message");
System.in.read();// to read data

Subject: Web Technology


I/O in Java
Before exploring various input and output streams lets look at 3 standard or default streams that Java has
to provide which are also most common in use:

Subject: Web Technology


I/O in Java
Basically these 2-way streams we classified into 2 types:
• Byte Stream: Byte streams are used to perform reading and writing in a java program, a byte of
information/data at a time.
• Character Stream: Character streams are used to perform reading and to write in a java program 2 bytes
of information/data at a time.
• Byte streams input stream classes: java performs different courses, using which can perform a reading of
data with input stream classes.
• Input Stream Class: This is an “Abstract class”. It contains the following method.
1. abstract int read()// this method reads a byte of data from the source and returns that as int.
2. int read(Byte [])// this method reads collections of bytes of data from the source and stores that in
byte[] of your program. It returns int i.e., no of bytes successfully read from the source.
3. Int read(byte[], int offset, int length);// this method reads a collection of byes from the source and
stores that data in byte[] starting from offset-index and length no. of an array.
4. Int available();
5. Void close();

Subject: Web Technology


I/O in Java
• Examples of I/O Java

// Java code to illustrate print()


import java.io.*;

class Demo_print {
public static void main(String[] args)
{

// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}

Subject: Web Technology


Applet in Java

Subject: Web Technology


Applet in Java
• The applet is client-side programming.
• Applet is a special type of program that is embedded in the webpage to generate dynamic
content.
• It runs inside the browser and works on the client side.
• All applets are subclasses (either directly or indirectly) of java.applet.Applet class.
• Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer.
• JDK provides a standard applet viewer tool called applet viewer.
• It is refreshed automatically each time the user revisits the hosting website. Therefore, keeps
full application up to date on each client desktop on which it is running.
• In general, the execution of an applet does not begin at the main() method.
• Output of an applet window is not performed by System.out.println().
• Rather it is handled with various AWT methods

Subject: Web Technology


Applet in Java

Subject: Web Technology


Applet in Java

Subject: Web Technology


Applet in Java

Advantage of Applet
• It works on the client side so less response time.
• Secured
• It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os, etc.

Drawback of Applet
• Plugin is required at the client browser to execute the applet.

Subject: Web Technology


Applet in Java
METHODS

Subject: Web Technology


Applet in Java
For creating any applet java.applet.Applet class must be inherited.
4 life cycle methods of an applet.
1 public void init(): It is used to initialize the Applet. It is invoked only once.
2 public void start(): It is invoked after the init() method or browser is maximized.
It is used to start the Applet.
3 public void stop(): It is used to stop the Applet.
It is invoked when Applet is stopped or the browser is minimized.
Java.awt.Component class
4 Public void destroy(): It is used to destroy the Applet. It is invoked only once.

The Component class provides 1 life cycle method of the applet.


1. public void paint(Graphics g): is used to paint the Applet. It provides a Graphics class object that can be
used for drawing ovals, rectangles, arcs, etc.
The Graphics class provides methods that draw text on a component or an image. The drawString()
method, takes as parameters an instance of the String class containing the text to be drawn, and two
integer values specifying the coordinates where the text should start.

Subject: Web Technology


Applet in Java
There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purposes).
//First.java
Simple example of Applet by html file:
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome",150,150);
}
}

Subject: Web Technology


Applet in Java
By HTML file in Browser

Subject: Web Technology


Applet in Java
By appletViewer tool

Subject: Web Technology


Applet in Java

Subject: Web Technology


Applet in Java

Subject: Web Technology


String Handling in Java

Subject: Web Technology


String Handling in Java
String Handling
• A string is a sequence of characters. But in Java, a string is an object that represents a sequence of
characters.
• The java.lang.String class is used to create a string object.
• An array of characters works the same as a java string.
Examples
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
• Java String class provides several methods to perform operations on string such as compare(), concat(),
split(), length(), replace(), comapreTo(), intern(), substring(), etc.
• The java.lang.String.class implements Serializable, Comparable and CharSequence interfaces.

Subject: Web Technology


String Handling in Java
CharSequence Interface
• The CharSequence interface is used to represent the sequence of characters.
• String, StringBuffer , and StringBuilder classes implement it. It means, we can create strings in Java by
using these three classes.
• The Java String is immutable which means it cannot be changed.
• Whenever we change any string, a new instance is created.
• For mutable strings, you can use StringBuffer and StringBuilder classes.

Subject: Web Technology


String Handling in Java
How to create a String object?
• There are two ways to create a String object:
1. By string literal
2. By new keyword
String Literal
• Java String literal is created by using double quotes. For Example: String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a
new string instance is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

Subject: Web Technology


String Handling in Java
By New Keyword
Syntax: String stringName = new String();
In such a case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
Some Java String class methods:
• char charAt(int index): It returns the char value for the particular index.
• Int length(): It returns string length.
• String substring(int beginIndex): It returns a substring for a given begin index.
• Boolean contains(CharSequnce s): It returns true or false after matching the sequence of char values.
• Boolean equals(Object another): It checks the equality of the string with the given object.
• String concat(String str): It concatenates the specified string.

Subject: Web Technology


String Handling in Java
By New Keyword
Syntax: String stringName = new String();
In such a case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
Some Java String class methods:
• char charAt(int index): It returns the char value for the particular index.
• Int length(): It returns string length.
• String substring(int beginIndex): It returns a substring for a given begin index.
• Boolean contains(CharSequnce s): It returns true or false after matching the sequence of char values.
• Boolean equals(Object another): It checks the equality of the string with the given object.
• String concat(String str): It concatenates the specified string.

Subject: Web Technology


Event Handling in Java

Subject: Web Technology


Event Handling in Java
Event Handling
An event can be defined as changing the state of an object or behavior by performing actions. Actions can
be a button click, cursor movement, keypress through a keyboard or page scrolling, etc.
• The java.awt.event package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events

Subject: Web Technology


Event Handling in Java
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are
nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of
these events are operating system failures/interrupts, operation completion, etc
Event Handling
• It is a mechanism to control the events and to decide what should happen after an event occur.
• To handle the events, Java follows the Delegation Event model.
- It has Sources and Listeners.

Subject: Web Technology


Event Handling in Java
• Source: Events are generated from the source. There are various sources like buttons, checkboxes, lists,
menu-item, choices, scrollbars, text components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
• To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.

Syntax:
addTypeListener()
• Example 1: For KeyEvent we use addKeyListener() to register.
• Example 2:that For ActionEvent we use addActionListener() to register.

Subject: Web Technology


Event Handling in Java
Flow of Event Handling
i. User Interaction with a component is required to generate an event.
ii. The object of the respective event class is created automatically after event generation, and it holds
all information of the event source.
iii. The newly created object is passed to the methods of the registered listener.
iv. The method executes and returns the results.
Some Listener Interfaces:
1. KeyListener: An event that occurs due to a sequence of key presses on the keyword. keyTypes(),
keyPressed(), keyRelesed().
2. MouseWheelListener: An event that specifies that the mouse rotated in a component.
mouseWheelMoved().
3. MouseListener & MouseMotionListener: The event that occur due to the user interaction with the
mouse(Pointing Device). mousePressed(), mouseclicked(), mouseEntered(), mouseExited(),
mouseReleased().

Subject: Web Technology


AWT in Java

Subject: Web Technology


AWT(Abstract Window Toolkit)

Subject: Web Technology


AWT(Abstract Window Toolkit)
in Java

Examples of GUI-based applications:


Airline Ticketing System, ATM, Mobile Applications
Subject: Web Technology
AWT(Abstract Window Toolkit)
in Java

Subject: Web Technology


AWT in Java(Cont.…)
Java AWT Hierarchy

Subject: Web Technology


AWT in Java(Cont.…)

The javap command


disassembles a class file. The javap
command displays information about
the fields, constructors and methods
present in a class file.

Subject: Web Technology


AWT in Java(Cont.…)

Types of containers:
There are four types of containers
in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog

Subject: Web Technology


AWT in Java(Cont.…)
• Java AWT components are platform-dependent i.e., components are displayed according to the view of
the operating system. Java AWT calls the native platform(OS) subroutine for creating API components like
TextField, CheckBox, Button, etc.
• The java.awt.packge provides classes for AWT API such as TextField, Label, TextArea, RadiaButton,
CheckBox, etc.
• Useful Methods of component class are listed below:
Method Description

public void add(Component c) Inserts a component on this component.

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.

Subject: Web Technology


AWT in Java(Cont.…)

Subject: Web Technology


AWT in Java(Cont.…)

Subject: Web Technology


AWT in Java(Cont.…)
How to create AWT
To create AWT, we need a frame. Here are two ways to create GUI using frame
- By extending the Frame class (inheritance)
- By Creating the object of the frame class (association)

Subject: Web Technology


AWT in Java(Cont.…)

Subject: Web Technology


AWT in Java(Cont.…)

Subject: Web Technology


AWT in Java(Cont.…)

By Creating
the object of
the frame
class.

Subject: Web Technology


AWT in Java(Cont.…)
Java AWT Controls
Every user interface considers the following three main aspects:
• UI elements: These are the core visual elements the user eventually sees and interacts with. GWT
provides a huge list of widely used and common elements varying from basic to complex which we will
cover in this tutorial.
• Layouts: They define how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter.
• Behavior: These are events that occur when the user interacts with UI elements. This part will be
covered in the Event Handling chapter.
Every Awt controls inherits properties from the class of the component.
1. Label: A Label object is a component for placing text in a container.

Subject: Web Technology


AWT in Java(Cont.…)
Useful label class constructors are given below:
• Label: Construct an empty label.
Syntax: label I=new Label();
• Label(String text): Constructs a new label with the specified string of text, left justified.
Syntax: label I new label(“this is a label.LEFT);
2. Button: The button is a control component that has a label and generates an event when pressed. This
class creates a labeled button.
Button class constructors:
• Button():
• Button(String text)

Subject: Web Technology


AWT in Java(Cont.…)
3. list: The list component presents the user with a scrolling list of text items. The list represents a list of
text items. The list can be configured so that the user can choose either one item or multiple items.
List class constructors:
• List(): Create a new scrolling list. For example Syntax; List li = new List();
• List(int rows): Creates a new scrolling list initialized with the specified number of visible lines.
• List(int rows, Boolean multipleMode)
4. Text Field
5. Text Area
6. Choice
7. Images
8. Scroll Bar

Subject: Web Technology


AWT in Java(Cont.…)
Java AWT Layout Manager
• The layout means the arrangement of components within the container or placing the component at a
particular position within the container.
• The task of lay-outing the controls is done automatically by the layout manager.
• Layout Manager: The layout manager automatically positions all the components within the container. If
we do not use a layout manager then also the components are positioned by the default layout manager.
• Java provides us with various layout managers to position the controls. The properties like size, shape,
and arrangement vary from one layout manager to another layout managers.
• The layout manager is associated with every container object.
• Each layout manager is an object of the class that implements the Layout Manager.

Subject: Web Technology


AWT in Java(Cont.…)
AWT layout Manager classes are listed below:
1. Border Layout: The Border layout arranges the component to fit in the five regions: east, west, north
south, and center.
Syntax: BorderLayout()(no gap between components), BorderLayout(int hgap, int vgap)(specified
horizontal and vertical gap.
2. CardLayout: The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
Syntax: CardLayout()
3. FlowLayout: FlowLayout is the default layout. It layout the component in a directional flow.
Syntax: FlowLayout()
4. GridLayout: The GridLayout manages the component in form of a rectangular grid.
Syntax: GridLayout()
5. GridBagLayout: This is the most flexible layout manager class.
Syntax: GridBagLayout()

Subject: Web Technology


AWT in Java(Cont…)
Characteristics
• It is a set of native user interface components.
• It is very robust in nature.
• It includes various editing tools like graphics tools and imaging tools.
• It uses native window-system controls.
• It provides functionality to include shapes, colors, and font classes.
Advantages
• It takes very less memory for the development of GUI and executing programs.
• It is highly stable as it rarely crashes.
• It is dependent on the operating system so performance is high.
• It is easy to use for beginners due to its easy interface.

Subject: Web Technology


AWT in Java(Cont…)
Disadvantages
• The buttons of AWT do not support pictures.
• It is heavyweight in nature.
• Two very important components trees and tables are not present.
• Extensibility is not possible as it is platform dependent

Subject: Web Technology

You might also like