Web Technology (Short Notes)

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 84

WEB TECHNOLOGY

SHORT Notes
For Btech Students

Object & class

A class can be defined as a design prototype or a blueprint.

Objects are created from these blueprints.

It essentially defines a common type consisting of properties and methods that operate on these
properties for this common type. Then we define the instances of this class called objects.

 Inheritance

Inheritance is one of the most important characteristics of OOP. Through inheritance, Java promotes the
reusability of code.

Inheritance is a mechanism in Java in which one class can inherit the properties of another class. The
properties that can be inherited include data members and methods of the class.

The class that inherits the properties of another class is called the subclass. The inherited class is
known as the “super” class in Java.

By inheriting the class, the subclass not only inherits the properties but also reuses the code as the
programmer need not once again write the code when it can directly inherit it using inheritance.

In Java, inheritance is achieved by using the “extends” keyword. This extends keyword is used in the
definition of the class and is followed by the class name that is to be inherited.

 A class (child class) can extend another class (parent class) by inheriting its features
 Implements the DRY (Don’t Repeat Yourself) programming principle
 Improves code reusability
 Multi-level inheritance is allowed in Java (a child class can have its own child class as well)

 Polymorphism

Polymorphism is yet another important feature of OOP. Polymorphism is the ability of the language to
allow objects or entities to assume multiple forms. For example, a method that has various
implementations is polymorphic in Java.

Polymorphism is of two types in Java:

Overloading or Compile Time Polymorphism: In compile-time polymorphism, the call to the polymorphic
or overloaded method is resolved at compile time.
Overriding or Runtime Polymorphism: In runtime polymorphism, the call to an overridden method in the
Java program is resolved at runtime.

 Abstraction

Using data abstraction, we only expose the essential parts of the application that are made accessible to
the user. For example, if we have a car, we are not concerned about the internal components of the car,
rather we only consider the car as a whole.

Using a data abstraction mechanism, we only identify the necessary details and ignore the irrelevant
details. Java uses abstract classes and interfaces to achieve abstraction. Interfaces are 100 % abstract as
they only have method prototypes and not their definition.

 Hides the underlying complexity of data


 Helps avoid repetitive code
 Presents only the signature of internal functionality
 Gives flexibility to programmers to change the implementation of abstract behavior
 Partial abstraction (0-100%) can be achieved with abstract classes
 Total abstraction (100%) can be achieved with interfaces

 Encapsulation

Encapsulation is hiding data or protecting the data. In programming, we achieve encapsulation by


wrapping data and methods operating on that data under a single unit.

A class can be viewed as an encapsulation unit i.e. we have data members and methods operating on
these data members as bundled in one single unit.

Proper encapsulation can be achieved by making data members private and having the methods operating
on these data as public so that data is completely protected from the outside entities.

 Restricts direct access to data members (fields) of a class


 Fields are set to private
 Each field has a getter and setter method
 Getter methods return the field
 Setter methods let us change the value of the field

 Types of Java Platforms

Java Platform, Standard Edition (Java SE): Java SE’s API offers the Java programming language’s core
functionality. It defines all the basis of type and object to high-level classes. It is used for networking,
security, database access, graphical user interface (GUI) development, and XML parsing.

Java Platform, Enterprise Edition (Java EE): The Java EE platform offers an API and runtime environment
for developing and running highly scalable, large-scale, multi-tiered, reliable, and secure network
applications.
Java Programming Language Platform, Micro Edition (Java ME): The Java ME platform offers an API and
a small-footprint virtual machine running Java programming language applications on small devices, like
mobile phones.

Java FX: JavaFX is a platform for developing rich internet applications using a lightweight user-interface
API. It user hardware-accelerated graphics and media engines that help Java take advantage of higher-
performance clients and a modern look-and-feel and high-level APIs for connecting to networked data
sources.

What are OOP concepts in Java?

OOP concepts allow us to create specific interactions between Java objects. They make it possible to
reuse code without creating security risks or harming performance and code readability.

There are four main and three secondary principles of object-oriented Java programming. Let’s take a
look at what they are and why they’re useful.

MULTITHREADING IN JAVA

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

• However, 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.

• Java Multithreading is mostly used in games, animation, etc.

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.

What is Thread in Java?

• A thread is a lightweight sub process, the smallest unit of processing. It is a separate path of
execution.
• Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.

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

• Note: At a time one thread is executed only.

WORA, which is abbreviated as Write Once Run Anywhere, is the feature applicable to those programs
which hold the capability to execute itself on any operating systems or any machine. Sun Microsystem
gave this terminology for their programming language - Java. According to this concept, the same code
must run on any machine, and hence the source code needs to be portable. So Java allows run Java
bytecode on any computer irrespective of the machine or the hardware, using JVM (Java Virtual Machine).
The bytecode generated by the compiler is not platform-specific and hence takes the help of JVM to run on
a wide range of machines. So we can call Java programs as a write once and run on any computer residing
anywhere.

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.

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 Thread currentThread() It returns a reference to the currently executing thread


object.

5. void join() It waits for a thread to die.

6. int getPriority() It returns the priority of the thread.

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. void suspend() It is used to suspend the thread.

13. void resume() It is used to resume the suspended thread.

14. void stop() It is used to stop the thread.

15. void destroy() It is used to destroy the thread group and all of its subgroups.

16. boolean isDaemon() It tests if the thread is a daemon thread.

17. void setDaemon() It marks the thread as daemon or user thread.

18. void interrupt() It interrupts the thread.

19. boolean isinterrupted() It tests whether the thread has been interrupted.

20. static boolean interrupted() It tests whether the current thread has been interrupted.

21. static int activeCount() It returns the number of active threads in the current thread's
thread group.

LIFE CYCLE OF THREAD

In Java, a thread always exists in any one of the following states. These states are:

• New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.

• Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other is running.

• Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.

• Terminated: A thread reaches the termination state because of the following reasons: When a
has finished its job, then it exists or terminates normally.

• Abnormal termination: It occurs when some unusual events such as an unhandled exception
or segmentation fault. A terminated thread means the thread is no more in the system. In other
words, the thread is dead, and there is no way one can respawn (active after kill) the dead
thread.

Java Threads | How to create a thread in Java

There are two ways to create a thread:

• By extending Thread class


• Thread class provide constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable interface.

• Commonly used Constructors of Thread class:

• Thread()

• Thread(String name)

• Thread(Runnable r)

• Thread(Runnable r,String name)

• Commonly used methods of Thread class:

• public void run(): is used to perform action for a thread.

• public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.

• public void sleep(long miliseconds): Causes the currently executing thread


to sleep (temporarily cease execution) for the specified number of
milliseconds.

• public void join(): waits for a thread to die.

• public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.

• public int getPriority(): returns the priority of the thread.

• public int setPriority(int priority): changes the priority of the thread.

• public void setName(String name): changes the name of the thread.

• public Thread currentThread(): returns the reference of currently executing


thread.

• public int getId(): returns the id of the thread.

• public Thread.State getState(): returns the state of the thread.

• public boolean isAlive(): tests if the thread is alive.

• By implementing Runnable interface.


1. The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().

2. public void run(): is used to perform action for a thread.

3. Starting a thread:

4. The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:

5. new thread starts(with new callstack).

6. The thread moves from New state to the Runnable state.

7. When the thread gets a chance to execute, its target run() method will run.

Features of JAVA

Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object
model.

Platform Independent − Unlike many other programming languages including C and C++, when Java is
compiled, it is not compiled into platform specific machine, rather into platform-independent bytecode. This
byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is
being run on.

Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be
easy to master.

Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.

Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime system.

Portable − Being architecture-neutral and having no implementation dependent aspects of the specification
makes Java portable. The compiler in Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.

Robust − Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time
error checking and runtime checking.

Multithreaded − With Java multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that can run
smoothly.

Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental and light-
weight process.
High Performance − With the use of Just-In-Time compilers, Java enables high performance.

Distributed − Java is designed for the distributed environment of the internet.

Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time information that can be used to verify
and resolve accesses to objects at run-time.

Features of JavaScript

• Scripting Language

JavaScript is a lightweight scripting language made for client-side execution on the browser. Since it is not
designed as a general-purpose language and is specially engineered for web applications, the set of libraries is
also geared primarily towards web applications.

• Validation of User’s Input

Validation of User’s Input is most commonly known as form validation, it allows users to interact with client
through filling forms through web pages. The details in the form need to be correctly filled where form
validation helps the client to validate the details entered by the user.

interpreter Based

JavaScript is an interpreted language instead of a compiled one. In that sense, it is closer to languages like
Ruby and Python. The browser interprets JavaScript’s source code, line by line and runs it. In contrast, a
compiled language needs to be compiled into a byte-code code executable. Java and C++ are examples of
compiled languages.

Event Handling

An event is an action or an occurrence in a system that communicates about said occurrence so that you can
respond to it somehow. For example, a user clicks on a button, and the system tells you to respond to the
button click event with an action, say an information box.

JavaScript enables you to handle events and even generate custom events.

Case Sensitive

JavaScript is highly case sensitive. All keywords, variables, functions names and other identifiers can and must
only follow a consistent capitalisation of letters. E.g.:

var hitCounter = 5

var hitcounter = 5

Here variables hitCounter and hitcounter are both different variables because of the difference in the case.
Also, all keywords such as “var” are case sensitive.

Control Statements

JavaScript is equipped with control statements like if-else-if, switch-case, and loops like for, while, and do-
while loops. These control statements make it a powerful programming language, enabling its user to write
complex logic.
Platform Independent

JavaScript is platform-independent; it can run on any computer irrespective of the operating systems used.
JavaScript is built into Netscape 2.0 and greater. Since the JavaScript interpreter is part of Netscape, it runs on
platforms that support Netscape, which means that a piece of Javascript code will give the same output with
the same setup on all platforms.

Light Weight

JavaScript isn’t a compiled language, so it doesn’t get converted to byte-code beforehand. However, it does
follow a paradigm called Just-In-Time (JIT) Compilation. Meaning it gets converted to bytecode just as it’s
about to run. This enables JS to be lightweight. Even less powerful devices are capable of running JavaScript.

Dynamic Typing

JavaScript is a dynamically typed language. It means that the JS interpreter does not require explicit
declaration of the variables before they are used. E.g.:

var dynamicType = “a string”

dynamicType = 5

Here we can see the same variable dynamicType can contain either a string or an integer with the same
variable declaration. That is, the variable type does not need to be declared during creation or assignment.

Advantages of JavaScript

Speed. Client-side JavaScript is very fast because it can be run immediately within the client-side browser.
Unless outside resources are required, JavaScript is unhindered by network calls to a backend server.

Simplicity. JavaScript is relatively simple to learn and implement.

Popularity. JavaScript is used everywhere on the web.

Interoperability. JavaScript plays nicely with other languages and can be used in a huge variety of applications.

Server Load. Being client-side reduces the demand on the website server.

Gives the ability to create rich interfaces.

Disadvantages of JavaScript

Client-Side Security. Because the code executes on the users’ computer, in some cases it can be exploited for
malicious purposes. This is one reason some people choose to disable Javascript.

Browser Support. JavaScript is sometimes interpreted differently by different browsers. This makes it
somewhat difficult to write cross-browser code.

Java Applets

 Applets are small Java applications which can be accessed on an Internet server, transported over the
Internet, and can be installed and run automatically as part of a web document.
 The applet can create a graphical user interface after a user gets an applet. It has restricted access to
resources so that complicated computations can be carried out without adding the danger of viruses or
infringing data integrity.
 Any Java applet is a class that extends the class of java.applet.Applet.
There is no main() methods in an Applet class. Using JVM it is regarded. The JVM can operate an applet
application using either a Web browser plug-in or a distinct runtime environment.
JVM generates an applet class instant and invokes init() to initialize an applet.
Simple Applet
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Simple Applet
Every Applet application must import 2 packages - java.applet. & java.awt.
Abstract Window Toolkit (AWT) classes are imported by java.awt.*. Applets communicate (directly or
indirectly) via the AWT with the client. The AWT includes support for a graphical user interface based on a
window. Java.applet.* imports the Applet package containing the Applet class. Any applet you generate must
be an Applet class subclass.
The class in the program must be declared public because code outside of the program will be accessed to it.
Every request in Applet must declare a method for paint. AWT class defines this method and the applet must
override it. Every moment an applet requires to redisplay its output, the paint() method is called. Another
significant thing to notice about the applet implementation is that an applet execution does not start with the
main method. In reality, there is no primary/main method in an applet implementation.

Benefits of Applets
As it operates on the client side, it requires much less response time.
Any browser that has JVM operating in it can operate it.
Applet class
Applet class provides all the support needed to execute applets, such as initializing and destroying applets. It
also provides techniques/methods for loading and displaying audio videos and playback pictures.
An Applet Skeleton
These 4 methods are overridden by most applets. These four methods are the lifecycle of the Applet.
init() : The first technique to be called is init(). This is where you initialize the variable. This technique is only
called once during the applet runtime.
start() : Method start() is called after ini(). This technique is called after it has been stopped to restart an applet.
stop() : Method stop() is called to suspend threads that do not need to operate when the applet is not noticeable.
destroy() : The destroy() technique/method is called if you need to remove your applet from memory entirely.
Note: The stop() method is always called/executed before destroy() method.
Example of an Applet Skeleton
import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet {
public void init() {
//initialization
}
public void start () {
//start or resume execution
}
public void stop() {
//suspend execution
{
public void destroy() {
//perform shutdown activity
}
public void paint (Graphics g) {
//display the content of window
}
}
Example of an Applet
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
int height, width;
public void init() {
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g) {
g.drawRoundRect(10, 30, 120, 120, 2, 3);
}
}

Java AWT

Java programming is used to develop different types of applications like window-based applications, web
applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT
API is used. AWT allows programmers to create Graphical User Interface (GUI) for a window-based application.

Java Abstract Window Toolkit (AWT) is an Application Program Interface (API). The components used in Java
AWT are platform-dependent. It uses recourses of the operating system that means the view of these
components is changed according to the operating system.

Features of AWT

• AWT has a set of native user interface components.


• It provides various classes for graphical representation of components like font, shape, color.
• It provides a robust event-handling model.
• It has Layout managers which is helpful for changing window size or screen resolution.
• It provides a large range of libraries that can be used for designing graphics for gaming applications or
educational applications.
• It has data transfer classes through which cut and paste operation can be performed using the local
clipboard.
• AWT User Interface Aspects

The AWT UI is designed using the following aspects:

• Elements of UI: These are the elements that are visible to the user and using those elements the user
can communicate with the application. AWT provides a wide range of UI elements.
• Layouts: Layouts are useful for managing the different UI elements on the screen and provide a well-
organized look to the application.
• Behavior: It explains how the UI elements act on triggering events performed by the user.

AWT Hierarchy Java AWT


Component In the AWT class hierarchy, the Component class is derived from the Object class. Component
class is an abstract class. It is the superclass of all the GUI element classes like Container, Button, Label,
Checkbox, Choice, and List. Therefore, Component class is responsible for an overall graphical interface.

Container A Container in AWT is a component, which holds all the other components used for building the
interface. We can insert another container inside the main container.

There are four types of container available in AWT:

Window:A window is a rectangular box shaped area displayed on the screen. It is an instance of Window class.
It does not have any menu bar, toolbar, or border. It should always be placed inside another window, frame,
or dialog.

Frame:A Frame is a subclass of Window. It has a border, menu bar, title bar. The size of the frame can also be
changed. It can hold all other AWT components like buttons, checkboxes, etc. Frames are the most widely
used type of AWT container.

Dialog:Dialog is a subclass of Window. It contains a border and title bar. To create a dialog object, an instance
of the associated Frame class is always needed.

Panel: A Panel is a subclass of Container. The Panel does not have any border, title bar, or menu bar. It is a
generic container that holds other GUI components. An instance of Panel class is necessary in order to insert
the components.

Button:The Button class allows the developer to create a button with an appropriate label on it. It also
provides a way to define functionality after clicking the button.

List A List class is used to display a list of required items. Using a list, the user can select one or multiple items
in it.

Checkbox A Checkbox can be used when an application wants the user to choose from either true or false.

Label A Label provides descriptive text information on the application window. It is placed inside a container.

Choice A Choice class is used to display a drop-down menu. The selected choice can be seen on the head.

Advantages of GUI over CLI

• GUI provides interactive graphical elements to perform required actions while in CLI the command
needs to be in text format only.
• GUI offers an easy yet efficient way of communication for the user. But in CLI, it is a difficult task to
remember all the commands.
• GUI gives a facility for multitasking. On the other hand, multitasking is not possible in CLI.
• It is easier for a new user to interact with the application using GUI but it is difficult in CLI.
• GUI makes the application more entertaining and user friendly on the contrary CLI does not.

AWT Classes

The various AWT classes have their own constructors and methods. Some of these constructors and methods
of AWT classes are explained below.
Window:The Window class is the area where other graphical components are placed. It do not consists of a
border and menu bar.

Constructors of the Window class

Constructor Description

• Window(Frame parentframe) Creates a new Window inside the specified Frame.


• Window(Window parentwindow) Creates a new Window inside the specified Window.
• Window(Window parentwindow, GraphicsConfigurationgc) Creates a new Window inside the
specified Window with a GraphicsConfiguration of the display device.

Methods of the Window class

Method Description

• Void paint(Graphics g) Paints the window.


• void setIconImage(Image ig) Uses the image in argument as the icon of the window.
• void setSize(int width, int height) Sets the size of window with values of height and width
arguments.
• void setBounds(int x, int y, int width, int height) Used to set the height and width of the window
using initial points x and y.
• Window getOwner() Returns the parent frame or window of the current window.

Frame The Frame is a subclass of Window. It has a border, title bar, and menu bar. Frame class has its default
layout as BorderLayout.

Constructors of the Frame Class

Constructor Description

• Frame() Creates a new Frame object.


• Frame(GraphicsConfigurationgc) Creates a new Frame with a GraphicsConfiguration of the display
device.
• Frame(String name) Creates a new frame with a name passed as a title of the frame.

Methods of the FrameClass

Method Description

• booleanisResizable() Checks whether the frame is resizable. Returns True or False accordingly.
• MenuBargetMenuBar() Returns the menu bar of the Frame.
• void setMenuBar(MenuBar m) Sets the menu bar of the Frame to another specified Frame.
• void setState(int s) Sets the state of the Frame.
• void setTitle(String t) Changes the title of the Frame with the new title specified.

Panel A Panel is a subclass of Container. The Panel does not have any border, title bar, or menu bar. It has
FlowLayout as its default layout.

Constructors of Panel Class

Constructor Description

• Panel() Constructs a new Panel using FlowLayout.


• Panel(LayoutManagerlm) Constructs a new Panel with the mentioned layout.

Methods of Panel Class

Method Description

• void addNotify() Makes the Panel visible on the device.


• AccessibleContextgetAccessibleContext() Returns the AccessibleContext connected to the Panel.

Dialog Dialog is a subclass of Window. It contains a border and title bar.

Constructors of the Dialog Class

Constructor Description

• Dialog(Dialog Parent) Creates a new dialog with the connected parent dialog and without any
title.
• Dialog(Dialog Parent, String s) Creates a new dialog with the connected parent dialog and with
the mentioned title.
• Dialog(Frame Parent) Creates a new dialog with assigned Frame as a parent and without any
title.
• Dialog(Frame Parent, String s) Creates a new dialog with assigned Frame as a parent and with
the mentioned title.

Methods of the Dialog Class

Method Description

• String getTitle() Returns the assigned title of the Dialog.


• Boolean isResizable() Checks whether the dialog is resizable. Returns True or False accordingly.
• void setTitle(String s) Changes the title of the dialog with the new specified title.
• void setVisible(boolean b) Hides or displays the dialog according to the argument value passed.

Difference between AWT and Swing in Java

Java is one of the most in-demand programming languages for developing a variety of applications. The
popularity of Java can be attributed to its versatility as it can be used to design customized applications that
are light and fast and serve a variety of purposes ranging from web services to android applications. Java is
fast, reliable, and secure. There are multiple ways to develop GUI-based applications in java, out of which the
most popular ones are AWT and Swing.

1. AWT

AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI (Graphical User
Interface) or window-based applications in Java. It was developed by heavily Sun Microsystems In 1995. It is
heavy-weight in use because it is generated by the system’s host operating system. It contains a large number
of classes and methods, which are used for creating and managing GUI.

2. Swing:

Swing is a lightweight Java graphical user interface (GUI) that is used to create various applications. Swing has
platform-independent components. It enables the user to create buttons and scroll bars. Swing includes
packages for creating desktop applications in Java. Swing components are written in Java language. It is a part
of Java Foundation Classes(JFC).
Difference between AWT and Swing:

1. Java AWT is an API to develop GUI applications in Java


Swing is a part of Java Foundation Classes and is used to create various applications.
2. The components of Java AWT are heavy weighted.
The components of Java Swing are light weighted.
3. Java AWT has comparatively less functionality as compared to Swing.
Java Swing has more functionality as compared to AWT.
4. The execution time of AWT is more than Swing.
The execution time of Swing is less than AWT.
5. The components of Java AWT are platform dependent.
The components of Java Swing are platform independent.
6. MVC pattern is not supported by AWT.
MVC pattern is supported by Swing.

7. AWT provides comparatively less powerful components. Swing provides more powerful components.

Why is JavaFX preferred to AWT and Swing?

Swing is the standard toolkit for Java developer in creating GUI, whereas JavaFX provides platform support for
creating desktop applications. Swing has a more sophisticated set of GUI components, whereas JavaFX has a
decent number of UI components available but lesser than what Swing provides.

Java Swing used to create window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

1) AWT components are platform-dependent.


Java swing components are platform-independent.
2) AWT components are heavyweight.
Swing components are lightweight.

3) AWT doesn't support pluggable look and feel.


Swing supports pluggable look and feel.
4) AWT provides less components than Swing.
Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.
5) AWT doesn't follows MVC(Model View Controller) where model represents data, view represents
presentation and controller acts as an interface between model and view.
Swing follows MVC.

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Method Description

• public void add(Component c): add a component on another component.


• public void setSize(int width,int height): sets size of the component.
• public void setLayout(LayoutManager m) :sets the layout manager for the component.
• public void setVisible(boolean b) :sets the visibility of the component. It is by default false.

There are two ways to create a frame:

By creating the object of Frame class (association)

By extending Frame class (inheritance)

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside
the main() method.

File: FirstSwingExample.java

import javax.swing.*;

public class FirstSwingExample {

public static void main(String[] args) {

JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton

b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height

f.setLayout(null);//using no layout managers

f.setVisible(true);//making the frame visible

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.
File: Simple2.java

import javax.swing.*;

public class Simple2 extends JFrame{//inheriting JFrame

JFrame f;

Simple2(){

JButton b=new JButton("click");//create button

b.setBounds(130,100,100, 40);

add(b);//adding button on frame

setSize(400,500);

setLayout(null);

setVisible(true);

public static void main(String[] args) {

new Simple2();

What is XML?

• Xml (eXtensible Markup Language) is a mark up language.


• XML is designed to store and transport data.
• Xml was released in late 90’s. it was created to provide an easy to use and store self describing data.
• XML became a W3C Recommendation on February 10, 1998.
• XML is not a replacement for HTML.
• XML is designed to be self-descriptive.
• XML is designed to carry data, not to display data.
• XML tags are not predefined. You must define your own tags.
• XML is platform independent and language independent.

WHY XML?

• Platform Independent and Language Independent: The main benefit of xml is that you can use it to
take data from a program like Microsoft SQL, convert it into XML then share that XML with other
programs and platforms. You can communicate between two platforms which are generally very
difficult.

• The main thing which makes XML truly powerful is its international acceptance. Many corporation use
XML interfaces for databases, programming, office application mobile phones and more. It is due to its
platform independent feature.
MAIN FEATURE OR ADVANTAGE OF XML

• XML is widely used in the era of web development. It is also used to simplify data storage and data
sharing.

• XML separates data from HTML

• If you need to display dynamic data in your HTML document, it will take a lot of work to edit the
HTML each time the data changes.

• With XML, data can be stored in separate XML files. This way you can focus on using HTML/CSS
for display and layout, and be sure that changes in the underlying data will not require any
changes to the HTML. With a few lines of JavaScript code, you can read an external XML file and
update the data content of your web page.

• XML simplifies data sharing

• In the real world, computer systems and databases contain data in incompatible formats.

• XML data is stored in plain text format. This provides a software- and hardware-independent
way of storing data.

• This makes it much easier to create data that can be shared by different applications

• XML simplifies data transport

• One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.

• Exchanging data as XML greatly reduces this complexity, since the data can be read by different
incompatible applications.

• XML simplifies Platform change

• Upgrading to new systems (hardware or software platforms), is always time consuming. Large
amounts of data must be converted and incompatible data is often lost.

• XML data is stored in text format. This makes it easier to expand or upgrade to new operating
systems, new applications, or new browsers, without losing data.

• XML increases data availability

• Different applications can access your data, not only in HTML pages, but also from XML data
sources.

• With XML, your data can be available to all kinds of "reading machines" (Handheld computers,
voice machines, news feeds, etc), and make it more available for blind people, or people with
other disabilities.

An XML document is called well-formed if it satisfies certain rules, specified by the W3C.

These rules are:

• A well-formed XML document must have a corresponding end tag for all of its start tags.
• Nesting of elements within each other in an XML document must be proper. For example,
<tutorial><topic>XML</topic></tutorial> is a correct way of nesting but
<tutorial><topic>XML</tutorial></topic> is not.

• In each element two attributes must not have the same value. For example, <tutorial
id="001"><topic>XML</topic></tutorial> is right,but <tutorial id="001"
id="w3r"><topic>XML</topic></tutorial> is incorrect.

• Markup characters must be properly specified. For example, <tutorial


id="001"><topic>XML</topic></tutorial> is right, not <tutorial id="001"
id="w3r"><topic>XML</topic></tutorial>.

• An XML document can contain only one root element. So, the root element of an xml document is an
element which is present only once in an xml document and it does not appear as a child element
within any other element.

DTD (Document Type Definition)

• A DTD defines the structure and the legal elements and attributes of an XML document.

• With a DTD, independent groups of people can agree on a standard DTD for interchanging data.

• An application can use a DTD to verify that XML data is valid.

INTERNAL DTD

• The DTD above is interpreted like this:

• !DOCTYPE note defines that the root element of this document is note

• !ELEMENT note defines that the note element must contain four elements: "to,from,heading,body"

• !ELEMENT to defines the to element to be of type "#PCDATA"

• !ELEMENT from defines the from element to be of type "#PCDATA"

• !ELEMENT heading defines the heading element to be of type "#PCDATA"

• !ELEMENT body defines the body element to be of type "#PCDATA"

EXTERNAL DTD

• And here is the file "note.dtd", which contains the DTD:

• <!ELEMENT note (to,from,heading,body)>

• <!ELEMENT to (#PCDATA)>

• <!ELEMENT from (#PCDATA)>

• <!ELEMENT heading (#PCDATA)>


• <!ELEMENT body (#PCDATA)>

The Building Blocks of XML Documents

Seen from a DTD point of view, all XML documents are made up by the following building blocks:

• Elements: Examples of HTML elements are "body" and "table". Examples of XML elements could be
"note" and "message". Elements can contain text, other elements, or be empty. Examples of empty
HTML elements are "hr", "br" and "img".

• Attributes: Attributes are always placed inside the opening tag of an element. Attributes always come
in name/value pairs.

• Entities: Some characters have a special meaning in XML, like the less than sign (<) that defines the
start of an XML tag.

HTML entity: "&nbsp;". This "no-breaking-space" entity is used in HTML to insert an extra
space in a document. Entities are expanded when a document is parsed by an XML parser.

The following entities are predefined in XML:

Entity References Character

&lt; <

&gt; >

&amp; &

&quot; "

&apos; '

• PCDATA: PCDATA means parsed character data.

1. character data as the text found between the start tag and the end tag of an XML element.
2. PCDATA is text that Will be parsed by a parser. The text will be examined by the parser for
entities and markup.
3. Tags inside the text will be treated as markup and entities will be expanded.
4. However, parsed character data should not contain any &, <, or > characters; these need to be
represented by the &amp; &lt; and &gt; entities, respectively.

• CDATA: CDATA means character data.

CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be treated as markup
and entities will not be expanded.

The attribute-value can be one of the following:

• Value Explanation

• value The default value of the attribute

DTD:

<!ELEMENT square EMPTY>


<!ATTLIST square width CDATA "0">

Valid XML:

<square width="100" />

In the example above, the "square" element is defined to be an empty element with a "width"
attribute of type CDATA. If no width is specified, it has a default value of 0.

• #REQUIRED The attribute is required

<!ATTLIST element-name attribute-name attribute-type #REQUIRED>

DTD:

<!ATTLIST person number CDATA #REQUIRED>

Valid XML:

<person number="5677" />

Invalid XML:

<person />

Use the #REQUIRED keyword if you don't have an option for a default value, but still want to
force the attribute to be present.

• #IMPLIED The attribute is optional

<!ATTLIST element-name attribute-name attribute-type #IMPLIED>

DTD:

<!ATTLIST contact fax CDATA #IMPLIED>

Valid XML:

<contact fax="555-667788" />

Valid XML:

<contact />

Use the #IMPLIED keyword if you don't want to force the author to include an attribute, and
you don't have an option for a default value.

• #FIXED value The attribute value is fixed

<!ATTLIST element-name attribute-name attribute-type #FIXED "value">

Example

DTD:

<!ATTLIST sender company CDATA #FIXED "Microsoft">


Valid XML:

<sender company="Microsoft" />

Invalid XML:

<sender company=“abc" />

Use the #FIXED keyword when you want an attribute to have a fixed value without allowing
the author to change it.

• #ENUMERATED value The attribute value is one of a fixed set of values

<!ATDTD:

<!ATTLIST payment type (check|cash) "cash">

XML example:

<payment type="check" />

or

<payment type="cash" />

Use enumerated attribute values when you want the attribute value to be one of a fixed set of legal
values.TLIST element-name attribute-name (en1|en2|..) default-value>

XML PARSERS

• An XML parser is a software library or package that provides interfaces for client applications to work
with an XML document.

• The XML Parser is designed to read the XML and create a way for programs to use XML.

• XML parser validates the document and check that the document is well formatted.

There are the two main types of XML Parsers:

1. DOM

 A DOM document is an object which contains all the information of an XML document. It is
composed like a tree structure. The DOM Parser implements a DOM API. This API is very simple
to use.

 A DOM Parser creates an internal structure in memory which is a DOM document object and
the client applications get information of the original XML document by invoking methods on
this document object.

 DOM Parser has a tree based structure.

Advantages

1) It supports both read and write operations and the API is

very simple to use.


2) It is preferred when random access to widely separated parts

of a document is required.

Disadvantages

1) It is memory inefficient. (consumes more memory

because the whole XML document needs to loaded into memory).

2) It is comparatively slower than other parsers.

2. SAX

 A SAX Parser implements SAX API. This API is an event based API and less intuitive.

 It does not create any internal structure.

 Clients does not know what methods to call, they just overrides the methods of the API and
place his own code inside method.

 It is an event based parser, it works like an event handler in Java.

Advantages

1) It is simple and memory efficient.

2) It is very fast and works for huge documents

Disadvantages

1) It is event-based so its API is less intuitive.

2) Clients never know the full information because the data is broken into pieces.

What does XML DOM?

• The XML DOM makes a tree-structure view for an XML document.

• We can access all elements through the DOM tree.

• We can modify or delete their content and also create new elements. The elements, their content (text
and attributes) are all known as nodes.

• For example, consider this table, taken from an HTML document:

What is an XML Schema?

 An XML Schema describes the structure of an XML document.


 The XML Schema language is also referred to as XML Schema Definition (XSD).
 XML Schema is an XML-based (and more powerful) alternative to DTD.

XML Schemas Support Data Types

 One of the greatest strength of XML Schemas is the support for data types.
 It is easier to describe allowable document content
 It is easier to validate the correctness of data
 It is easier to define data facets (restrictions on data)
 It is easier to define data patterns (data formats)
 It is easier to convert data between different data types

XML Schemas use XML Syntax

 Another great strength about XML Schemas is that they are written in XML.
 You don't have to learn a new language
 You can use your XML editor to edit your Schema files
 You can use your XML parser to parse your Schema files
 You can manipulate your Schema with the XML DOM
 You can transform your Schema with XSLT
 XML Schemas are extensible, because they are written in XML.
 With an extensible Schema definition you can:
 Reuse your Schema in other Schemas
 Create your own data types derived from the standard types
 Reference multiple schemas in the same document

XSD Simple Elements

 A simple element is an XML element that can contain only text. It cannot contain any other elements
or attributes.
 However, the "only text" restriction is quite misleading. The text can be of many different types. It can
be one of the types included in the XML Schema definition (boolean, string, date, etc.), or it can be a
custom type that you can define yourself.
 You can also add restrictions (facets) to a data type in order to limit its content, or you can require the
data to match a specific pattern.

Defining a Simple Element

 <xs:elXML Schema has a lot of built-in data types. The most common types are:
 xs:string
 xs:decimal
 xs:integer
 xs:boolean
 xs:date
 xs:timeement name="xxx" type="yyy"/>

eg : <lastname>Refsnes</lastname>

<age>36</age>

<dateborn>1970-03-27</dateborn>

<xs:element name="lastname" type="xs:string"/>

<xs:element name="age" type="xs:integer"/>

<xs:element name="dateborn" type="xs:date"/>


Restrictions on Values
The following example defines an element called "age" with a restriction.
The value of age cannot be lower than 0 or greater than 120:

xs:element name="age">

<xs:simpleType>

<xs:restriction base="xs:integer">

<xs:minInclusive value="0"/>

<xs:maxInclusive value="120"/>

</xs:restriction>

</xs:simpleType>

</xs:element>

Restrictions on a Set of Values

To limit the content of an XML element to a set of acceptable values, we would use the enumeration
constraint.

The example below defines an element called "car" with a restriction. The only acceptable values are: Audi,
Golf, BMW:

<xs:element name="car">

<xs:simpleType>

<xs:restriction base="xs:string">

<xs:enumeration value="Audi"/>

<xs:enumeration value="Golf"/>

<xs:enumeration value="BMW"/>

</xs:restriction>

</xs:simpleType>

</xs:element>

Restrictions on a Series of Values

To limit the content of an XML element to define a series of numbers or letters that can be used, we would
use the pattern constraint.

The example below defines an element called "letter" with a restriction. The only acceptable value is ONE of
the LOWERCASE letters from a to z:

<xs:element name="letter">
<xs:simpleType>

<xs:restriction base="xs:string">

<xs:pattern value="[a-z]"/>

</xs:restriction>

</xs:simpleType>

</xs:element>

The next example defines an element called "initials" with a restriction. The only acceptable value is THREE
of the UPPERCASE letters from a to z:

<xs:element name="initials">

<xs:simpleType>

<xs:restriction base="xs:string">

<xs:pattern value="[A-Z][A-Z][A-Z]"/>

</xs:restriction>

</xs:simpleType>

</xs:element>

What is AJAX?

• AJAX = Asynchronous JavaScript and XML.

• AJAX is a technique for creating fast and dynamic web pages.

• AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the
server behind the scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.

• Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

• Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
AJAX is Based on Internet Standards

1. AJAX is based on internet standards, and uses a combination of:


a. XMLHttpRequest object (to exchange data asynchronously with a server)
b. JavaScript/DOM (to display/interact with the information)
c. CSS (to style the data)
d. XML (often used as the format for transferring data)
e. AJAX applications are browser- and platform-independent!

FEATURES OF AJAX

1. An event occurs in a web page (the page is loaded, a button is clicked)


3. An XMLHttpRequest object is created by JavaScript
4. The XMLHttpRequest object sends a request to a web server
5. The server processes the request
6. The server sends a response back to the web page
7. The response is read by JavaScript
8. Proper action (like page update) is performed by JavaScript

Create an XMLHttpRequest Object

1. All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-in XMLHttpRequest
object.
2. Syntax for creating an XMLHttpRequest object:
3. variable = new XMLHttpRequest();

Define a Callback Function

A callback function is a function passed as a parameter to another function.

In this case, the callback function should contain the code to execute when the response is ready.

xhttp.onload = function() {

// What to do when the response is ready

Send a Request

To send a request to a server, you can use the open() and send() methods of the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt");

xhttp.send();

XMLHttpRequest Object Methods

1. Method Description
2. new XMLHttpRequest() Creates a new XMLHttpRequest object
3. abort() Cancels the current request
4. getAllResponseHeaders() Returns header information
5. getResponseHeader() Returns specific header information
6. open(method, url, async, user, psw) Specifies the request
7. method: the request type GET or POST
8. url: the file location
9. async: true (asynchronous) or false (synchronous)
10. user: optional user name
11. psw: optional password
12. send() Sends the request to the server
13. Used for GET requests
14. send(string) Sends the request to the server.
15. Used for POST requests
16. setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties

1. Property Description
2. onload Defines a function to be called when the request is recieved (loaded)
3. onreadystatechange Defines a function to be called when the readyState property changes
4. readyState Holds the status of the XMLHttpRequest.
5. 0: request not initialized
6. 1: server connection established
7. 2: request received
8. 3: processing request
9. 4: request finished and response is ready
10. responseText Returns the response data as a string
11. responseXML Returns the response data as XML data
12. status Returns the status-number of a request
13. 200: "OK"
14. 403: "Forbidden"
15. 404: "Not Found"

The onreadystatechange Property

1. The readyState property holds the status of the XMLHttpRequest.


2. The onreadystatechange property defines a callback function to be executed when the readyState
changes.
3. The status property and the statusText properties hold the status of the XMLHttpRequest object.
Property Description
 onreadystatechange Defines a function to be called when the readyState property changes
 readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
 status 200: "OK"
403: "Forbidden"
404: "Page not found"
 statusText Returns the status-text (e.g. "OK" or "Not Found")
 The onreadystatechange function is called every time the readyState changes.
 When readyState is 4 and status is 200, the response is ready:

Server Response Properties

1. responseText get the response data as a string


2. responseXML get the response data as XML data

1) What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It is a group of related technologies used to display data
asynchronously. In other words, it sends and retrieves data without reloading the web page.

2) What are the advantages of AJAX?

1. Quick Response
2. Bandwidth utilization
3. The user is not blocked until data is retrieved from the server.
4. It allows us to send only important data to the server.
5. It makes the application interactive and faster.

3) What are the real web applications of AJAX currently running in the market?

1. Twitter
2. Facebook
3. Gmail
4. Youtube

6) What is the difference between synchronous and asynchronous requests?

Synchronous request blocks the user until a response is retrieved whereas asynchronous doesn't block the
user.

7) What are the technologies used by AJAX?

1. HTML/XHTML and CSS - These technologies are used for displaying content and style.
2. DOM - It is used for dynamic display and interaction with data.
3. XML - It is used for carrying data to and from server
4. XMLHttpRequest - It is used for asynchronous communication between client and server.
5. JavaScript - It is used mainly for client-side validation

8) What is the difference between JavaScript and AJAX?

1. JavaScript is an object-based scripting language. AJAX is a group of inter-related


technologies like JavaScript, XML, HTML, CSS etc
1. It requests the server and waits for the response. It sends a request to the server and doesn't
wait for the response.
2. It consumes more bandwidth as it reloads the page. It doesn't reload the page so consumes less
bandwidth.

SERVLET

Servlet technology is used to create a web application (resides at server side and generates a dynamic web
page). Servlet technology is robust and scalable because of java language.

Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.

1. Servlet is a technology which is used to create a web application.


2. Servlet is an API that provides many interfaces and classes including documentation.
3. Servlet is an interface that must be implemented for creating any Servlet.
4. Servlet is a class that extends the capabilities of the servers and responds to the incoming requests.
It can respond to any requests.
5. Servlet is a web component that is deployed on the server to create a dynamic web page

CGI (Common Gateway Interface)

CGI Technology enables the web server to all an external

program and pass HTTP request information to the external


program to process the request. For each request, it starts

a new process.

Disadvantages of CGI

There are many problems in CGI technology:

1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

There are many advantages of Servlet over CGI.

• The web container creates threads for handling the multiple requests to the Servlet. Threads have
many benefits over the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as follows:

 Better performance: because it creates a thread for each request, not process.


 Portability: because it uses Java language.
 Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
 Secure: because it uses java language.

GET & POST Method

GET POST

1) In case of Get request, only limited amount of In case of post request, large amount of data can be sent
data can be sent because data is sent in header. because data is sent in body.
2) Get request is not secured because data is Post request is secured because data is not exposed in URL
exposed in URL bar. bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second Post request is non-idempotent.


request will be ignored until response of first
request is delivered

5) Get request is more efficient and used more Post request is less efficient and used less than get.
than Post.

Servlet API

• The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

• The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.

• The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.

Servlets - Life Cycle

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are
the paths followed by a servlet.

 The servlet is initialized by calling the init() method.


o 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.
o 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.
o 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.
o The init method definition looks like this −
o public void init() throws ServletException { // Initialization code... }

 The servlet calls service() method to process a client's request.


o 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.
o 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 { }
o 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 }
o the doPost() Method
 A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
 public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // Servlet code }

 The servlet is terminated by calling the destroy() method.


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

Finally, servlet is garbage collected by the garbage collector of the JVM.

Architecture Diagram

The following figure depicts a typical servlet life-cycle scenario.

 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple threads, each thread
executing the service() method of a single instance of the servlet.
ServletRequest Interface with example

When a client sends a request to the web server, the servlet container creates ServletRequest &
ServletResponse objects and passes them as an argument to the servlet’s service() method. The request object
provides the access to the request information such as header and body information of request data.

First we will see an example and then we will see the list of methods available in the ServletRequest interface:

Example 1: ServletRequest getParameter() method to display the user input

In this html form, we are taking user input (name and age) and storing them in the parameters uname and
uage respectively.

index.html

<form action="details" method="get">

User Name: <input type="text" name="uname"><br>

User Age: <input type="text" name="uage"><br>

<input type="submit" value="submit">

</form>

MyServletDemo.java

In this servlet class we are getting the value of the parameters by using getParameter() method, this method
belongs to the ServletRequest interface. In this example we have HttpServletRequest as a parameter of
doGet() method, HttpServletRequest extends ServletRequest interface thats why the getParameter() method
is available to the req object.

After getting the values, we are writing them on the webpage.

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class MyServletDemo extends HttpServlet{

public void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException
{

res.setContentType("text/html");

PrintWriter pwriter=res.getWriter();

String name = req.getParameter("uname");

String age = req.getParameter("uage");

pwriter.println("Name: "+name);

pwriter.println("Age: "+age);

pwriter.close();

Web.xml

This is your deployment descriptor file that maps the servlet to the url. Since our form has details page as
action, we mapped the servlet class to the details page.

<web-app>

<display-name>Demo</display-name>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>

</welcome-file-list>

<servlet>

<servlet-name>BeginnersBook</servlet-name>

<servlet-class>MyServletDemo</servlet-class>

</servlet>
<servlet-mapping>

<servlet-name>BeginnersBook</servlet-name>

<url-pattern>/details</url-pattern>

</servlet-mapping>

</web-app>

screen 2 that appears upon clicking submit:

Example 2: Getting parameter names and values

In this example, we will be using getParameterNames() and getParameter() methods to get parameter names
and values.
getParameterNames(): Returns an Enumeration of String objects containing the names of the parameters
contained in this request. If the request has no parameters, the method returns an empty Enumeration.

getParameter(): As mentioned above, this returns the value of given parameter.


index.html

<form action="details" method="get">

User Name: <input type="text" name="uname"><br>

User Age: <input type="text" name="uage"><br>

<input type="submit" value="submit">

</form>

MyServletDemo.class

import java.io.IOException;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.Enumeration; 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class MyServletDemo extends HttpServlet{    

public void doGet(HttpServletRequest req,HttpServletResponse res)    

throws ServletException,IOException    

{  

PrintWriter pwriter=res.getWriter(); res.setContentType("text/html");

Enumeration en=req.getParameterNames();

while(en.hasMoreElements())

Object obj=en.nextElement();

String param=(String)obj;

String pvalue=req.getParameter(param);

pwriter.print("Parameter Name: "+param+  

" Parameter Value: "+pvalue);

pwriter.close();  

web.xml

<web-app>

<servlet>

<servlet-name>BeginnersBook</servlet-name>

<servlet-class>MyServletDemo</servlet-class>
</servlet>

<servlet-mapping>

<servlet-name>BeginnersBook</servlet-name>

<url-pattern>/details</url-pattern>

</servlet-mapping>

</web-app>

Example 3: Display Header information

index.html

<h1>Servlet Request Demo</h1>

<body>

<a href="headinfo">Click Here</a>

</body>

HeaderDetails.java

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
public class HeaderDetails extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

response.setContentType("text/html");

PrintWriter pwriter = response.getWriter();

pwriter.println("HTTP header Information:<br>");

Enumeration en = request.getHeaderNames();

while (en.hasMoreElements()) {

String hName = (String) en.nextElement();

String hValue = request.getHeader(hName);

pwriter.println("<b>"+hName+": </b>"

+hValue + "<br>");

web.xml

<web-app>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>

<servlet-name>BeginnersBook</servlet-name>

<servlet-class>HeaderDetails</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>BeginnersBook</servlet-name>

<url-pattern>/headinfo</url-pattern>

</servlet-mapping>

</web-app

Example:

In the below example, we have used setContentType() and getWriter() methods of ServletResponse interface.

index.html

<form action="mydetails" method="get">


User name: <input type="text" name="uname">

<input type="submit" value="login">

</form>

MyServletDemo.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class MyServletDemo extends HttpServlet{

public void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException

res.setContentType("text/html");

PrintWriter pwriter=res.getWriter();

String name=req.getParameter("uname");

pwriter.println("User Details Page:");

pwriter.println("Hello "+name);

pwriter.close();

web.xml

<web-app>

<servlet>

<servlet-name>DemoServlet</servlet-name>

<servlet-class>MyServletDemo</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>DemoServlet</servlet-name>
<url-pattern>/mydetails</url-pattern>

</servlet-mapping>

</web-app>

Servlet is a java program that runs inside JVM on the web server. It is used for developing dynamic web
applications.
Dynamic web application: A web application can be described as collection of web pages (e.g. a website) and
when we call it dynamic, it simply means that the web pages are not same for all the users, web pages would
be generated on server side based on the request made by client(user’s browser).

The main difference between static and dynamic web page is that static page as name suggests remains
same for all users however a dynamic web page changes based on the request from client (user’s browser).
For example, consider a web application that shows you two input fields & an add button and when you enter
two numbers and click add, it shows you another web page that has the result of addition of two numbers,
this web application is dynamic in nature as the second web page that shows you the result changes based on
the user input, it is not static for all users.

However you can very well say that what a servlet does can be done by CGI (Common Gateway Interface), well
its true but here is the thing – CGI has several limitations such as performance, scalability, reusability etc.
that a servlet doesn’t have.

Limitations of CGI

Server has to create a new CGI process for every client request. For example, If 100 users are accessing the
web application, then the server has to create 100 CGI processes to handle the request made by them. Since a
server has limited resources, creating new process every time for a new request is not a viable option, this
imposed the limitation on server, due to that the server cannot handle more than a specified number of users
at the same time.

How Servlet is better than CGI

CGI programs are handled by a new process every time a new request has been made. Unlike CGI, the servlet
programs are handled by separate threads that can run concurrently more efficiently.

CGI program can be written in any programming language that makes it mostly platform dependent as not all
programming languages are platform independent. Servlet only uses Java as programming language that
makes it platform independent and portable. Another benefit of using java is that the servlet can take
advantage of the object oriented programming features of java.

How Servlet Works


concurrent requests to the server are handled by threads, here is the graphical representation of the same –

Features of Servlet

1. Portable:
Servlet uses Java as a programming language, since java is platform independent, the same holds true for
servlets. For example, you can create a servlet on Windows operating system that users GlassFish as web
server and later run it on any other operating system like Unix, Linux with Apache tomcat web server, this
feature makes servlet portable and this is the main advantage servlet has over CGI.

2. Efficient and scalable:


Once a servlet is deployed and loaded on a web server, it can instantly start fulfilling request of clients. The
web server invokes servlet using a lightweight thread so multiple client requests can be fulling by servlet at the
same time using the multithreading feature of Java. Compared to CGI where the server has to initiate a new
process for every client request, the servlet is truly efficient and scalable.

3. Robust:
By inheriting the top features of Java (such as Garbage collection, Exception handling, Java Security
Manager etc.) the servlet is less prone to memory management issues and memory leaks. This makes
development of web application in servlets secure and less error prone.

Servlet API

You need to use Servlet API to create servlets.

There are two packages, the javax.servlet package that contains the classes to support generic servlet
(protocol-independent servlet) and the javax.servlet.http package that contains classes to support http servlet.
Let’s see the hierarchy of packages:

java.lang.Object

|_extended by javax.servlet.GenericServlet

|_extended by javax.servlet.http.HttpServlet

Every Servlet must implement the java.servlet.Servlet interface, you can do it by extending one of the
following two classes: javax.servlet.GenericServlet or javax.servlet.http.HttpServlet. The first one is for
protocol independent Servlet and the second one for http Servlet.

How servlet works?

Generic Servlet

As I mentioned above, if you are creating a Generic Servlet then you must
extend javax.servlet.GenericServlet class. GenericServlet class has an abstract service() method. Which means
the subclass of GenericServlet should always override the service() method.
Signature of service() method:

public abstract void service(ServletRequest request, ServletResponse response)

throws ServletException, java.io.IOException

The service() method accepts two arguments ServletRequest object and ServletResponse object. The request
object tells the servlet about the request made by client while the response object is used to return a
response back to the client.

HTTP Servlet

If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class, which is an abstract class.
Unlike Generic Servlet, the HTTP Servlet doesn’t override the service() method. Instead it overrides one or
more of the following methods. It must override at least one method from the list below:

 doGet() – This method is called by servlet service method to handle the HTTP GET request from client.
The Get method is used for getting information from the server
 doPost() – Used for posting information to the Server
 doPut() – This method is similar to doPost method but unlike doPost method where we send
information to the server, this method sends file to the server, this is similar to the FTP operation from
client to server
 doDelete() – allows a client to delete a document, webpage or information from the server
 init() and destroy() – Used for managing resources that are held for the life of the servlet
 getServletInfo() – Returns information about the servlet, such as author, version, and copyright.
In Http Servlet there is no need to override the service() method as this method dispatches the Http Requests
to the correct method handler, for example if it receives HTTP GET Request it dispatches the request to the
doGet() method.

Interfaces in javax.servlet package

 Servlet
 ServletRequest
 ServletResponse
 ServletConfig
 ServletContext
 SingleThreadModel
 RequestDispatcher
 ServletRequestListener
 ServletRequestAttributeListener
 ServletContextListener
 ServletContextAttributeListener
 Filter
 FilterConfig
 FilterChain
Classes in javax.servlet package

 GenericServlet
 ServletInputStream
 ServletOutputStream
 ServletException
 ServletRequestWrapper
 ServletRequestEvent
 ServletResponseWrapper
 ServletContextEvent
 ServletRequestAttributeEvent
 ServletContextAttributeEvent
 UnavailableException
Interfaces in javax.servlet.http package

 HttpSession
 HttpServletRequest
 HttpServletResponse
 HttpSessionAttributeListener
 HttpSessionListener
 HttpSessionBindingListener
 HttpSessionActivationListener
 HttpSessionContext
Classes in javax.servlet.http package
 HttpServlet
 Cookie
 HttpSessionEvent
 HttpSessionBindingEvent
 HttpServletRequestWrapper
 HttpServletResponseWrapper
 HttpUtils

Web Server: it can handle HTTP Requests send by clients and responds the request with an HTTP Response.

Web Application(webapp): I would refer this as webapp in this guide. Basically the project is your web
application, it is the collection of servlets.

Web Container: Also known as Servlet Container and Servlet Engine. It is a part of Web Server that interacts
with Servlets. This is the main component of Web Server that manages the life cycle of Servlets.

Life Cycle of Servlet

Servlet life cycle contains five steps:

1) Loading of Servlet

2) Creating instance of Servlet

3) Invoke init() once

4) Invoke service() repeatedly for each client request

5) Invoke destroy()

Step 1: Loading of Servlet

When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets.

Step 2: Creating instance of Servlet

Once all the Servlet classes loaded, the servlet container creates instances of each servlet class. Servlet
container creates only once instance per servlet class and all the requests to the servlet are executed on the
same servlet instance.

Step 3: Invoke init() method


Once all the servlet classes are instantiated, the init() method is invoked for each instantiated servlet. This
method initializes the servlet. There are certain init parameters that you can specify in the deployment
descriptor (web.xml) file. For example, if a servlet has value >=0 then its init() method is immediately invoked
during web container startup.

You can specify the element in web.xml file like this:

<servlet>

<servlet-name>MyServlet</servlet-name>

<servlet-class>MyServletDemo</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

Now the init() method for corresponding servlet class MyServletDemo would be invoked during web container
startup.

Note: The init() method is called only once during the life cycle of servlet.

Step 4: Invoke service() method

Each time the web server receives a request for servlet, it spawns a new thread that calls service() method. If
the servlet is GenericServlet then the request is served by the service() method itself, if the servlet is
HttpServlet then service() method receives the request and dispatches it to the correct handler method based
on the type of request.

For example if its a Get Request the service() method would dispatch the request to the doGet() method by
calling the doGet() method with request parameters. Similarly the requests like Post, Head, Put etc. are
dispatched to the corresponding handlers doPost(), doHead(), doPut() etc. by service() method of servlet.

Note: Unlike init() and destroy() that are called only once, the service() method can be called any number of
times during servlet life cycle. As long as servlet is not destroyed, for each client request the service() method
is invoked.

Out of all the 5 steps in life cycle, this is the only step that executes multiple times.

Step 5: Invoke destroy() method

When servlet container shuts down(this usually happens when we stop the web server), it unloads all the
servlets and calls destroy() method for each initialized servlets.

How Servlet Works?


1) When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets.
During this step Servlet container creates ServletContext object. ServletContext is an interface that defines
the set of methods that a servlet can use to communicate with the servlet container.

Note: There is only one ServletContext per webapp which is common to all the servlets. ServletContext has
several useful methods such as addListener(), addFilter() etc. For now I am not explaining them as I will cover
them in a separate text about ServletContext.

2) Once the servlet is loaded, the servlet container creates the instance of servlet class. For each instantiated
servlet, its init() method is invoked

3) Client (user browser) sends an Http request to web server on a certain port. Each time the web server
receives a request, the servlet container creates HttpServletRequest and HttpServletResponse objects. The
HttpServletRequest object provides the access to the request information and the HttpServletResponse object
allows us to format and change the http response before sending it to the client.

The servlet container spawns a new thread that calls service() method for each client request. The service()
method dispatches the request to the correct handler method based on the type of request.

For example if server receives a Get Request the service() method would dispatch the request to the doGet()
method by calling the doGet() method with request parameters. Similarly the requests like Post, Head, Put etc.
are dispatched to the corresponding handlers doPost(), doHead(), doPut() etc. by service() method of servlet.

4) When servlet container shuts down, it unloads all the servlets and calls destroy() method for each initialized
servlets.

JAVA BEANS

A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API
specifications.

Following are the unique characteristics that distinguish a JavaBean from other Java classes −

1. It provides a default, no-argument constructor.


2. It should be Serializable and that which can implement the Serializable interface.
3. It may have a number of properties which can be read or written.
4. It may have a number of "getter" and "setter" methods for the properties.
5. JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class
that should follow following conventions:
6. Must implement Serializable.
7. It should have a public no-arg constructor.
8. All properties in java bean must be private with public getters and setter methods.

Java Beans Properties

• A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute
can be of any Java data type, including the classes that you define.
• A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed
through two methods in the JavaBean's implementation class –

Method and Description

getPropertyName() : For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.

setPropertyName() : For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.

Java Beans Example

Consider a student class with few properties −

public class StudentsBean implements java.io.Serializable {


private String firstName = null;
private String lastName = null;
private int age = 0;
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}

Accessing Java Beans

The useBean action declares a JavaBean for use in a JSP.


Once declared, the bean becomes a scripting variable that can be accessed by both scripting
elements and other custom tags used in the JSP.
The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name among
other useBean declarations in the same JSP.
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing Java Beans Properties

Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the get
methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax −
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean
action. The property attribute is the name of the get or the set methods that should be invoked.
Following example shows how to access the data using the above syntax –
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the following
result will be displayed −
Student First Name: Zara
Student Last Name: Ali
Student Age: 10

Following steps to be adopted to create a new Bean

1. Create the Java source file.


2. Compile the source file.
3. Create a manifest file.
4. Generate a JAR file.
5. Start the BDK.
6. Test.
Step 1: Put this source code into a file named "SimpleBean.java“
import java.awt.*;
import java.io.Serializable;
public class SimpleBean extends Canvas
implements Serializable{
//Constructor sets inherited properties
public SimpleBean(){
setSize(60,40);
setBackground(Color.red);
}}
Step 2: Compile the file:
javac SimpleBean.java
Step 3: Create a manifest file, named "manifest.tmp":
Name: SimpleBean.class
Java-Bean: True
Step 4: Create the JAR file, named "SimpleBean.jar":
jar cfm SimpleBean.jar manifest.tmp SimpleBean.class
Then verify that the content is correct by the command "jar tf SimpleBean.jar".
Step 5: Start the Bean Box.
CD to c:\Program Files\BDK1.1\beanbox\.
Then type "run".
Load JAR into Bean Box by selecting "LoadJar..." under the File menu.
Step 6: After the file selection dialog box is closed, change focus to the "ToolBox" window. You'll
see"SimpleBean" appear at the bottom of the toolbox window.
Select SimpleBean.jar.
Cursor will change to a plus. In the middle BeanBox window, you can now click to drop in what will
appear to be a colored rectangle.

**What is Persistence in Java Bean?

A bean has the property of persistence when its properties, fields, and state information are saved to and
retrieved from storage. Component models provide a mechanism for persistence that enables the state of
components to be stored in a non-volatile place for later retrieval.

Why is Bean not an applet?

A bean differs from a Java applet in that it has persistence (it remains on the user's system after execution).
Additionally, beans are capable of communicating and exchanging data with other JavaBeans through inter-
process communication.

What is getter and setter in Java?

1. Getters and setters are used to protect your data, particularly when creating classes. For each
instance variable, a getter method returns its value while a setter method sets or updates its value.
2. getters and setters are also known as accessors and mutators, respectively.

Enterprise Java Beans (EJB)

1. Enterprise Java Beans (EJB) is one of the several Java APIs for standard manufacture of enterprise
software. EJB is a server-side software element that summarizes business logic of an application.
Enterprise Java Beans web repository yields a runtime domain for web related software elements
including computer reliability, Java Servlet Lifecycle (JSL) management, transaction procedure and
other web services. The EJB enumeration is a subset of the Java EE enumeration.
2. The EJB enumeration was originally developed by IBM in 1997 and later adopted by Sun
Microsystems in 1999 and enhanced under the Java Community Process.
3. The EJB enumeration aims to provide a standard way to implement the server-side business
software typically found in enterprise applications. Such machine code addresses the same types of
problems, and solutions to these problems are often repeatedly re-implemented by programmers.
Enterprise Java Beans is assumed to manage such common concerns as endurance, transactional
probity and security in a standard way that leaves programmers free to focus on the particular
parts of the enterprise software at hand.
4. To run EJB application we need an application server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc.

It Performs :

1. Life Cycle Management


2. Security
3. Transaction Management
4. Object Pooling

Types of Enterprise Java Beans

There are three types of EJB:

1. Session Bean: Session bean contains business logic that can be invoked by local, remote or webservice
client. There are two types of session beans: (i) Stateful session bean and (ii) Stateless session bean.

(i) Stateful Session bean :

Stateful session bean performs business task with the help of a state. Stateful session bean can be
used to access various method calls by storing the information in an instance variable. Some of the
applications require information to be stored across separate method calls. In a shopping site, the
items chosen by a customer must be stored as data is an example of stateful session bean.

(ii) Stateless Session bean :

Stateless session bean implement business logic without having a persistent storage mechanism,
such as a state or database and can used shared data. Stateless session bean can be used in
situations where information is not required to used across call methods.

2. Message Driven Bean: Like Session Bean, it contains the business logic but it is invoked by passing message.

3. Entity Bean: It summarizes the state that can be remained in the database. It is deprecated. Now, it is
replaced with JPA (Java Persistent API). There are two types of entity bean:

(i) Bean Managed Persistence : In a bean managed persistence type of entity bean, the programmer
has to write the code for database calls. It persists across multiple sessions and multiple clients.

(ii) Container Managed Persistence : Container managed persistence are enterprise bean that persists
across database. In container managed persistence the container take care of database calls.

When to use Enterprise Java Beans

1. 1.Application needs Remote Access. In other words, it is distributed.


2. 2.Application needs to be scalable. EJB applications supports load balancing, clustering and fail-over.
3. 3.Application needs encapsulated business logic. EJB application is differentiated from demonstration
and persistent layer.
Advantages of Enterprise Java Beans

1. EJB repository yields system-level services to enterprise beans, the bean developer can focus on
solving business problems. Rather than the bean developer, the EJB repository is responsible for
system-level services such as transaction management and security authorization.
2. The beans rather than the clients contain the application’s business logic, the client developer can
focus on the presentation of the client. The client developer does not have to code the pattern that
execute business rules or access databases. Due to this the clients are thinner which is a benefit
that is particularly important for clients that run on small devices.
3. Enterprise Java Beans are portable elements, the application assembler can build new applications
from the beans that already exists.

Disadvantages of Enterprise Java Beans

1. Requires application server


2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop EJB applications.

Difference between Java Beans and EJB

Session vs. Cookies| Difference between Session and Cookies

The Session and cookies are used by different websites for storing user's data across different pages of the
site. Both session and cookies are important as they keep track of the information provided by a visitor for
different purposes. The main difference between both of them is that sessions are saved on the server-side,
whereas cookies are saved on the user's browser or client-side. Apart from this, there are also various other
differences between both.

What is a Session?

o A session is used to temporarily store the information on the server to be used across multiple pages
of the website. It is the total time used for an activity. The user session starts when he logs-in to a
particular network application and ends when the user logs out from the application or shutdowns the
system.
o When we work on an application over the internet, the webserver doesn't know the user because the
HTTP protocol does not maintain the state. The information provided by the user on one page of the
application (Let's say Home) will not be transferred to another page. To remove this limitation, sessions
are used. Session gets started whenever a visitor first enters a website.
o The user information is stored in session variables, and these variables can store any type of value or
data type of an Object.
o Session values are much secured as these are stored in binary form or encrypted form and can only be
decrypted at the server. The session values are automatically removed when the user shutdowns the
system or logout from the application. To store the values permanently, we need to store them in the
database.
o Each session is unique for each user, and any number of sessions can be used in an application; there is
no limitation to it.
o The user is identified with the help of sessionID, which is a unique number saved inside the server. It is
saved as a cookie, form field, or URL.
Working of Session

The working of a session can be understood with the help of the below diagram:

1. In the first step, the client request to the server via GET or POST method.
2. The sessionID is created on the server, and it saves the sessionID into the database. It returns the
sessionId with a cookie as a response to the client.
3. Cookie with sessionID stored on the browser is sent back to the server. The server matches this id with
the saved sessionID and sends a response HTTP200
Why Use Session?

o Sessions are used to store information such as UserID over the server more securely, where it cannot
be tempered.
o It can also transfer the information in the form of value from one web page to another.
o It can be used as an alternative to cookies for browsers that don't support cookies to store variables in
a more secure way.
What is Cookie?
o A cookie is a small text file that is stored on the user's computer. The maximum file size of a cookie
is 4KB. It is also known as an HTTP cookie, web cookie, or internet Cookie. Whenever a user visits a
website for the first time, the site sends packets of data in the form of a cookie to the user's computer.
o The cookies help the websites to keep track of the user's browsing history or cart information when
they visit their sites.
o It stores only the "String" data type.
o The information stored within cookies is not secure because this information is stored in text-format
on the client-side, which can be read by anyone.
o We can enable or disable the cookies as per the requirement.
o The cookies generated by a user are only be shown to them, and no other user can see those cookies.
o Cookies are created and shared between the server and browser with the help of an HTTP header.
o The path where the cookies are saved is decided by the browser, as Internet explorer usually stored
them in Temporal Internet File Folder.
o When we visit YouTube channel and search for some songs, next time whenever we visit YouTube,
cookies read our browsing history and shows similar songs or last played songs.
Creating Cookies

To create a cookie, we need to use the setcookie() function, and it must appear before the <html> tag. The
syntax of this function is given below:

Syntax:

1. setcookie(name, value, expire, path, domain, secure, httponly);  
2. In the above syntax, only a name argument is required, and others are optional.   
Example:

setcookie("Userid", "1005", "time()+3600");

Cookies Attribute:

o Name: It defines the name of the cookie.


o Value: It defines the value of the cookie.
o Expire: It specifies the time when the cookie will expire. If it is not used or set as 0, cookies will be
deleted at the end of the session.
o Path: It defines the server path of the cookie. If it is set to "/", the cookie will be available within the
complete domain.
o Domain: It defines the domain name of the cookies. If we set it "javatpoint.com", it will be available for
all subdomains of javatpoint.com.
o Secure: It specifies that if the cookies are only transmitted over HTTPS or not. If it is set True, it means
cookies will only be set for the secured connection.
o HTTPOnly: If it is set to TRUE, the cookies will be accessible through the HTTP protocol.
Why use Cookies?

HTTP is a stateless protocol; hence it does not store any user information. For this purpose, we can use
Cookies. It allows us to store the information on the user's computer and track the state of applications.

Key Differences between Session and Cookies

o Sessions are server-side files that store the user information, whereas Cookies are client-side files that
contain user information on a local computer.
o Sessions are cookies dependent, whereas Cookies are not dependent on Session.
o The session ends when the user closes the browser or logout from the application, whereas Cookies
expire at the set time.
o A session can store as much data as a user want, whereas Cookies have a limited size of 4KB.
Difference table between Cookies and Session

Session Cookies

A session stores the variables and their values Cookies are stored on the user's computer as a text file.
within a file in a temporary directory on the server.

The session ends when the user logout from the Cookies end on the lifetime set by the user.
application or closes his web browser.

It can store an unlimited amount of data. It can store only limited data.

We can store as much data as we want within a The maximum size of the browser's cookies is 4 KB.
session, but there is a maximum memory limit,
which a script can use at one time, and it is 128 MB.

We need to call the session_start() function to start We don't need to call a function to start a cookie as it is
the session. stored within the local computer.

Sessions are more secured compared to cookies, as Cookies are not secure, as data is stored in a text file, and
they save data in encrypted form. if any unauthorized user gets access to our system, he
can temper the data.

Conclusion

From the above discussion, we can have a better understanding of cookies and sessions and the differences
between them. Hence, we can conclude that session is a way to temporarily store the user information on the
server-side, whereas cookies store the information on the user's computer until it expires.

Servlet – Login and Logout Example using Cookies


Cookies are a piece of textual information that is stored in key-value pair format in the client’s browser during
multiple requests.

Why do we use cookies?

We use Cookies as one of the techniques of Session Tracking / State Management.

Session Tracking is a way to maintain state (data) of a user. It is also known as State Management.

We use session tracking because HTTP is a stateless protocol. In stateless, the server treats each request as
a new request because it will not remember that the requests are being sent by the same client.

Hence, using cookies we can create a login/logout module and the server can store our data.

Working of a Cookie

The client sends a request “req1” to the server. After processing the request “req1”, the server sends
“response+cookies”.

These cookies are saved on the client’s browser.

Now, if the client sends another request “req2+cookies” to the server, then first the server will check the
cookie and it will know that this is an already logged-in user and will not treat this request “req2+cookies” as a
new request. Then further processing will be done by the server.

That’s how a state will be established.

How to use cookies in java?

To create cookies, use the Cookies class in javax.servlet.http package.

To make a cookie, create an object of the cookie class and pass a name-value pair.

How to attach a cookie to a response?

To attach a cookie to a response, use addCookie(cookie) method of response interface.

How to fetch a cookie when a client sends another request (i.e., req2+cookie) ?

Cookie will come through a request so we will take help from the request object.

request.getCookies() method will return an array of cookies.

getName() and getValue() methods of Cookie class are used to fetch the key and its corresponding value from
the array of cookies.

If no cookies are found, then it will return null means the client is a new user and the request is also new.

How to delete a cookie?

A cookie is deleted to log out the user.

In the key-value pair, pass an empty string.

Also, use setMaxAge() method of Cookie class to indicate after how long the cookie should expire.
Note: To run the following programs, the author created a Dynamic Web Project in Eclipse IDE and executed
it using Apache Tomcat Server v9.0.

Example: Login and Logout module using Cookies

A. File: index.html

This page includes links to three other pages for navigation – login page, logout servlet and profile servlet.

Click on login.html and enter username and password (i.e., gfg). From the login page, you will be redirected
to GFGLoginServlet.java

Example:

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>GFG</title>

</head>

<body>

<p>

<a href="login.html" style="font-size:25px;">Login |</a>

<a href="GFGLogoutServlet" style="font-size:25px;"> Logout |</a>

<a href="GFGProfileServlet" style="font-size:25px;"> Profile </a>

</p>

</body>

</html>

Output: index.html is as follows:

B. File: link.html

link.html is the same as index.html because we will include link.html page’s content using
RequestDispatcher in GFGLoginServlet.java and GFGLogoutServlet.java

Example:

<!DOCTYPE html>

<html>

<head>
<meta charset="ISO-8859-1">

<title>GFG</title>

</head>

<body>

<p>

<a href="login.html" style="font-size:25px;">Login |</a>

<a href="GFGLogoutServlet" style="font-size:25px;"> Logout |</a>

<a href="GFGProfileServlet" style="font-size:25px;"> Profile </a>

</p>

</body>

</html>

C. File: login.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>GFG</title>

</head>

<body>

<form action="GFGLoginServlet">

<pre>

User name: <input type="text" name="user_name" placeholder="Enter your name">

Password: <input type="password" name="password" placeholder="Enter password">

<button type="submit" value="login">Login</button>

</pre>

</form>

</body>

</html>
Case: GFGLoginServlet.java

Here, the password will be checked.

If the password is correct (i.e., gfg), then cookie will be created.

Else contents of login.html will be displayed asking the user to login again as the password was incorrect.

Content of link.html will be displayed at the top in either case.

// Java Program to Illustrate Login in Servlets

// Importing required classes

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

// Annotation

@WebServlet("/GFGLoginServlet")

// Class

// Extending HttpServlet class

public class GFGLoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

PrintWriter out = response.getWriter();

request.getRequestDispatcher("link.html")
.include(reqest, response); // This statement includes

// link.html in this servlet

String name = request.getParameter("user_name");

String password = request.getParameter("password");

if (password.equals("gfg")) {

out.println(

"<h1>Welcome " + name

+ ", you have successfully logged in!</h1>");

// creating cookie

Cookie c = new Cookie("username", name);

// attaching cookie to response object

response.addCookie(c);

else {

out.println(

"Sorry invalid username or password!");

request.getRequestDispatcher("login.html")

.include(request, response);

// Above statement includes login.html for the

// user to re-login if username or password is

// invalid.

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException


{

// TODO Auto-generated method stub

doGet(request, response);

Output: GFGLoginServlet.java is as follows:

GFGLoginServlet.java

GFGProfileServlet.java

Here, accessing the profile page means actually sending another request to the user (i.e., req2+cookie).

If the cookie does not exist (i.e., null), then contents of login.html will be displayed asking the user to login.

Else cookie will be fetched using getName() function and the required cookie name (i.e., username) will be
matched. Upon finding the cookie name, cookie value will be fetched using getValue() function.

Contents of link.html will not be displayed on this page.

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/GFGProfileServlet")

public class GFGProfileServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

{
PrintWriter out = response.getWriter();

String name = "";

// request object will return an array of cookies

Cookie[] cookies = request.getCookies();

if (cookies == null) {

out.println(

"<h1> You are a new user, kindly login. </h1>");

request.getRequestDispatcher("login.html")

.include(request, response);

// Above statement includes login.html for the

// user to re-login if username or password is

// invalid.

else {

for (Cookie c : cookies) {

String tempName

= c.getName(); // For every cookie, add

// cookie name to the

// tempName.

if (tempName.equals("username"))

// If tempName and username (that we had set

// in the cookie c in GFGLoginServlet) are

// same, then this is an already logged in

// user and the request is not from a new

// user. So let the user access profile page.


{

name = c.getValue(); // From the (name,

// value) pair of

// cookie, fetch

// value

out.println(

"<a href='GFGLogoutServlet' style='font-size:25px;'>Logout </a>");

out.println(

"<h1>Welcome to your profile, "

+ name);

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

// TODO Auto-generated method stub

doGet(request, response);

GFGProfileServlet.java

Case: GFGLogoutServlet.java

Here, the cookie will be deleted in order to end the session.

Along with cookie name (i.e., username), null value will be passed.
Inside setMaxAge() function, we will set the expiration date of the cookie, to specify after how long the
cookie will expire.

Using response.addCookie() function, we will attach this cookie with the response to send it to the client’s
browser.

Example

// Java Program to Illustrate Logout in Servlets

// Importing required classes

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

// Annotation

@WebServlet("/GFGLogoutServlet")

// Class

// Extending HttpServlet class

public class GFGLogoutServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

PrintWriter out = response.getWriter();

request.getRequestDispatcher("link.html")

.include(request,
response); // This statement includes

// link.html in this servlet

// cookie with blank value is used to delete

// a cookie to sign out the user

Cookie c = new Cookie("username", "");

// setMaxAge will set the expiration of cookie.

// This cookie will expire in 0seconds

c.setMaxAge(0);

// Attach cookie to response

response.addCookie(c);

out.println("<h1>You have logged out!</h1>");

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

// TODO Auto-generated method stub

doGet(request, response);

Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a
maximum age, and a version number.

How Cookie works

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

Types of Cookie

There are 2 types of cookies in servlets.

Non-persistent cookie

Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser..

Persistent cookie

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

Advantage of Cookies

 Simplest technique of maintaining the state.


 Cookies are maintained at client side.
Disadvantage of Cookies

 It will not work if cookie is disabled from the browser.


 Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods
for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.
Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces.
They are:

public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response
object.

public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the
browser.

How to create Cookie?

Let's see the simple code to create cookie.

Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object

response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie

ck.setMaxAge(0);//changing the maximum age to 0 seconds


response.addCookie(ck);//adding cookie in the response

How to get Cookies?

Let's see the simple code to get all the cookies.

Cookie ck[]=request.getCookies();

for(int i=0;i<ck.length;i++){

out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie

Simple example of Servlet Cookies

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

cookies in session tracking

index.html

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

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

FirstServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();


String n=request.getParameter("userName");

out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object

response.addCookie(ck);//adding cookie in the response

//creating submit button

out.print("<form action='servlet2'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

out.close();

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

SecondServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();

out.print("Hello "+ck[0].getValue());

out.close();

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

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>FirstServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>
****Servlet Login and Logout Example using Cookies

A cookie is a kind of information that is stored at client side.

Here, we are going to create a login and logout example using servlet cookies.
In this example, we are creating 3 links: login, logout and profile. User can't go to profile page until he/she is
logged in. If user is logged out, he need to login again to visit profile.

In this application, we have created following files.

index.html

link.html

login.html

LoginServlet.java

LogoutServlet.java

ProfileServlet.java

web.xml

File: index.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Servlet Login Example</title>

</head>

<body>

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

<a href="login.html">Login</a>|

<a href="LogoutServlet">Logout</a>|

<a href="ProfileServlet">Profile</a>

</body>

</html>

File: link.html

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

<a href="ProfileServlet">Profile</a>

<hr>

File: login.html

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

Name:<input type="text" name="name"><br>

Password:<input type="password" name="password"><br>

<input type="submit" value="login">

</form>

File: LoginServlet.java

package com.javatpoint;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();

request.getRequestDispatcher("link.html").include(request, response);

String name=request.getParameter("name");

String password=request.getParameter("password");
if(password.equals("admin123")){

out.print("You are successfully logged in!");

out.print("<br>Welcome, "+name);

Cookie ck=new Cookie("name",name);

response.addCookie(ck);

}else{

out.print("sorry, username or password error!");

request.getRequestDispatcher("login.html").include(request, response);

out.close();

File: LogoutServlet.java

package com.javatpoint;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LogoutServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();

request.getRequestDispatcher("link.html").include(request, response);

Cookie ck=new Cookie("name","");

ck.setMaxAge(0);

response.addCookie(ck);

out.print("you are successfully logged out!");

File: ProfileServlet.java

package com.javatpoint;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class ProfileServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);

Cookie ck[]=request.getCookies();

if(ck!=null){

String name=ck[0].getValue();

if(!name.equals("")||name!=null){

out.print("<b>Welcome to Profile</b>");

out.print("<br>Welcome, "+name);

}else{

out.print("Please login first");

request.getRequestDispatcher("login.html").include(request, response);

out.close();

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet>

<description></description>

<display-name>LoginServlet</display-name>

<servlet-name>LoginServlet</servlet-name>

<servlet-class>com.javatpoint.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>

<servlet-name>LoginServlet</servlet-name>

<url-pattern>/LoginServlet</url-pattern>

</servlet-mapping>

<servlet>

<description></description>

<display-name>ProfileServlet</display-name>

<servlet-name>ProfileServlet</servlet-name>

<servlet-class>com.javatpoint.ProfileServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ProfileServlet</servlet-name>

<url-pattern>/ProfileServlet</url-pattern>

</servlet-mapping>

<servlet>

<description></description>

<display-name>LogoutServlet</display-name>

<servlet-name>LogoutServlet</servlet-name>

<servlet-class>com.javatpoint.LogoutServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LogoutServlet</servlet-name>

<url-pattern>/LogoutServlet</url-pattern>

</servlet-mapping>

</web-app>
CEATING SMILIY

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Smiley extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.YELLOW);
        g.fillOval(10, 10, 200, 200); // draw Eyes
        g.setColor(Color.BLACK);
        g.fillOval(55, 65, 30, 30);
        g.fillOval(135, 65, 30, 30); // draw Mouth
        g.fillOval(50, 110, 120, 60);  // adding smile
        g.setColor(Color.YELLOW);
        g.fillRect(50, 110, 120, 30);
        g.fillOval(50, 120, 120, 40);
    }
    public static void main(String[] args) {
        Smiley smily = new Smiley();
        JFrame app = new JFrame();
        app.add(smily);
        app.setSize(300, 300);
        app.setVisible(true);
    }
}

question 2 : create rectangle and oval in java.

DrawShapes.java
package com.onlinetutorialspoint.swing;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class DrawShapes extends JPanel {
    private int input;
    public DrawShapes(int choice) {
        input = choice;
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < 10; i++) {
            switch (input) {
            case 1:
                g.drawRect(10+i*10, 10+i*10, 50+i*10, 50+i*10);
                break;
            case 2:
                g.drawOval(10+i*10, 10+i*10, 50+i*10, 50+i*10);
                break;
            }
        }
    }
    public static void main(String[] args) {
        String choice = JOptionPane.showInputDialog("Enter 1 to draw rectangles \n"+"Enter 2 to draw
Ovals");
        DrawShapes shapes = new DrawShapes(Integer.parseInt(choice));
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(shapes);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

THREADING
class RunnableDemo implements Runnable {
    private Thread t;
    private String threadName;
    RunnableDemo( String name) {
       threadName = name;
       System.out.println("Creating " +  threadName );
    }
    public void run() {
       System.out.println("Running " +  threadName );
       try {
          for(int i = 4; i > 0; i--) {
             System.out.println("Thread: " + threadName + ", " + i);
             Thread.sleep(50);
          }
       } catch (InterruptedException e) {
          System.out.println("Thread " +  threadName + " interrupted.");
       }
       System.out.println("Thread " +  threadName + " exiting.");
    }
    public void start () {
       System.out.println("Starting " +  threadName );
       if (t == null) {
          t = new Thread (this, threadName);
          t.start ();
       }
    }
 }
 public class TestThread {
    public static void main(String args[]) {
       RunnableDemo R1 = new RunnableDemo( "Thread-1");
       R1.start();
       RunnableDemo R2 = new RunnableDemo( "Thread-2");
       R2.start();
    }  
 }

You might also like