0% found this document useful (0 votes)
11 views86 pages

AOT Unit-1 - Merged

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 86

ADVANCE OBJECT TECHNOLOGY

UNIT-1
• Introduction to Javascript-
JavaScript is a lightweight, cross-platform, and interpreted compiled
programming language which is also known as the scripting language for
webpages. It is well-known for the development of web pages, many non-
browser environments also use it. JavaScript can be used for Client-
side developments as well as Server-side developments. Javascript is both
imperative and declarative type of language .JavaScript contains a standard
library of objects, like Array, Date, and Math, and a core set of language
elements like operators, control structures, and statements.

• Client-side: It supplies objects to control a browser and its Document


Object Model (DOM). Like if client-side extensions allow an application
to place elements on an HTML form and respond to user events such
as mouse clicks, form input, and page navigation. Useful libraries for the
client-side are AngularJS, ReactJS, VueJS and so many others.
• Server-side: It supplies objects relevant to running JavaScript on a
server. Like if the server-side extensions allow an application to
communicate with a database, and provide continuity of information
from one invocation to another of the application, or perform file
manipulations on a server. The useful framework which is the most
famous these days is node.js.
• Imperative language – In this type of language we are mostly concern
about how it is to be done . It simply control the flow of computation .
The procedural programming approach , object, oriented approach
comes under this like async await we are thinking what it is to be done
further after async call.
• Declarative programming – In this type of language we are concern
about how it is to be done , basically here logical computation require .
Here main goal is to describe the desired result without direct dictation
on how to get it like arrow function do .
JavaScript can be added to your HTML file in two ways:
• Internal JS: We can add JavaScript directly to our HTML file by writing
the code inside the <script> tag. The <script> tag can either be placed
inside the <head> or the <body> tag according to the requirement.
Syntax:
<script>
// JavaScript Code
</script>
• External JS: We can write JavaScript code in other file having an
extension.js and then link this file inside the <head> tag of the HTML file
in which we want to add this code.
Syntax:
<script src="myScript.js"></script>
Applications of JavaScript:
• Web Development: Adding interactivity and behavior to static sites
JavaScript was invented to do this in 1995. By using AngularJS that can
be achieved so easily.
• Web Applications: With technology, browsers have improved to the
extent that a language was required to create robust web applications.
When we explore a map in Google Maps then we only need to click and
drag the mouse. All detailed view is just a click away, and this is possible
only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code. The Electron and
React is helpful in this department.
• Server Applications: With the help of Node.js, JavaScript made its way
from client to server and node.js is the most powerful on the server-
side.
• Games: Not only in websites, but JavaScript also helps in creating games
for leisure. The combination of JavaScript and HTML 5 makes JavaScript
popular in game development as well. It provides the EaseJS library
which provides solutions for working with rich graphics.
• Smartwatches: JavaScript is being used in all possible devices and
applications. It provides a library PebbleJS which is used in smartwatch
applications. This framework works for applications that require the
internet for its functioning.
• Art: Artists and designers can create whatever they want using
JavaScript to draw on HTML 5 canvas, and make the sound more
effective also can be used p5.js library.

• Objects in Javascript-
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc. JavaScript is an object-
based language. Everything is an object in JavaScript. JavaScript is template based not
class based. Here, we don't create class to get the object. But, we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal


The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

Example:

emp={id:102,name:"Shyam Kumar",salary:40000}

2) By creating instance of Object


The syntax of creating object directly is given below:

var objectname=new Object();


Example:

var emp=new Object();


emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;

3) By using an Object constructor


Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.

Example:

function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

• Dynamic HTML with Java Script-


• Dynamic HTML is a set of technologies that allows dynamic changes to HTML
documents.
• An embedded script can be used to change tag attributes, contents or element style
properties.

What can you do with Dynamic HTML?


• Elements can be moved to new positions on the display.
• Elements can be made to appear and disappear.
• Foreground (text) and background colors can be changed.
• The font, font size and font style an be changed.
• Element content can be changed.
• The stacking order of overlapping elements (such as pictures) can be changed.
• The mouse cursor position can be changed.
• Text can be made to move across the display.

Following are the various examples, which describes how to use the JavaScript
technology with the DHTML(Dynamic HTML):
Document.write() Method

The document.write() method of JavaScript, writes the output to a web page.

Example 1: The following example simply uses the document.write() method of


JavaScript in the DHTML. In this example, we type the JavaScript code in
the <body> tag.

<HTML>
<head>
<title>
Method of a JavaScript
</title>
</head>
<body>
<script type="text/javascript">
document.write("JavaTpoint");
</script>
</body>
</html>

Output:

JavaScript and HTML event

A JavaScript code can also be executed when some event occurs. Suppose, a user clicks
an HTML element on a webpage, and after clicking, the JavaScript function associated
with that HTML element is automatically invoked. And, then the statements in the
function are performed.

Example 1: The following example shows the current date and time with the JavaScript
and HTML event (Onclick). In this example, we type the JavaScript code in the <head>
tag.

<html>
<head>
<title>
DHTML with JavaScript
</title>
<script type="text/javascript">
function dateandtime()
{
alert(Date());
}
</script>
</head>
Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
</p> </center>
</body>
</html>

Output:

• XML

XML stands for Extensible Markup Language. It is a text-based markup language


derived from Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than
specifying how to display it like HTML tags, which are used to display the data. XML
is not going to replace HTML in the near future, but it introduces new possibilities by
adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of
systems and solutions −
• XML is extensible − XML allows you to create your own self-descriptive
tags, or language, that suits your application.
• XML carries the data, does not present it − XML allows you to store
the data irrespective of how it will be presented.
• XML is a public standard − XML was developed by an organization
called the World Wide Web Consortium (W3C) and is available as an
open standard.

XML Usage
A short list of XML usage says it all −
• XML can work behind the scene to simplify the creation of HTML
documents for large web sites.
• XML can be used to exchange the information between organizations
and systems.
• XML can be used for offloading and reloading of databases.
• XML can be used to store and arrange the data, which can customize
your data handling needs.
• XML can easily be merged with style sheets to create almost any
desired output.
• Virtually, any type of data can be expressed as an XML document
.
• Document Type Definition – DTD
A Document Type Definition (DTD) describes the tree structure of a document
and something about its data. It is a set of markup affirmations that actually
define a type of document for the SGML family, like GML, SGML, HTML, XML.

A DTD can be declared inside an XML document as inline or as an external


recommendation. DTD determines how many times a node should appear, and
how their child nodes are ordered.

There are 2 data types, PCDATA and CDATA


o PCDATA is parsed character data.
o CDATA is character data, not usually parsed.

• Example

DTD for the above tree is:


<?xml version="1.0"?>
<!DOCTYPE address [
<!ELEMENT address (name, email, phone, birthday)>
<!ELEMENT name (first, last)>
<!ELEMENT first (#PCDATA)>
<!ELEMENT last (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT birthday (year, month, day)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT month (#PCDATA)>
<!ELEMENT day (#PCDATA)>
]>

<address>
<name>
<first>Rohit</first>
<last>Sharma</last>
</name>
<email>sharmarohit@gmail.com</email>
<phone>9876543210</phone>
<birthday>
<year>1987</year>
<month>June</month>
<day>23</day>
</birthday>
</address>
The DTD above is interpreted like this:

o !DOCTYPE address defines that the root element of this document is address.
o !ELEMENT address defines that the address element must contain four
elements: “name, email, phone, birthday”.
o !ELEMENT name defines that the name element must contain two elements:
“first, last”.
o !ELEMENT first defines the first element to be of type “#PCDATA”.
o !ELEMENT last defines the last element to be of type “#PCDATA”.
o !ELEMENT email defines the email element to be of type “#PCDATA”.
o !ELEMENT phone defines the phone element to be of type “#PCDATA”.
o !ELEMENT birthday defines that the birthday element must contain three
elements “year, month, day”.
o !ELEMENT year defines the year element to be of type “#PCDATA”.
o !ELEMENT month defines the month element to be of type “#PCDATA”.
o !ELEMENT day defines the day element to be of type “#PCDATA”.

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

The purpose of an XML Schema is to define the legal building blocks of an


XML document:

• the elements and attributes that can appear in a document


• the number of (and order of) child elements
• data types for elements and attributes
• default and fixed values for elements and attributes

Why Learn XML Schema?


In the XML world, hundreds of standardized XML formats are in daily use.
Many of these XML standards are defined by XML Schemas.
XML Schema is an XML-based (and more powerful) alternative to DTD.

XSD Example
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

• Document Object Model (DOM)


The Document Object Model (DOM) is a programming API for HTML and XML documents. It
defines the logical structure of documents and the way a document is accessed and
manipulated.
With the Document Object Model, programmers can create and build documents, navigate
their structure, and add, modify, or delete elements and content. Anything found in an HTML
or XML document can be accessed, changed, deleted, or added using the Document Object
Model,
The Document Object Model is a programming API for documents. The object model itself
closely resembles the structure of the documents it models. For instance, consider this table,
taken from an HTML document:
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>

The Document Object Model represents this table like this:


The XML DOM
All XML elements can be accessed through the XML DOM.

The XML DOM is:

• A standard object model for XML


• A standard programming interface for XML
• Platform- and language-independent

In other words: The XML DOM is a standard for how to get, change,
add, or delete XML elements.

Get the Value of an XML Element

This code retrieves the text value of the first <title> element in an XML
document:

Example
txt = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

Example Explained

• xmlDoc - the XML DOM object created by the parser.


• getElementsByTagName("title")[0] - get the first <title> element
• childNodes[0] - the first child of the <title> element (the text node)
• nodeValue - the value of the node (the text itself)

XML DOM Properties

These are some typical DOM properties:

• x.nodeName - the name of x


• x.nodeValue - the value of x
• x.parentNode - the parent node of x
• x.childNodes - the child nodes of x
• x.attributes - the attributes nodes of x

Note: In the list above, x is a node object.

XML DOM Methods


• x.getElementsByTagName(name) - get all elements with a specified
tag name
• x.appendChild(node) - insert a child node to x
• x.removeChild(node) - remove a child node from x

The HTML DOM


When a web page is loaded, the browser creates a Document Object Model
of the page. The HTML DOM model is constructed as a tree of Objects:

Finding HTML Elements


When you want to access HTML elements with JavaScript, you have to find
the elements first.

There are a couple of ways to do this:

• Finding HTML elements by id


• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the
element id.

This example finds the element with id="intro":

Example
var myElement = document.getElementById("intro");
Finding HTML Elements by Tag Name

This example finds all <p> elements:

Example
var x = document.getElementsByTagName("p");

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name, use
getElementsByClassName().

This example returns a list of all elements with class="intro".

Example
var x = document.getElementsByClassName("intro");

Finding HTML Elements by CSS Selectors

If you want to find all HTML elements that matches a specified CSS selector (id,
class names, types, attributes, values of attributes, etc), use the
querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".

Example
var x = document.querySelectorAll("p.intro");

• Review of Applets
APPLET
Applets are small applications that are accessed on an Internet server,
transported over the Internet, automatically installed, and run as part of a
Web document. After an applet arrives on the client, it has limited access
to resources, so that it can produce an arbitrary multimedia user interface
and run complex computations without introducing the risk of viruses or
breaching data integrity.

Let’s begin with the simple applet shown here:


import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
This applet begins with two import statements. The first imports the
Abstract Window Toolkit (AWT) classes. Applets interact with the user
through the AWT, not through the console-based I/O classes. The AWT
contains support for a window-based, graphical interface.

The second import statement imports the applet package, which contains
the class Applet. Every applet that you create must be a subclass of
Applet.

The next line in the program declares the class SimpleApplet. This class
must be declared as public, because it will be accessed by code that is
outside the program.
Inside SimpleApplet, paint( ) is declared. This method is defined by the
AWT and must be overridden by the applet. paint( ) is called each time
that the applet must redisplay its output.

Life cycle of an applet :

It is important to understand the order in which the various methods shown in


the above image are called. When an applet begins, the following methods are
called, in this sequence:

oinit( )
ostart( )
opaint( )
When an applet is terminated, the following sequence of method calls takes
place:

o stop( )
o destroy( )
o
Let’s look more closely at these methods.

1. init( ) : The init( ) method is the first method to be called. This is where you
should initialize variables. This method is called only once during the run time of
your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart
an applet after it has been stopped. Note that init( ) is called once i.e. when the
first time an applet is loaded whereas start( ) is called each time an applet’s
HTML document is displayed onscreen. So, if a user leaves a web page and
comes back, the applet resumes execution at start( ).

3. paint( ) : The paint( ) method is called each time an AWT-based applet’s


output must be redrawn. This situation can occur for several reasons. For
example, the window in which the applet is running may be overwritten by
another window and then uncovered. Or the applet window may be minimized
and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will
contain the graphics context, which describes the graphics environment in which
the applet is running. This context is used whenever output to the applet is
required.

4. stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example.
When stop( ) is called, the applet is probably running. You should use stop( ) to
suspend threads that don’t need to run when the applet is not visible. You can
restart them when start( ) is called if the user returns to the page.

5. destroy( ) : The destroy( ) method is called when the environment determines


that your applet needs to be removed completely from memory. At this point,
you should free up any resources the applet may be using. The stop( ) method is
always called before destroy( ).

Running the HelloWorld Applet :


There are two standard ways in which you can run an applet :

Executing the applet within a Java-compatible web browser.


Using an applet viewer, such as the standard tool, applet-viewer. An applet
viewer executes your applet in a window. This is generally the fastest and
easiest way to test your applet.
Each of these methods is described next.

1. Using java enabled web browser : To execute an applet in a web browser we


have to write a short HTML text file that contains a tag that loads the applet. We
can use APPLET or OBJECT tag for this purpose. Using APPLET, here is the HTML
file that executes HelloWorld :

<applet code="HelloWorld" width=200 height=60>


</applet>

The width and height statements specify the dimensions of the display area used
by the applet. The APPLET tag contains several other options. After you create
this html file, you can use it to execute the applet.
2. Using appletviewer : This is the easiest way to run an applet. To execute
HelloWorld with an applet viewer, you may also execute the HTML file shown
earlier. For example, if the preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :

appletviewer RunHelloWorld.html

Features of Applets over HTML

• Displaying dynamic web pages of a web application.


• Playing sound files.
• Displaying documents
• Playing animations

Java Applet Class

The Applet class provides a standard interface between applets and their
environment. The Applet class is the superclass of an applet that is embedded in
a Web page or viewed by the Java Applet Viewer. The Java applet class gives
several useful methods to give you complete control over the running of an
Applet. Like initializing and destroying an applet, It also provides ways that load
and display Web Colourful images and methods that load and play audio and
Videos Clips and Cinematic Videos.

Advantages of Applet
• It runs inside the browser and works on the Client-side, so it takes less
time to respond.
• It is more Secured
• It can be Executed By multi-platforms with any Browsers, i.e., Windows,
Mac Os, Linux Os.
Disadvantages of Applet
• A plugin is required at the client browser(User Side) to execute an Applet.

• Event Handling
An event can be defined as changing the state of an object or behavior by
performing actions. Actions can be a button click, cursor movement, keypress
through keyboard or page scrolling, etc.

The java.awt.event package can be used to provide various event classes.

Classification of Events
• Foreground Events
• Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate,
i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI). Interactions are nothing but
clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.

Event Handling
It is a mechanism to control the events and to decide what should happen
after an event occur. To handle the events, Java follows the Delegation Event
model.
Delegation Event model
• It has Sources and Listeners.

• Source: Events are generated from the source. There are various sources
like buttons, checkboxes, list, menu-item, choice, scrollbar, text
components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible
for handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.

Listener Interface Methods

ActionListener
• actionPerformed()

AdjustmentListener
• adjustmentValueChanged()

• componentResized()
• componentShown()
• componentMoved()
ComponentListener
• componentHidden()

• componentAdded()
ContainerListener
• componentRemoved()

• focusGained()
FocusListener
• focusLost()

ItemListener
• itemStateChanged()

• keyTyped()
• keyPressed()
KeyListener
• keyReleased()

• mousePressed()
• mouseClicked()
• mouseEntered()
• mouseExited()
MouseListener
• mouseReleased()

• mouseMoved()
MouseMotionListener
• mouseDragged()

MouseWheelListener
• mouseWheelMoved()

TextListener
• textChanged()
Listener Interface Methods

• windowActivated()
• windowDeactivated()
• windowOpened()
• windowClosed()
• windowClosing()
• windowIconified()
WindowListener
• windowDeiconified()

• AWT Programming
• Java AWT (Abstract Window Toolkit) is an API to develop Graphical User
Interface (GUI) or windows-based applications in Java.
• Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
• The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• The AWT tutorial will help the user to understand Java GUI programming in
simple and easy steps.

Why AWT is platform independent?


Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix.
The reason for this is the platforms have different view for their native components
and AWT directly calls the native subroutine that creates those components.

In simple words, an AWT application will look like a windows application in Windows
OS whereas it will look like a Mac application in the MAC OS.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order
to place every component in a particular position on a screen, we need to add them
to a container.

Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are known
as container such as Frame, Dialog and Panel.

Types of containers:

There are four types of containers in Java AWT:


1. Window
2. Panel
3. Frame
4. Dialog

Window

The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window. We need to create an instance of
Window class to create this container.

Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we can
add components.

Frame

The Frame is the container that contain title bar and border and can have menu bars.
It can have other components like button, text field, scrollbar etc. Frame is most widely
used container while developing an AWT application.

Useful Methods of Component Class

Method Description

public void add(Component Inserts a component on


c) this component.

public void setSize(int Sets the size (width and


width,int height) height) of the
component.

public void Defines the layout


setLayout(LayoutManager m) manager for the
component.

public void setVisible(boolean Changes the visibility of


status) the component, by
default false.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to create a GUI
using Frame in AWT.

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.

AWTExample1.java

// importing Java AWT class


import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {
// initializing using constructor
AWTExample1() {
// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}

The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above
example that sets the position of the awt button.

Output:

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here,
we are creating a TextField, Label and Button component on the Frame.

AWTExample2.java

// importing Java AWT class


import java.awt.*;
// class AWTExample2 directly creates instance of Frame class
class AWTExample2 {
// initializing using constructor
AWTExample2() {
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// setting position of above components in the frame
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
// adding components into frame
f.add(b);
f.add(l);
f.add(t);
// frame size 300 width and 300 height
f.setSize(400,300);
// setting the title of frame
f.setTitle("Employee info");
// no layout
f.setLayout(null);
// setting visibility of frame
f.setVisible(true);
}
// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();
}
}

Output:
UNIT-II
Introduction to Swing, Differences between AWT Controls &
Swing Controls, JApplet, Swing Button: JButton, JToggleButton,
CheckBoxes, Radio Button, JComboBox, Text Boxes etc., Icons,
Labels, JTabbed Pains, JScroll Pains, JList, JTrees, JTables Java
Beans: Introduction to Java Beans, Advantages of Java Beans,
BDK Introspection, developing a home page using Applet &
Swing.

Introduction of Java Swing

Swing has about four times the number of User Interface [U1] components
as AWT and is part of the standard Java distribution. By today’s application
GUI requirements, AWT is a limited implementation, not quite capable of
providing the components required for developing complex GUIs required in
modern commercial applications. The AWT component set has quite a few
bugs and really does take up a lot of system resources when compared to
equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUIs for commercial applications.
• Swing is a Set of API ( API- Set of Classes and Interfaces )
• Swing is Provided to Design a Graphical User Interfaces
• Swing is an Extension library to the AWT (Abstract Window Toolkit)
• Includes New and improved Components that have been enhancing
the looks and Functionality of GUI’s
• Swing can be used to build(Develop) The Standalone swing GUI
Apps Also as Servlets and Applets
• It Employs model/view design architecture
• Swing is more portable and more flexible than AWT, The Swing is
built on top of the AWT
• Swing is Entirely written in Java
• Java Swing Components are Platform-independent And The Swing
Components are lightweight
• Swing Supports Pluggable look and feels And Swing provides more
powerful components
• such as tables, lists, ScrollPane, Colour chooser, tabbed pane, etc
• Further Swing Follows MVC
Many programmers think that JFC and Swing is one and the same thing, but
that is not so.
JFC contains Swing [A UI component package] and quite a number of other
items:
• Cut and paste: Clipboard support
• Accessibility features: Aimed at developing GUI’s for users with
disabilities
• The Desktop Colors Features Has been Firstly introduced in Java
1.1
• The Java 2D: it has Improved colors, images, and also texts
support
Features Of Swing Class
• Pluggable look and feel
• Uses MVC architecture
• Lightweight Components
• Platform Independent
• Advance features such as JTables, JTabbedPane, JScrollPane etc
• Java is a platform-independent language and runs on any client
machine, the GUI look and feel, owned and delivered by a platform
specific O/S, simply does not affect an application’s GUI
constructed using Swing components
• Lightweight Components: Starting with the JDK 1.1, its AWT
supported lightweight component development. For a component to
qualify as lightweight, it must not depend on any non-Java [O/s
based) system classes. Swing components have their own view
supported by Java’s look and feel classes
• Pluggable Look and Feel: This feature enables the user to switch
the look and feel of Swing components without restarting an
application. The Swing library supports components look and feel
that remains the same across all platforms wherever the program
runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
Swing Classes Hierarchy

The MVC Connection



In general, a visual component is a composite of three distinct
aspects:
0. The way that the component looks when rendered on the
screen
1. The way such that the component reacts to the user
2. The state information associated with the component
• Over the years, one component architecture has proven itself to be
exceptionally effective:- Model-View-Controller or MVC for short.
• In MVC terminology, the model corresponds to the state
information associated with the Component
• The view determines how the component is displayed on the
screen, including any aspects of the view that are affected by the
current state of the model.
• The controller determines how the component reacts to the user
The simplest Swing components have capabilities far beyond AWT
components as follows:
• Swing buttons and the labels can be displaying images instead of
or in addition to text
• The borders around most Swing components can be changed
easily. For example: it is easy to put a 1-pixel border around the
outside of a Swing label
• Swing components do not have to be rectangular. Buttons, for
example, can be round
• Now The Latest Assertive technologies such as screen readers can
easily getting the information from Swing components. For
example: A screen reader tool can easily capture the text that is
displayed on a Swing button or label

AWT and Swing in Java


AWT and Swing are used to develop window-based applications in Java. Awt is an
abstract window toolkit that provides various component classes like Label, Button,
TextField, etc., to show window components on the screen. All these classes are part
of the Java.awt package.

On the other hand, Swing is the part of JFC (Java Foundation Classes) built on the top
of AWT and written entirely in Java

. The javax.swing API provides all the component classes like JButton, JTextField, JCheckbox, JMenu,
etc.

The components of Swing are platform-independent, i.e., swing doesn't depend on


the operating system to show the components. Also, the Swing's components are
lightweight.
The main differences between AWT and swing is given below in the following
table:

Context AWT Swing

API Package The AWT Component classes are The Swing component classes are provided
provided by the java.awt package. by the javax.swing package.

Operating System The Components used in AWT are The Components used in Swing are not
mainly dependent on the operating dependent on the operating system. It is
system. completely scripted in Java.

Weightiness The AWT is heavyweight since it uses The Swing is mostly lightweight since it
the resources of the operating doesn't need any Operating system object
system. for processing. The Swing Components are
built on the top of AWT.

Appearance The Appearance of AWT Components The Swing Components are configurable
is mainly not configurable. It generally and mainly support pluggable look and feel.
depends on the operating system's
look and feels.

Number of The Java AWT provides a smaller Java Swing provides a greater number of
Components number of components in components than AWT, such as list, scroll
comparison to Swing. panes, tables, color choosers, etc.

Full-Form Java AWT stands for Abstract Window Java Swing is mainly referred to as Java
Toolkit. Foundation Classes (JFC).

Peers Java AWT has 21 peers. There is one Java Swing has only one peer in the form of
peer for each control and one peer for OS's window object, which provides the
the dialogue. Peers are provided by drawing surface used to draw the Swing's
the operating system in the form of widgets (label, button, entry fields, etc.)
widgets themselves. developed directly by Java Swing Package.
Functionality and Java AWT many features that are Swing components provide the higher-level
Implementation completely developed by the inbuilt functions for the developer that
developer. It serves as a thin layer of facilitates the coder to write less code.
development on the top of the OS.

Memory Java AWT needs a higher amount of Java Swing needs less memory space as
memory for the execution. compared to Java AWT.

Speed Java AWT is slower than swing in Java Swing is faster than the AWT.
terms of performance.

JApplet
Java applets can be executed on multiple platforms which include
Microsoft Windows, UNIX, Mac OS and Linux. JApplet can also be run as
an application, though this would require a little extra coding. The
executable applet is made available on a domain from which it needs to
be downloaded. The communication of the applet is restricted only to this
particular domain.

JApplet extends the class in the form of java.applet.Applet. JApplet are


executed in a tightly-controlled set of resources referred to as sandboxes.
This prevents the JApplet from accessing local data like the clipboard or
file system.

The first JApplet implementations were performed by downloading an


applet class by class. Classes contain many small files and so applets
were considered to be slow loading components. Since the introduction of
the Java Archive (or simply JAR file), an applet is aggregated and sent as
a single, but larger file.

JButton
The JButton class is used to create a labelled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits Abstract Button class.

JButton class declaration


Let's see the declaration for javax.swing. JButton class.
public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of Abstract Button class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener


to this object.

JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.

Nested Classes
Modifier Class Description
and Type

protected JToggleButton.AccessibleJToggleButton This class implements accessibility


class support for the JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model

Constructors

Constructor Description

JToggleButton() It creates an initially unselected toggle button without


setting the text or image.

JToggleButton(Action a) It creates a toggle button where properties are taken


from the Action supplied.

JToggleButton(Icon icon) It creates an initially unselected toggle button with the


specified image but no text.

JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the specified


text.

JToggleButton(String text, boolean It creates a toggle button with the specified text and
selected) selection state.

JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and
image, and that is initially unselected.

JToggleButton(String text, Icon icon, It creates a toggle button with the specified text, image,
boolean selected) and selection state.

Methods

Modifier and Method Description


Type
AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this
JToggleButton.

String getUIClassID() It returns a string that specifies the name of the


l&f class that renders this component.

protected String paramString() It returns a string representation of this


JToggleButton.

void updateUI() It resets the UI property to a value from the


current look and feel.

CheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true)
or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off"
to "on ".It inherits JToggleButton

class.

JCheckBox class declaration


Let's see the declaration for javax.swing.JCheckBox class.

public class JCheckBox extends JToggleButton implements Accessible

commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text,


no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it
selected) is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
Commonly used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext associated with this


getAccessibleContext() JCheckBox.

protected String paramString() It returns a string


representation of this JCheckBox.

JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration


Let's see the declaration for javax.swing.JRadioButton class.

public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.

Commonly used Methods:

Methods Description
void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, Li


stDataListener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.

JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.

Commonly used Methods:


Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is editable.

void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListener i) It is used to add the ItemListener.

JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.

JTextField class declaration


Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstant


s

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of columns.

Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive action
events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent source,
or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it no


removeActionListener(ActionListener l) longer receives action events from this textfield.

JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.

JLabel class declaration


Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Acces


sible

Commonly used Constructors:

Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty
string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.

JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking
on a tab with a given title or icon. It inherits JComponent class.

JTabbedPane class declaration


Let's see the declaration for javax.swing.JTabbedPane class.
1. public class JTabbedPane extends JComponent implements Serializable, Acc
essible, SwingConstants

Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab placement of


JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement
tabLayoutPolicy) and tab layout policy.

JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose size
can change dynamically.

Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when present, sets the
scroll pane's client. The two int parameters, when present, set the vertical
JScrollPane(Component) and horizontal scroll bar policies (respectively).

JScrollPane(int, int)

JScrollPane(Component,
int, int)

Useful Methods
Modifier Method Description

void setColumnHeaderView(Component) It sets the column header for the scroll pane.

void setRowHeaderView(Component) It sets the row header for the scroll pane.

void setCorner(String, Component) It sets or gets the specified corner. The int parameter
specifies which corner and must be one of the
Component getCorner(String) following constants defined in ScrollPaneConstants:
UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JList
The object of JList class represents a list of text items. The list of text items can be set
up so that the user can choose either one item or multiple items. It inherits
JComponent class.

JList class declaration


Let's see the declaration for javax.swing.JList class.

1. public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel) model.

Commonly used Methods:

Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be notified


listener) each time a change to the selection occurs.

int getSelectedIndex() It is used to return the smallest selected cell index.

ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.

void setListData(Object[] listData) It is used to create a read-only ListModel from an


array of objects.

JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is
a complex component. It has a 'root node' at the top most which is a parent for all
nodes in the tree. It inherits JComponent class.

JTree class declaration


Let's see the declaration for javax.swing.JTree class.

1. public class JTree extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.


JTree(Object[] value) Creates a JTree with every element of the specified array as the child of a new root
node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the root
root) node.

JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns.

JTable class declaration


Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

JavaBean
A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as getter
and setter methods.
Why use JavaBean?
According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.

JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features


are accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()

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

2. setPropertyName ()

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

Advantages of JavaBean
The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another application.


o It provides an easiness to reuse the software components.

Disadvantages of JavaBean
The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead to the
boilerplate code.

Introspection
At the core of Java Beans is introspection. This is the process of analyzing a Bean
to determine its capabilities. This is an essential feature of the Java Beans API
because it allows another application, such as a design tool, to obtain information
about a component. Without introspection, the Java Beans technology could not
operate.
There are two ways in which the developer of a Bean can indicate which of its
properties, events, and methods should be exposed. With the first method, simple
naming conventions are used. These allow the introspection mechanisms to infer
information about a Bean. In the second way, an additional class that extends
the BeanInfo interface is provided that explicitly supplies this information. Both
approaches are examined here.

Design Patterns for Properties

A property is a subset of a Bean’s state. The values assigned to the properties


determine the behavior and appearance of that component. A property is set
through a setter method. A property is obtained by a getter method. There are two
types of properties: simple and indexed.

Simple Properties

A simple property has a single value. It can be identified by the following design
patterns, where N is the name of the property and T is its type:

public T getN( ) public void setN(T arg)

A read/write property has both of these methods to access its values. A read-only
property has only a get method. A write-only property has only a set method.

Indexed Properties
An indexed property consists of multiple values. It can be identified by the
following design patterns, where N is the name of the property and T is its type:

public T getN(int index);

public void setN(int index, T value); public T[ ] getN( );


public void setN(T values[ ]);

Here is an indexed property called data along with its getter and setter methods:
Unit=3
Servlets | Servlet Tutorial

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
side programming language. However, there were many
disadvantages to this technology. We have discussed these disadvantages
below.

There are many interfaces and classes in the Servlet API such as Servlet,
Servlet
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

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


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

Life Cycle of a Servlet (Servlet Life Cycle)


1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

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

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.

1. public void destroy()

Servlet API
1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package

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.

Let's see what are the interfaces of javax.servlet package.


15.9M

208

SQL CREATE TABLE

Interfaces in javax.servlet package


There are many interfaces in javax.servlet package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package


There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package


There are many classes in javax.servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
8. Reading Servlet Parameters
9.
10. The ServletRequest interface includes methods that allow you to read the
names and values of parameters that are included in a client request. We will
develop a servlet that illustrates their use. The example contains two files. A
web page is defined in PostParameters.html, and a servlet is defined
in PostParametersServlet.java.
11. The HTML source code for PostParameters.html is shown in the following
listing. It defines a table that contains two labels and two text fields. One of
the labels is Employee and the other is Phone. There is also a submit button.
Notice that the action parameter of the form tag specifies a URL. The URL
identifies the servlet to process the HTTP POST request.
12. <html>
13.
14. <body>
15.
16. <center>
17.
18. <form name="Form1" method="post"
19.
20. action="http://localhost:8080/examples/servlets/
21.
22. servlet/PostParametersServlet">
23.
24. <table>
25.
26. <tr>
27.
28. <td><B>Employee</td>
29.
30. <td><input type=textbox name="e" size="25" value=""></td>
</tr>
31.
32. <tr>
33.
34. <td><B>Phone</td>
35.
36. <td><input type=textbox name="p" size="25" value=""></td>
</tr>
37.
38. </table>
39.
40. <input type=submit value="Submit"> </body>
41.
42. </html>
43.
44. The source code for PostParametersServlet.java is shown in the following
listing. The service( ) method is overridden to process client requests.
The getParameterNames( ) method returns an enumeration of the
parameter names. These are processed in a loop. You can see that the
parameter name and value are output to the client. The parameter value is
obtained via the getParameter( ) method.
45.
Reading Initialization Parameters
The servlet container provides the initialization parameters for a servlet or filter within the
configuration object the container passes to the init method. The configuration object provides
agetInitParameter() function that takes a std::string name and returns the contents of the
initialization parameter by that name. A filter uses the configuration object to access initialization
parameters. A servlet uses the convenience functions provided by rwsf::GenericServlet to
access initialization parameters directly.
The code sample below shows a servlet retrieving the initialization parameters from
the servlet element shown in Section 4.2.

std::string greeting = getInitParameter("greeting");


std::string fontsize = getInitParameter("fontsize");

If the instance definition does not contain an initialization parameter with the name provided,
the getInitParameter() function returns an empty string.

HTTP Requests
The request sent by the computer to a web server, contains all sorts of
potentially interesting information; it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request
message which includes following information:

o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header
The HTTP request method indicates the method to be performed on the
resource identified by the Requested URI (Uniform Resource Identifier).
This method is case-sensitive and should be used in uppercase.

The HTTP request methods are:

HTTP Description
Request

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET
request with extra info sent with the request.

HEAD Asks for only the header part of whatever a GET would return. Just
like GET but with no body.

TRACE Asks for the loopback of the request message, for testing or
troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request
URL can respond

Handling HTTP POST Requests


Here we will develop a servlet that handles an HTTP POST request. The servlet is
invoked when a form on a web page is submitted. The example contains two files.
A web page is defined in ColorPost.html, and a servlet is defined
in ColorPostServlet.java.

The HTML source code for ColorPost.html is shown in the following listing. It is
identical to ColorGet.html except that the method parameter for the form tag
explicitly specifies that the POST method should be used, and the action parameter
for the form tag specifies a different servlet.

JSP Tutorial
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to Servlet because it provides more
functionality than servlet such as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It
provides some additional features such as Expression Language, Custom Tags,
etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes JSP
development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic
with presentation logic. In Servlet technology, we mix our business logic with
the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project.
The Servlet code needs to be updated and recompiled if we have to change
the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the
help of JSP translator. The JSP translator is a part of the web server which is
responsible for translating the JSP page into Servlet. After that, Servlet page is
compiled by the compiler and gets converted into the class file. Moreover, all
the processes that happen in Servlet are performed on JSP later like
initialization, committing response to the browser and destroy.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it
by .jsp extension. We have saved this file as index.jsp. Put it in a folder and
paste the folder in the web-apps directory in apache tomcat to run the JSP
page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put
Java code in the JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
Problem with servlet

JSP is slower than Servlet because the first step in JSP lifecycle is the
translation of JSP to java code and then compile. Servlet can accept all
protocol requests. JSP only accepts HTTP requests. In Servlet, we can
override the service() method.

Advantages of JSP
Here are the advantages of using JSP:

 It is very much convenient to modify the regular HTML.


 We can write the servlet code into the JSP.
 It is only intended for simple inclusions which can use form data
and make connections.
 You can easily connect with JSP with the MySQL database.
 The performance and scalability of JSP are good because JSP
allows embedding of dynamic elements in HTML pages.
 JSP is built on Java technology hence it is platform-independent
and not depending on any operating systems.
 JSP includes the feature of multithreading of java.
 We can also make use of exception handling of java into JSP.
 It enables to separate presentation layer with the business logic
layer in the web application.
 It is easy for developers to show as well as process the
information.

Disadvantages of JSP
Here are the disadvantages for using JSP:

 It is hard to trace JSP pages error because JSP pages are


translated to servlet.
 As JSP output is HTML, it is not rich in features.
 It is very hard to debug or trace errors because JSP pages are
first translated into servlets before the compilation process.
 Database connectivity is not easy.
 JSP pages require more disk space and time to hold JSP pages
as they are compiled on the server.

The Anatomy of a JSP Page


A JSP page is simply a regular web page with JSP elements for
generating the parts of the page that differ for each request, as show.
Everything in the page that is not a JSP element is called template
text . Template text can really be any text: HTML, WML, XML, or
even plain text. Since HTML is by far the most common web page
language in use today, most of the descriptions and examples in this
book are HTML-based, but keep in mind that JSP has no
dependency on HTML; it can be used with any markup language.
Template text is always passed straight through to the browser.

When a JSP page request is processed, the template text and the
dynamic content generated by the JSP elements are merged, and the
result is sent as the response to the browser.

JSP Elements
There are three types of elements with JavaServer
Pages: directive, action, and scripting elements.
The directive elements, shown in Table 3.1, are used to specify
information about the page itself that remains the same between
page requests, for example, the scripting language used in the page,
whether session tracking is required, and the name of a page that
should be used to report errors, if any.

Jsp aschitecture
The web server needs a JSP engine, i.e, a container to process JSP pages.
The JSP container is responsible for intercepting requests for JSP pages. This
tutorial makes use of Apache which has built-in JSP container to support JSP
pages development.
A JSP container works with the Web server to provide the runtime
environment and other services a JSP needs. It knows how to understand the
special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web
application.

JSP Processing
The following steps explain how the web server creates the Webpage using
JSP −
 As with a normal page, your browser sends an HTTP request to the web
server.
 The web server recognizes that the HTTP request is for a JSP page and
forwards it to a JSP engine. This is done by using the URL or JSP page
which ends with .jsp instead of .html.
 The JSP engine loads the JSP page from disk and converts it into a
servlet content. This conversion is very simple in which all template text
is converted to println( ) statements and all JSP elements are converted
to Java code. This code implements the corresponding dynamic
behavior of the page.
 The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.
 A part of the web server called the servlet engine loads the Servlet class
and executes it. During execution, the servlet produces an output in
HTML format. The output is furthur passed on to the web server by the
servlet engine inside an HTTP response.
 The web server forwards the HTTP response to your browser in terms
of static HTML content.
 Finally, the web browser handles the dynamically-generated HTML
page inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −

Typically, the JSP engine checks to see whether a servlet for a JSP file
already exists and whether the modification date on the JSP is older than the
servlet. If the JSP is older than its generated servlet, the JSP container
assumes that the JSP hasn't changed and that the generated servlet still
matches the JSP's contents. This makes the process more efficient than with
the other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without
having to be a Java programming wiz. Except for the translation phase, a JSP
page is handled exactly like a regular servlet.
What is MVC?
MVC stands for Model-View-Controller. It is a design pattern used for developing
web applications. It is a layout pattern used to isolate the information, presentation
logic, business logic. Web application Logic is divided into three logics:
1. Presentation Logic
2. Business Logic
3. Persistent Logic
Each one is called Model or Tier. MVC is popular because it isolates the appliance
logic from the interface layer and supports the separation of concerns. Here the
Controller receives all requests for the appliance then works with the Model to
organize any data needed by the View. The View then uses the information
prepared by the Controller to get a final presentable response. The MVC abstraction
is often graphically represented as follows.

What is the Model?


It is a module or tier which contains persistent logic or database operation. The
model uses JDBC, Hibernate, JPA. The Model segment compares each one among
the knowledge-related rationale that the client works with. This can speak to either
the information that is being exchanged between the View and Controller segments
or some other business-related information.
What is a Controller?
The controller controls the flow of execution of web applications. In web application
development servlet is called a controller. Controller receive request/input from the
client and uses other modules to perform operations. The controller contains
Business Logic. Controllers set about as an interface amongst Model and consider
segments to process all the business rationale and approaching solicitations, control
information utilizing the Model part and cooperate with the Views to render the last
yield.
What is View?
The view is used for generating input and output. It contains presentation logic. This
is developed using HTML or JSP. The View part is utilized for all the UI rationale of
the application.
Advantages of MVC
1. The main advantage of using MVC in a Web Application is it makes complex
applications easy to manage with divisions of Model, View, and Controllers.
2. MVC provides a strong routing mechanism with a Front Controller pattern.
3. MVC works well for development with large teams with multiple web
developers and designers working simultaneously.
4. In MVC, separating the model from View makes the web application more
robust and easier to maintain.
5. In MVC, separating the Controller from the Model allows configurable
mapping of user actions on the Controller to application functions on the
Model.
Example of MVC in JSP Application
In this example, we are showing how to use MVC architecture in JSP. In this
example, we are creating an example in which servlet as a controller, JSP as a view
component, Java Bean class as a model. In this example, we have created 6 pages.
1. index.jsp
2. ControllerServlet.java
3. LoginBean.java
4. login-success.jsp
5. login-error.jsp
6. web.xml
jsp environment
To work on JSP and create dynamic pages, you will need an environment
where you can develop and run web applications built using JSP. An
environment is basically a set of all the software and tools needed to
create dynamic web pages, test them, and eventually run them in a
virtual client-server. In this lesson, you will learn how to create and set up an
environment to start with JSP programming.

Jsp setup
This is probably the first thing you must do to work under Java supported
tools and technologies. The steps are as follows:

1. Download the Java SDK (Software Development Toolkit)


from https://www.oracle.com/technetwork/java/javase/downloads/index
.html, the official Oracle Java site.
2. After downloading the SDK, follow the instructions of the installation
package.
3. After the JDK installation, some folders will be created on your hard
drive. These are - bin, demo, include, jre, lib, src.
4. Once you installed Java on your machine, you have to set the PATH
along with the JAVA_HOME environment variable that will point to a
particular directory where Java (java_install_dir/bin) and javac
(java_install_dir) are residing.
5. Please refer to the Java installation tutorial to learn further environment
setup steps.

What is Tomcat?
It is an open-source Java servlet container that implements many Java
Enterprise Specs such as the Websites API, Java-Server Pages and last but not
least, the Java Servlet. The complete name of Tomcat is "Apache Tomcat" it
was developed in an open, participatory environment and released in 1998 for
the very first time. It began as the reference implementation for the very first
Java-Server Pages and the Java Servlet API.

What kind of server is Tomcat?


The Java ecosystem supports a wide variety of application servers, so let's have
a little discussion on each of them and see where Tomcat fits in:
A servlet container is basically an implementation of the Java servlet
specification, which is mainly used for the purpose of hosting Java servlets.

The Java enterprise application-server is an implementation of the Java


specification.

A web- server is a kind of server designed to serve files using a local system
such as Apache.

We can say that, at the center, the Tomcat is JSP (Java Server Pages) and
Servlet. The JSP is one of the server-side programming technologies that
enables the developers to create platform-independent dynamic content and
also known as the server-side view rendering technology. A servlet is a java-
based software component that helps in extending the capabilities of a server.
However, it can also respond to several kinds of requests and generally
implemented web server containers to host the web-applications on the
webservers. As the developer's point of view, we just have to write the java
server pages (or JSP) or the servlet and not required to worry about routing;
the Tomcat will handle the routing.

Advantages of Tomcat:
Some significant advantages of Tomcat are as follows:

o It is open-source
It means anyone from anywhere can download, install, and use it free of
cost, which makes it the first choice among the new developers and new
users.
o Incredibly Lightweight
It is actually a very light application, even with the JavaEE's certification.
However, it provides all necessary and standard functionalities required
to operate a server, which means it gives very fast load and redeploys as
compared to its various alternatives.
Yes, it is right that it does not offer so many features in case you want a
number of features, it might be good for you, but if you want to have an
easy and fast means in order to run your application, it is the best
option for you.
o Highly flexible
Due to its built-in customization options, extensive and lightweight
nature, it offers high flexibility, a user can run it in any fashion he wants,
and it will still work as fine without any issues. Since it is open-source,
anyone who has knowledge can tweak it according to his requirements.
o Stability
It is one of the most stable platforms available today to build on and
using it to run our applications. It is incredibly stable because it runs
independently of our Apache installation. In case if there is a big failure
in Tomcat due to which it to stop working, the rest of our server would
run just well.
o It provides us an extra level of security
As the several organizations usually like to position their Tomcat's
installation behind the protection of an extra firewall which can be
accessible only from the Apache installation.
o It is well documented
It has several excellent documentation available, including a vast range
of freely available online tutorials that can be downloaded or viewed
directly online by the user, which makes it one of the best choices to fill
the requirement of an application server in mostly every java web-
application.Whether a user is looking for the installation instructions,
startup settings, server configuration notes, all kind of information about
the Tomcat is already available on the internet.
o It is one of the most widely used application servers
According to an estimation, it holds almost 60 percent of the market
share almost all java application server deployments, which makes it one
of the most popular application servers used for java web-based
applications. However, we cannot say that it implements all of the
features required for a JavaEE application server; instead, it enables us to
run Java EE application.
Tomcat acts as a "webserver" or "servlet container." However, there is a
plethora of terminology for anything.
o It's mature
We take a look back in the past; we will find that it has existed for
almost 20 years, which is quite a significant time, in which it gets mature
over time passage. Since the Tomcat is open-source software, it's
updated, and new releases come out nearly on a regular basis, and the
open-source community maintains it. The maturity makes it one of the
most extremely stable application servers for the development of
software, applications, and deploying java applications. Since now, it is
extremely a stable option that becomes more powerful with excellent
community support.

Let discuss some disadvantages of Tomcat


o It is not as fast as the Apache if we are working with the static pages
o It has some issues like a memory leak
o It's way to handle the logs.
o Issues in the SSL installations
o Its user interface is inferior and basic.

What is Tomcat in testing?


It is an open-source Java servlet container that implements many Java
Enterprise Specs such as the Websites API, Java-Server Pages and last
but not least, the Java Servlet. The complete name of Tomcat is "Apache
Tomcat" it was developed in an open, participatory environment and released
in 1998 for the very first time.

finish
Unit-4 Javascript
Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases. This tutorial will teach you how to use Java Server Pages to
develop your web applications in simple and easy steps.

Why to Learn JSP?


JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in
comparison with the CGI.
 Performance is significantly better because JSP allows embedding Dynamic
Elements in HTML Pages itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time the
page is requested.
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP
also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI,
EJB, JAXP, etc.
 JSP pages can be used in combination with servlets that handle the business
logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding.

Applications of JSP
As mentioned before, JSP is one of the most widely used language over the web. I'm
going to list few of them here:
JSP vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
JSP vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
JSP vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
JSP vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.
JSP vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.

Creating Dynamic Content


You create dynamic content by accessing Java programming language objects from within
scripting elements.

Using Objects within JSP Pages

You can access a variety of objects, including enterprise beans and JavaBeans components,
within a JSP page. JSP technology automatically makes some objects available, and you can also
create and access application-specific objects.

Implicit Objects

Implicit objects are created by the Web container and contain information related to a particular
request, page, or application. Many of the objects are defined by the Java Servlet technology
underlying JSP technology and are discussed at length in . Table 13-2 summarizes the implicit
objects.

Application-Specific Objects

When possible, application behavior should be encapsulated in objects so that page


designers can focus on presentation issues. Objects can be created by developers who
are proficient in the Java programming language and in accessing databases and other
services. There are four ways to create and use objects within a JSP page:

 Instance and class variables of the JSP page's servlet class are
created in declarations and accessed
in scriptlets and expressions.
 Local variables of the JSP page's servlet class are created and
used in scriptlets and expressions.
 Attributes of scope objects (see Using Scope Objects) are created
and used in scriptlets and expressions.
 JavaBeans components can be created and accessed using
streamlined JSP elements. These elements are discussed in the
chapter JavaBeans Components in JSP Pages. You can also create
a JavaBeans component in a declaration or scriptlet and invoke
the methods of a JavaBeans component in a scriptlet or
expression.

Shared Objects

The conditions affecting concurrent access to shared objects described in Controlling


Concurrent Access to Shared Resources apply to objects accessed from JSP pages that
run as multithreaded servlets. You can indicate how a Web container should dispatch
multiple client requests with the following page directive:
<%@ page isThreadSafe="true|false" %>

When isThreadSafe is set to true, the Web container may choose to dispatch multiple
concurrent client requests to the JSP page. This is the default setting. If using true,
you must ensure that you properly synchronize access to any shared objects defined at
the page level. This includes objects created within declarations, JavaBeans
components with page scope, and attributes of the page scope object.

If isThreadSafe is set to false, requests are dispatched one at a time, in the order they
were received, and access to page level objects does not have to be controlled.
However, you still must ensure that access to attributes of
the application or session scope objects and to JavaBeans components with
application or session scope is properly synchronized.

JSP Scriptlet tag (Scripting elements)


1. Scripting elements

2. JSP scriptlet tag


3. Simple Example of JSP scriptlet tag

4. Example of JSP scriptlet tag that prints the user name

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:

o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

<% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.

<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp. The index.html
file gets the username from the user and the welcome.jsp file prints the username with
the welcome message.

File: index.html

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

JSP Implicit Objects


1. JSP Implicit Objects

2. out implicit object

3. Example of out implicit object

There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter. In case of servlet you need to write:

1. PrintWriter out=response.getWriter();

But in JSP, you don't need to write this code.


Example of out implicit object
In this example we are simply displaying date and time.

index.jsp

<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Output

Conditional Processing
In most web applications, you produce different output based on runtime
conditions, such as the state of a bean or the value of a request header such
as UserAgent (containing information about the type of client that is accessing
the page).

If the differences are not too great, you can use JSP scripting elements to
control which parts of the JSP page are sent to the browser, generating
alternative outputs from the same JSP page. However, if the outputs are
completely different, I recommend using a separate JSP page for each
alternative and passing control from one page to another. This chapter
contains a number of examples in which one page is used. In the remainder of
this book you’ll see plenty of examples where multiple pages are used
instead.

Using an Expression to Set an Attribute


In all our JSP action element examples so far, the
attributes are set to literal string values. But in
many cases, the value of an attribute is not known
when you write the JSP page; instead, the value
must be calculated when the JSP page is requested.
For situations like this, you can use a JSP
expression as an attribute value. This is called
a request-time attribute value. Here is an example
of how this can be used to set an attribute of a
fictitious log entry bean:

<jsp:useBean id="logEntry" class="com.foo.LogEntryBean" />

<jsp:setProperty name="logEntry" property="entryTime"

value="<%= new java.util.Date( ) %>" />

...
This bean has a property named entryTime that holds a timestamp for a log
entry, while other properties hold the information to be logged. To set the
timestamp to the time when the JSP page is requested,
a <jsp:setProperty> action with a request-time attribute value is used.

The attribute value is represented by the same type of JSP expression as in


the previous snippet, here an expression that creates a
new java.util.Date object (representing the current date and time). The
request-time attribute is evaluated when the page is requested, and the
corresponding attribute is set to the result of the expression. As you might
have guessed, any property you set this way must have a Java type matching
the result of the expression. In this case, the entryDate property must be of
type java.util.Date.

Not all attributes support request-time ...

Exception Handling in JSP


1. Exception Handling in JSP
2. Example of exception handling in jsp by the elements of page directive
3. Example of exception handling in jsp by specifying the error-page element
in web.xml file

The exception is normally an object that is thrown at runtime. Exception Handling is the
process to handle the runtime errors. There may occur exception any time in your web
application. So handling exceptions is a safer side for the web developer. In JSP, there
are two ways to perform exception handling:

1. By errorPage and isErrorPage attributes of page directive


2. By <error-page> element in web.xml file

Example of exception handling in jsp by the elements of page


directive
In this case, you must define and create a page to handle the exceptions, as in the
error.jsp page. The pages where may occur exception, define the errorPage attribute of
page directive, as in the process.jsp page.

There are 3 files:

o index.jsp for input values


o process.jsp for dividing the two numbers and displaying the result
o error.jsp for handling the exception

index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

Example of exception handling in jsp by specifying the error-


page element in web.xml file
This approach is better because you don't need to specify the errorPage attribute in
each jsp page. Specifying the single entry in the web.xml file will handle the exception.
In this case, either specify exception-type or error-code with the location element. If you
want to handle all the exception, you will have to specify the java.lang.Exception in the
exception-type element. Let's see the simple example:

Debugging a JSP file on a server

Last Updated: 2021-03-02

You can use the debugger to detect and diagnose errors in your application. You can control the
execution of your program by setting breakpoints, suspending threads, stepping through the code, and
examining the contents of the variables. You can debug a JavaServer Page (JSP) without losing the
state of your application.

About this task


To debug a JSP file on a server:

Procedure
1. In the Project Explorer view, open your JSP file. In a Web project, JSP files are located in the
Web Content folder. Double-click the JSP file, the file opens in an editor.
2.

a. Verify that you are using the Source page of the editor. If multiple pages are available
for the editor, such as Design, Source, or Preview page, select the Source page on the
bottom of the editor. If multiple pages are not available, the editor defaults to a source
editor.
b. Select a line of code in the editor and double-click where you want to add the
breakpoint in blue area of the marker bar directly to the left of the line of code.
3. From the JSP file's context menu in the Project Explorer view, click Debug As> Debug on
Server. The workbench switches to the Debug perspective and the server is launched in debug
mode.
4. In the Debug view, step through the code and make the necessary changes to the JSP file. For
detailed information on debugging, refer to the Debugging Java™ applications documentation.
5. Save the JSP file.
6. Click the Refresh icon in the Web Browser to update the changes. The state of your application
is not lost and the server recognizes your changes.

Passing Control and Data Between Pages


As discussed in Chapter 3, one of the most fundamental features of JSP
technology is that it allows for separation of request processing, business
logic and presentation, using what’s known as the Model-View-Controller
(MVC) model. As you may recall, the roles of Model, View, and Controller
can be assigned to different types of server-side components. In this part of
the book, JSP pages are used for both the Controller and View roles, and the
Model role is played by either a bean or a JSP page. This isn’t necessarily the
best approach, but it lets us focus on JSP features instead of getting into Java
programming. If you’re a programmer and interested in other role
assignments, you may want to take a peek at Chapter 18 and Chapter 19.
These chapters describe other alternatives and focus on using a servlet as the
Controller.

In this section we look at how to separate the different aspects in a pure JSP
application, using a modified version of the User Info example from Chapter
8 as a concrete example. In this application, the business logic piece is trivial.
However, it sets the stage for a more advanced application example in the
next section and the remaining chapters in this part of the book; all of them
use the pattern introduced here.
The different aspects of the User Info example can be categorized like this:

 Display the form for user input (presentation)


 Validate the input (request processing and business logic)
 Display the result of the validation ...

Sharing Session and Application Data


The request scope makes data available to multiple pages processing the
same request. But in many cases, data must be shared over multiple requests.

Imagine a travel agency application. It’s important to remember the dates and
destination entered to book the flight so that the customer doesn’t have to
reenter the information when it’s time to make hotel and rental car
reservations. This type of information, available only to requests from the
same user, can be shared through the session scope.

Some information is needed by multiple pages independent of who the


current user is. JSP supports access to this type of shared information through
the application scope. Information saved in the application scope by one page
can later be accessed by another page, even if the two pages were requested
by different users. Examples of information typically shared through the
application scope are database connection pool objects, information about
currently logged-in users, and cache objects that avoid unnecessary database
queries for data that is the same for all users.

Figure 10-4 shows how the server provides access to the two scopes for
different clients.
Introduction and Working of Struts Web Framework
 Last Updated : 28 Jan, 2020
Struts is used to create a web applications based on servlet and JSP. Struts depend on the
MVC (Model View Controller) framework. Struts application is a genuine web
application. Struts are thoroughly useful in building J2EE (Java 2 Platform, Enterprise
Edition) applications because struts takes advantage of J2EE design patterns. Struts
follows these J2EE design patterns including MVC.
In struts, the composite view manages the layout of its sub-views and can implement a
template, making persistent look and feel easier to achieve and customize across the
entire application. A composite view is made up by using other reusable sub views such
that a small change happens in a sub-view is automatically updated in every composite
view.
Struts consists of a set of own custom tag libraries. Struts are based on MVC framework
which is pattern oriented and includes JSP custom tag libraries. Struts also supports
utility classes.
Features of Struts: Struts has the following features:
 Struts encourages good design practices and modeling because the framework is
designed with “time-proven” design patterns.
 Struts is almost simple, so easy to learn and use.
 It supports many convenient features such as input validation and internationalization.
 It takes much of the complexity out as instead of building your own MVC framework,
you can use struts.
 Struts is very well integrated with J2EE.
 Struts has large user community.
 It is flexible and extensible, it is easy for the existing web applications to adapt the
struts framework.
 Struts provide good tag libraries.
 It allows capturing input form data into javabean objects called Action forms.
 It also hand over standard error handling both programmatically and declaratively.

Common Gateway Interface (CGI)


 Difficulty Level : Medium
 Last Updated : 09 Sep, 2019
The Common Gateway Interface (CGI) provides the middleware between WWW
servers and external databases and information sources. The World Wide Web
Consortium (W3C) defined the Common Gateway Interface (CGI) and also defined how
a program interacts with a Hyper Text Transfer Protocol (HTTP) server. The Web server
typically passes the form information to a small application program that processes the
data and may send back a confirmation message. This process or convention for passing
data back and forth between the server and the application is called the common gateway
interface (CGI).
Features of CGI:
 It is a very well defined and supported standard.
 CGI scripts are generally written in either Perl, C, or maybe just a simple shell script.
 CGI is a technology that interfaces with HTML.
 CGI is the best method to create a counter because it is currently the quickest
 CGI standard is generally the most compatible with today’s browsers
Advantages of CGI:
 The advanced tasks are currently a lot easier to perform in CGI than in Java.
 It is always easier to use the code already written than to write your own.
 CGI specifies that the programs can be written in any language, and on any platform,
as long as they conform to the specification.
 CGI-based counters and CGI code to perform simple tasks are available in plenty.
Disadvantages of CGI:
There are some disadvantages of CGI which are given below:
 In Common Gateway Interface each page load incurs overhead by having to load the
programs into memory.
 Generally, data cannot be easily cached in memory between page loads.
 There is a huge existing code base, much of it in Perl.
 CGI uses up a lot of processing time.

You might also like