SlideShare a Scribd company logo
1 of 86
Download to read offline
1 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Unit-I
Topics:
Event Handling | Abtract Window Toolkit
2 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q1. Explain the delegation event model in event handling.
 Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs. This mechanism has the code which is known as event handler that is
executed when an event occurs.
 Java Uses the Delegation Event Model to handle the events. This model defines the
standard mechanism to generate and handle the events.
 The Delegation Event Model has the following key participants namely:
Events: In the delegation model, an event is an object that describes a state change in a
source. It can be generated as a consequence of a person interacting with the elements in a
graphical user interface. Some of the activities that cause events to be generated are
pressing a button, entering a character via the keyboard, selecting an item in a list, and
clicking the mouse.
Source: The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to its handler. Java provide as with classes for source
object. Each type of event has its own registration method.
Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener. For Example,
the method that registers a keyboard event listener is called addKeyListener( ).
Listener: It is also known as event handler. Listener is responsible for generating response
to an event. From java implementation point of view the listener is also an object. Listener
waits until it receives an event. Once the event is received, the listener processes the event
and then returns.
 The benefit of this approach is that the user interface logic is completely separated from the
logic that generates the event. The user interface element is able to delegate the processing
of an event to the separate piece of code
Q2 List various the various Event classes and Event listener.
Event classes
Table enumerates the most important of these event classes and provides a brief
description of when they are generated.
Event Class Description
ActionEvent Generated when a button is pressed, a list is
double-clicked, or a menuitem is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
FocusEvent Generated when a component gains or loses
keyboard focus.
ItemEvent Generated when a check box or a list item is clicked;
also occurs when achoice selection is made or a
checkable menu is selected or deselected.
KeyEvent Generated when input is received from the
keyboard.
3 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
MouseEvent Generated when the mouse is dragged, moved,
clicked, pressed, or released; also generated when
the mouse enters or exits a component.
TextEvent Generated when the value of a text area or text field
is changed.
WindowEvent Generated when a window os activated, closed,
deactivated, deiconified,iconified, opened, or quit.
Event Listener
Following Table lists commonly used listener interfaces and provides a brief description of
the methods that they define.
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events
ItemListener Defines one method to recognize when the state of
an item changes.
KeyListener Defines three methods to recognize when a key is
pressed, released, or typed.
MouseListener Defines five methods to recognize when the mouse
is clicked, enters a component, exits a component,
is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse
is dragged or moved.
TextListener Defines one method to recognize when a text value
changes.
WindowListener Defines seven methods to recognize when a window
is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
Q3. Write a short note on “Event Listeners”. Explain the working with code specification.
The event model is quite powerful and flexible. Any number of event listener objects can
listen for all kinds of events from any number of event source objects. For example, a
program might create one listener per event source or a program might have a single listener
for all events from all sources. A program can even have more than one listener for a single
kind of event from a single event source.
Multiple listeners can register to be notified of events of a particular type from a particular
source. Also, the same listener can listen to notifications from different objects.
Each event is represented by an object that gives information about the event and identifies
the event source.
4 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
class Abc extends Frame implements ActionListener
{
Button ok,cancel;
TextBox t1;
Abc()
{
t1=new TextBox();
ok=new Button(“OK”);
cancel=new Button(“CANCEL”);
ok.addActionListener(this);
cancel.addActionListener(this);
add(ok);
add(cancel);
add(t1);
}
Public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand()==”OK”)
t1.setText(“ You clicked OK button”) ;
else if(ae.getActionCommand()==”CANCEL”)
t1.setText(“You clicked Cancel button”);
}
public static void main(String arg[])
{
new Abc();}
}
}
Q4. Write a java program to handle the mouse related events.
Example:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerEx extends Frame implements MouseListener
{
int x=0, y=0; String str= "";
MouseListenerEx (String title)
{
super(title);
addWindowListener(new MyWindowAdapter(this));
addMouseListener(this);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
5 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
str= "MouseClicked";
x = e.getX();
y = getY();
repaint();
}
public void mousePressed(MouseEvent e)
{
str = "MousePressed";
x = e.getX();
y = getY();
repaint();
}
public void mouseReleased(MouseEvent e)
{
str = "MouseReleased";
x = e.getX();
y = getY();
repaint();
}
public void mouseEntered(MouseEvent e)
{
str= "MouseEntered";
x = e.getX();
y = getY();
repaint();
}
public void mouseExited(MouseEvent e)
{
str = "MouseExited";
x = e.getX();
y = getY();
repaint();
}
public void paint(Graphics g)
{
g.drawString(str + " at " + x + "," + y, 50,50);
}
public static void main(String[] args)
{
MouseListenerEx m= new MouseListenerEx ("Window With Mouse Events Example");
}
}
class MyWindowAdapter extends WindowAdapter
{
6 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
MouseListenerEx myWindow = null;
MyWindowAdapter(MouseListenerEx myWindow)
{
this.myWindow = myWindow;
}
public void windowClosing(WindowEvent we)
{
myWindow.setVisible(false);
}
}
Q5. Write a short note on AWT
The Abstract Window Toolkit (AWT) is class library provides a user interface toolkit called
the Abstract Windowing Toolkit, or the AWT.
The AWT is both powerful and flexible. At the lowest level, the operating system transmits
information from the mouse and keyboard to the program as input, and provides pixels for
program output.
The AWT provides a well-designed object-oriented interface to these low-level services and
resources. Because the Java programming language is platform-independent, the AWT
must also be platform-independent. The AWT was designed to provide a common set of
tools for graphical user interface design that work on a variety of platforms.
The AWT classes are contained in the java.awt package. It is one of Java’s largest
packages. We will list some of the AWT classes:
Class Description
Button Creates a push button control.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box controls.
Choice Creates a pop-up list.
Color Manages colors in a portable, platform-independent fashion.
FlowLayout The flow layout manager. Flow layout positions components left to
right, top to bottom.
Frame Creates a standard window that has a title bar, resize corners, and
7 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
a menu bar.
GridLayout The grid layout manager. Grid layout displays components in a
two-dimensional grid.
Label Creates a label that displays a string.
List Creates a list from which the user can choose. Similar to the
standard Windows list box.
ScrollPane A container that provides horizontal and/or vertical scroll bars for
another component.
TextArea Creates a multiline edit control.
TextField Creates a single-line edit control.
Q6. What are different operations that can be carried out on Frame Window?
The class Frame is a top level window with border and title. It uses BorderLayout as
default layout manager.
Using below method various operation can be performed.
Method Description
setVisisble() Sets whether this frame is visible to user or not.
setSize() Sets the size of frame in width and height
setTitle() Sets the title for this frame to the specified string.
setResizable() Sets whether this frame is resizable by the user.
setMenuBar() Sets the menu bar for this frame to the specified menu bar.
Example:
import java.awt.*;
import java.awt.event.*;
public class FrameDemo extends Frame
{
Label l;
public FrameDemo()
{
setLayout(new FlowLayout());
l=new Label(“Hello World”);
setTitle("Frame Demo");
setSize(400,300);
add(l);
setVisible(true);
}
}
public static void main(String ar[])
{
FrameDemo f=new FrameDemo();
}
}
8 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q7. With respect to AWT explain following controls:
1. Button
2. Checkbox
3. Choice
4. List
5. Scrollbar
Button
Button is a control component that has a label and generates an event when pressed.
When a button is pressed and released, AWT sends an instance of ActionEvent to the
button, by calling processEvent on the button.
Below example demonstrate use of Button in AWT:
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame
{
Button b;
public ButtonDemo()
{
setLayout(new FlowLayout());
b=new Button(“Click Here”);
setTitle("Button Demo");
setSize(400,300);
add(b);
setVisible(true);
}
}
public static void main(String ar[])
{
ButtonDemo f=new ButtonDemo();
}
}
Checkbox
Checkbox control is used to turn an option on(true) or off(false). There is label for each
checkbox representing what the checkbox does.The state of a checkbox can be changed
by clicking on it.
Below example demonstrate use of Checkbox in AWT:
import java.awt.*;
import java.awt.event.*;
public class CheckboxDemo extends Frame
{
9 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Checkbox c1,c2,c3;
Label l;
public CheckboxDemo ()
{
setLayout(new FlowLayout());
l=new Label(“Select Your Hobbies:”);
c1=new Checkbox(“Cricket”);
c2=new Checkbox(“Carrom”);
c3=new Checkbox(“Football”);
setTitle("Checkbox Demo");
setSize(400,300);
add(l);
add(c1);
add(c2);
add(c3);
setVisible(true);
}
}
public static void main(String ar[])
{
CheckboxDemo f=new CheckboxDemo();
}
}
Choice
Choice control is used to show pop up menu of choices. Selected choice is shown on the
top of the menu.
Below example demonstrate use of Choice in AWT:
import java.awt.*;
import java.awt.event.*;
public class ChoiceDemo extends Frame
{
Choice ddl;
Label l;
public ChoiceDemo ()
{
setLayout(new FlowLayout());
l=new Label(“Select State:”);
ddl=new Choice();
ddl.add(“Maharashtra”);
ddl.add(“Uttar Pradesh”);
ddl.add(“Goa”);
ddl.add(“Gujrat”);
setTitle("Choice Demo");
setSize(400,300);
add(l);
add(ddl);
10 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
setVisible(true);
}
}
public static void main(String ar[])
{
ChoiceDemo f=new ChoiceDemo ();
}
}
List
The List represents a list of text items. The list can be configured to that user can choose
either one item or multiple items.
Below example demonstrate use of List in AWT:
import java.awt.*;
import java.awt.event.*;
public class ListDemo extends Frame
{
List lst;
Label l;
public ListDemo()
{
setLayout(new FlowLayout());
l=new Label(“Select Hobbies:”);
lst=new List(4,true);
lst.add(“Cricket”);
lst.add(“Football”);
lst.add(“Music”);
lst.add(“Singing”);
setTitle("List Demo");
setSize(400,300);
add(l);
add(lst);
setVisible(true);
}
}
public static void main(String ar[])
{
ListDemo f=new ListDemo ();
}
}
Scrollbar
Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.
11 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Below example demonstrate use of Scrollbar in AWT:
import java.awt.*;
import java.awt.event.*;
public class ScrollbarDemo extends Frame
{
public ScrollbarDemo ()
{
setLayout(new FlowLayout());
Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL);
Scrollbar verticalScroller = new Scrollbar();
verticalScroller.setOrientation(Scrollbar.VERTICAL);
horizontalScroller.setMaximum (100);
horizontalScroller.setMinimum (1);
verticalScroller.setMaximum (100);
verticalScroller.setMinimum (1);
setTitle("Scrollbar Demo");
setSize(400,300);
add(horizontalScroller);
add(verticalScroller);
setVisible(true);
}
}
public static void main(String ar[])
{
ScrollbarDemo f=new ScrollbarDemo ();
}
}
Q8. How does AWT create Radio Buttons? Explain with syntax and code specification.
OR
What is CheckBoxGroup? Explain with Example.
The java AWT, top-level window, is represented by the CheckBoxGroup. In this program,
we will see how to create and show the CheckboxGroup component on the frame.
In below program a radio button is created that is an item that can be selected or
deselected and displays that state to the user. Here we are creating a group of buttons in
which we can select only one option at a time.
CheckBoxGroup object=new CheckBoxGroup ();
import java.awt.*;
import java.awt.event.*;
public class RadioButtonEx{
public static void main(String[] args)
{
Frame fm=new Frame("RedioButton Group");
Label la=new Label("What is your choice:");
fm.setLayout(new GridLayout(0, 1));
12 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
CheckboxGroup cg1=new CheckboxGroup();
fm.add(la);
fm.add(new Checkbox("Maths", cg1, true));
fm.add(new Checkbox("Physics", cg1, false));
fm.add(new Checkbox("Chemistry", cg1, false));
fm.add(new Checkbox("English", cg1, false));
fm.setSize(250,200);
fm.setVisible(true);
fm.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
Output:
Q9. What are adapter classes? Why are they used?
 An adapter class provides the default implementation of all methods in an event listener
interface. An adapter class provides an empty implementation of all methods in an event
listener interface i.e. this class itself write definition for methods which are present in
particular event listener interface.
 Adapter classes are very useful when we want to process only few of the events that are
handled by a particular event listener interface.
 We can define a new class by extending one of the adapter classes and implement only
those events relevant to us.
 “Every listener that includes more than one abstract method has got a corresponding adapter
class”. The advantage of adapter is that we can override any one or two methods we like
instead of all.
 Adapter classes are useful when we want to receive and process only some of the events
that are handled by a particular event listener interface.
For Example
The MouseMotionAdapter class has 2 methods, mouseDragged( ) & mouseMoved( ),
which are the methods defined by the MouseMotionListener interface.
If we were interested in only mouse drag events, then we could simply extend
MouseMotionAdapter and override mouseDragged( ).
13 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
The empty implementation of mouseMoved( ) would handle the mouse motion events for us.
Some of the Adapter classes are mentioned below.
Adapter Classes
KeyAdpater
MouseAdapter
MouseMotionAdapter
WindowAdapter
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="TAdapterDemo" width=300 height=100>
</applet>
*/
public class TAdapterDemo extends Applet
{
public void init( ){
addMouseListener(
new MouseAdapter( ){
int X, Y;
public void mouseReleased(MouseEvent me){
X = me.getX( );
Y = me.getY( );
Graphics g = TAdapterDemo.this.getGraphics();
g.drawString("Mouse Realeased", X,Y);
}
});
}
}
Q10. What are inner classes? Explain with example
 In object-oriented programming, an inner class or nested class is a class declared entirely
within the body of another class or interface. It is distinguished from a subclass. So an inner
class is a class defined within another class, or even within an expression.
 Inner classes can be used to simplify the code when using event adapter classes as shown
below.
Example:
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
class Inner
14 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
Q11. What are anonymous classes? Explain with example
An anonymous inner class is one that is not assigned a name. This section illustrates how an
anonymous inner class can facilitate the writing of event handlers. Consider the applet shown
in the following listing. As before, its goal is to display the string “Mouse Pressed” in the
status bar of the applet viewer or browser when the mouse is pressed.
Example
import java.applet.*;
import java.awt.event.*;
/*
<applet code="Abc" width=200 height=100>
</applet>
*/
public class Abc extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}
Q12. What are the different Layout Managers classes in java? Explain Card Layout With
Example.
This class support following various types of layout as follows.
LayoutManager Description
BorderLayout The BorderLayout arranges the components to fit in the five
regions: east, west, north, south and center.
CardLayout The CardLayout object treats each component in the container
as a card. Only one card is visible at a time.
FlowLayout The FlowLayout is the default layout. It layouts the components
15 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
in a directional flow.
GridLayout The GridLayout manages the components in form of a
rectangular grid.
CardLayout
The CardLayout class manages the components in such a manner that only one component
is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class:
CardLayout (): creates a card layout with zero horizontal and vertical gap.
CardLayout (int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.
Commonly used methods of CardLayout class:
public void next(Container parent): is used to flip to the next card of the given container.
public void previous(Container parent): is used to flip to the previous card of the given
container.
public void first(Container parent): is used to flip to the first card of the given container.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to the specified card with the
given name.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
16 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
}
public static void main(String[] args)
{
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
}
}
Output:
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
Constructors of GridLayout class:
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but
no gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows
and columns alongwith given horizontal and vertical gaps.
Example:
import java.awt.*;
import javax.swing.*;
public class GridLayoutEx{
JFrame f;
GridLayoutEx(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
17 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new GridLayoutEx();
}
}
Output:
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.
Fields of FlowLayout class:
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING
Constructors of FlowLayout class:
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal
and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
18 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and
the given horizontal and vertical gap.
Example:
import java.awt.*;
import javax.swing.*;
public class FlowLayoutEx
{
JFrame f;
FlowLayoutEx(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutEx();
}
}
Output:
Q13. Explain the Border layout used in java with the help of a program.
OR
What is the default layout of the Frame? Explain the same.
 BorderLayout is the default layout manager for all Windows, such as Frames and Dialogs. It
uses five areas to hold components: north, south, east, west, and center.
 All extra space is placed in the center area. When adding a component to a container with a
border layout, use one of these five constants.
19 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Example:
import java.awt.*;
import java.awt.event.*;
public class BorderLayoutDemo extends Frame
{
Button b1,b2,b3,b4,b5;
public BorderLayoutDemo()
{
BorderLayout b=new BorderLayout();
setLayout(b);
b1=new Button("Center");
b2=new Button("South");
b3=new Button("North");
b4=new Button("East");
b5=new Button("West");
setTitle("Border Layout Example");
add(b1,BorderLayout.CENTER);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.NORTH);
add(b4,BorderLayout.EAST);
add(b5,BorderLayout.WEST);
setSize(500,500);
setVisible(true);
}
public static void main(String ar[])
{
BorderLayoutDemo bl=new BorderLayoutDemo();
}
}
Output:
Q14. Write a java AWT program that creates the following GUI.
Code Sample:
import java.awt.*;
import java.awt.event.*;
20 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
public class Login extends Frame
{
Label l1,l2;
TextField txtUser,txtPwd;
Button b;
public Login()
{
l1=new Label("User Name:");
l2=new Label("Password:");
txtUser=new TextField(15);
txtPwd=new TextField(15);
txtPwd.setEchoChar('#');
b=new Button("Login");
setLayout(new FlowLayout());
setSize(300,300);
setTitle("Login Form");
add(l1);
add(txtUser);
add(l2);
add(txtPwd);
add(b);
setVisible(true);
}
public static void main(String ar[])
{
Login l=new Login();
}
}
Output:
21 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Unit-II
Topics:
Swing
22 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q1. What are swings in java? Explain the features of swing
 Swing/JFC is short for Java Foundation Classes, which encompass a group of features for
building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity
to Java applications.
 The swing API contains 100% pure java versions of the AWT components, plus many
additional components that are also 100% pure java, because swing does not contain or
depend on native code.
 Swing is the package or set of classes that provide more powerful and flexible component
than that of ‘AWT’.
 It supplies several exiting addition including tabbed panes, trees and tables.
 Even familiar component like buttons have more capabilities in swing i.e. buttons may have
both image and text associated with it.
 The hierarchy of java swing API is given below.
Following are features of swing.
Swing Components Are Lightweight
This means that they are written entirely in Java and do not map directly to platform specific
peers. Because lightweight components are rendered using graphics primitives, they can be
transparent which enables non rectangular shapes. Thus, lightweight components are more
efficient and more flexible.
Swing Supports a Pluggable Look and Feel
Each Swing component is rendered by Java code rather than by native peers, the look and
feel of a component is under the control of Swing.
It is possible to “plug in” a new look and feel for any given component without creating any
side effects in the code that uses that component.
The MVC Architecture
23 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
This is Essential feature of Swing that is using MVC we can change internal representation of
table, trees and list.
New Components
There are various new components provided by swing which are as follows
Image Button
Tabbed Panes
Sliders
Toolbars
Text Areas
List
Trees
Tables
Q2. Explain the new features of JFC.
The JFC (Java Foundation Classes) are a set of GUI components and services which simplify
the development and deployment of commercial quality of desktop and Internet or Intranet
applications.
Its features are:
Java Foundation classes are core to the Java 2 Platform.
All JFC components are JavaBeans components and therefore reusable, interoperable, and
portable.
JFC offers an open architecture. Third-party JavaBeans components can be used to enhance
applications written using JFC.
It is truly cross-platform.
Q3. Compare Swing and AWT.
There are many differences between java awt and swing that are given below.
A.W.T Swing
AWT components are platform-dependent. Java swing components are platform-
independent
AWT components are heavyweight. Swing components are lightweight
AWT doesn't support pluggable look and
feel.
Swing supports pluggable look and feel.
AWT provides less components than Swing Swing provides more powerful components
such as tables, lists.
AWT doesn't follow MVC architecture. Swing follows MVC architecture.
It does not consist of new components. It consists of new components such as
Sliders, Tabbed Button, Toolbars and Tables
and so on
AWT is a thin layer of code on top of the
OS.
Swing is much larger. Swing also has very
much richer functionality.
Controls does not start with character J. In swing Controls start with character J. Ex.
JButton , JTextFiled
Q12. Write a java program using JCheckBox and JRadioButton.
24 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
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.
Constructor of JRadioButton:
JRadioButton(): creates an unselected radio button with no text.
JRadioButton(String s): creates an unselected radio button with specified text.
JRadioButton(String s, boolean selected): creates a radio button with the specified text and
selected status.
Example of JRadioButton with source code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Xyz extends JFrame
{
JPanel jpl;
JLabel lbl;
JRadioButton rnd1,rnd2;
ButtonGroup bgrp;
Xyz()
{
jpl=new JPanel();
bgrp=new ButtonGroup();
lbl=new JLabel("Select Job Type:");
rnd1=new JRadioButton("Full Time");
rnd2=new JRadioButton("Part Time");
bgrp.add(rnd1);
bgrp.add(rnd2);
setTitle("JCheckbox Example");
setSize(300,300);
jpl.add(lbl);
jpl.add(rnd1);
jpl.add(rnd2);
add(jpl);
setVisible(true);
}
}
class JRadioButtonEx
{
public static void main(String ar[])
{
Xyz x1=new Xyz();
}
}
25 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
JCheckBox
The JCheckBox class is used to create the checkbox and use can select multiple option.
Constructor of JCheckBox:
JCheckBox (): creates an unselected checkbox with no text.
JCheckBox (String s): creates an unselected checkbox with specified text.
Example of JCheckBox with source code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Xyz extends JFrame
{
JPanel jpl;
JCheckBox chk1,chk2;
Xyz()
{
jpl=new JPanel();
chk1=new JCheckBox("Cricket");
chk2=new JCheckBox("Basketball");
setTitle("JCheckbox Example");
setSize(300,300);
jpl.add(chk1);
jpl.add(chk2);
add(jpl);
setVisible(true);
}
}
class JCheckboxEx
{
public static void main(String ar[])
{
Xyz x1=new Xyz();
}
}
Q4. Write a java SWING program that creates the JTree GUI.
JTree is a Swing component with which we can display hierarchical data. JTree is quite a
complex component.
A JTree has a 'root node' which is the top-most parent for all nodes in the tree. A node is an
item in a tree. A node can have many children nodes.
These children nodes themselves can have further children nodes. If a node doesn't have any
children node, it is called a leaf node.
Example of JTree with source code
26 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
class Abc extends JFrame
{
JTree tree;
JPanel jpl;
public Abc()
{
DefaultMutableTreeNode r=new DefaultMutableTreeNode("Course");
DefaultMutableTreeNode i=new DefaultMutableTreeNode("Bsc-IT");
DefaultMutableTreeNode cs=new DefaultMutableTreeNode("Bsc-CS");
r.add(i);
r.add(cs);
DefaultMutableTreeNode fi=new DefaultMutableTreeNode("FYIT");
DefaultMutableTreeNode si=new DefaultMutableTreeNode("SYIT");
DefaultMutableTreeNode ti=new DefaultMutableTreeNode("TYIT");
i.add(fi);
i.add(si);
i.add(ti);
DefaultMutableTreeNode fcs=new DefaultMutableTreeNode("FYCS");
DefaultMutableTreeNode scs=new DefaultMutableTreeNode("SYCS");
DefaultMutableTreeNode tcs=new DefaultMutableTreeNode("TYCS");
cs.add(fcs);
cs.add(scs);
cs.add(tcs);
tree=new JTree(r);
jpl=new JPanel();
jpl.add(tree);
add(jpl);
setTitle("JTree Example");
setSize(500,500);
setVisible(true);
}
class JTreeEx
{
public static void main(String ar[])
{
Abc a1=new Abc();
}
}
27 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Output:
Q5. Write a java program to create different tabs using JTabbedPane.
A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display
both text and an image. With the JTabbedPane class, we can have several components, such
as panels, share the same space. The user chooses which component to view by selecting
the tab corresponding to the desired component
Example of JTabbedPane with source code
import javax.swing.*;
class Abc extends JFrame
{
JPanel jpl;
JTabbedPane jtp;
JButton b1,b2;
Abc()
{
jpl=new JPanel();
b1=new JButton("Button1");
b2=new JButton("Button2");
jtp=new JTabbedPane(2);
jtp.add("Tap1",b1);
jtp.add("Tap2",b2);
jpl.add(jtp);
setTitle("JFrame Example");
setSize(300,300);
add(jpl);
setVisible(true);
}
}
class JTappedPaneEx
{
28 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
public static void main(String ar[])
{
Abc a1=new Abc();
}
}
Output:
Q6. Explain JPopupMenu Class with Example
Popup menu represents a menu which can be dynamically popped up at a specified position
within a component.
JPopupMenu Constructor
JPopupMenu (): Constructs a JPopupMenu without an "invoker".
JPopupMenu (String label): Constructs a JPopupMenu with the specified title.
Example of JPopupMenu with source code
import javax.swing.*;
import java.awt.event.*;
class Abc extends JFrame
{
JPopupMenu jpm;
JMenuItem i1,i2,i3,i4;
public Abc()
{
jpm=new JPopupMenu();
i1=new JMenuItem("New");
i2=new JMenuItem("Save");
i3=new JMenuItem("Open");
i4=new JMenuItem("Exit");
jpm.add(i1);
jpm.add(i2);
jpm.add(i3);
jpm.add(i4);
setTitle("JPopupMenu Example");
addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent me)
{
jpm.show(me.getComponent(),me.getX(),me.getY());
}
}
);
setSize(500,500);
setVisible(true);
29 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
}
}
class JPopupMenuEx
{
public static void main(String ar[])
{
Abc a1=new Abc();
}
}
Output:
Q7. How are menus created in java? What are the classes used for creating menus?
Explain with example.
The JMenuBar class provides an implementation of a menu bar. For creating menu we use
JMenuItem and JMenu classes.
Example of JMenu with source code
import javax.swing.*;
import java.awt.*;
class Abc extends JFrame
{
JMenuBar jmb;
JMenu m1,m2;
JMenuItem i1,i2,i3,i4;
Abc()
{
jmb=new JMenuBar();
m1=new JMenu("File");
m2=new JMenu("Edit");
jmb.add(m1);
jmb.add(m2);
30 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
i1=new JMenuItem("New");
i2=new JMenuItem("Save");
i3=new JMenuItem("Save As");
i4=new JMenuItem("Exit");
m1.add(i1);
m1.add(i2);
m1.add(i3);
m1.add(i4);
setLayout(new FlowLayout());
setTitle("JFrame Example");
setSize(300,300);
setJMenuBar(jmb);
setVisible(true);
}
}
class JMenuBarEx
{
public static void main(String ar[])
{
Abc a1=new Abc();
}
}
Output:
Q8. Explain JScrollPane and JScrollBar with example.
JScrollPane
 It provides a scrollable view of a lightweight component. A JScrollPane manages a viewport,
optional vertical and horizontal scroll bars, and optional row and column heading viewports.
 JScrollPane does not support heavyweight components.
JScrollBar
 The JScrollBar lets the user graphically select a value by sliding a knob within a bounded
interval.
 It is us a very useful component when we want to display large amount of elements on the
screen.
Constructors:
31 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
JScrollBar ( ): It Creates a JScrollBar instance with a range of 0-100, an initial value of 0, and
vertical orientation.
JScrollBar (int Orientation): It creates a JScrollBar instance with a range of 0-100, an initial
value of 0, and the specified orientation.
Methods:
getValue ( ) : It gives the current value of scroll bar.
setMaximum (int Max) :The maximum value of the scrollbar is maximum – extent.
setMinimum (int Min) : Returns the minimum value supported by the scrollbar (usually zero).
setValue (int Value) :Sets the scrollbar's value.
Example of JScrollPane with source code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Xyz extends JFrame
{
JPanel jpl;
JLabel lbl;
JTextArea txtAdd;
JScrollPane jsp;
Xyz()
{
String str="Plase mention address here";
jpl=new JPanel();
lbl=new JLabel("Address:");
txtAdd=new JTextArea(str,6,16);
jsp=new JScrollPane(txtAdd);
setTitle("JCheckbox Example");
setSize(300,300);
jpl.add(lbl);
jpl.add(jsp);
add(jpl);
setVisible(true);
}
}
class JScrollPaneEx
{
public static void main(String ar[])
{
Xyz x1=new Xyz();
}
}
Q9. Explain JColorChooser with example.
The JColorChooser class is used to create a color chooser dialog box so that user can select
any color.
JPopupMenu Constructor
32 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
JColorChooser (): is used to create a color chooser pane with white color initially.
JColorChooser (Color c): is used to create a color chooser pane with the specified color
initially.
Example of JColorChooser with source code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Abc extends JFrame implements ActionListener
{
JButton b;
JPanel jpl;
Abc()
{
b=new JButton("Color");
b.addActionListener(this);
jpl=new JPanel();
setTitle("JColorChooser Example");
setSize(300,300);
jpl.add(b);
add(jpl);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Color initialcolor=Color.RED;
Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
setBackground(color);
}
}
class JColorChooserEx
{
public static void main(String ar[])
{
Abc a1=new Abc();
}
}
Output:
33 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q10. How do divide frame window in 2 parts? Explain with code specification.
The JSplitPane is commonly used component because it lets we want split our window
horizontally or vertically in order to create a wide variety of GUI elements to suit our
application’s needs.
In short in order to create a JSplitPane component in Java, one should follow these steps:
 Create a new JFrame.
 Call setLayout(new FlowLayout()) to set flow layout for the frame.
 Create two String arrays that will containt the contents of the two areas of theJSplitPane.
 Create two JScrollPane components.
 Create a new JSplitPane with the above JScrollPane components in each side.
 Use frame.getContentPane().add(splitPane) to add the spilt pane to our frame
Example of JMenu with source code
import java.awt.*;
import javax.swing.*;
class Abc extends JFrame
{
JPanel p1,p2;
Abc()
{
String[] options1 = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox combo1 = new JComboBox(options1);
String[] options2 = { "Car", "Motorcycle", "Airplane", "Boat" };
JComboBox combo2 = new JComboBox(options2);
p1 = new JPanel();
p1.add(combo1);
p2 = new JPanel();
p2.add(combo2);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p1, p2);
setTitle("Split Pane Example");
setSize(200, 200);
setLayout(new FlowLayout());
34 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
add(splitPane);
setVisible(true);
}
}
class JSplitPaneEx
{
public static void main(String[]ar)
{
Abc a1=new Abc();
}
}
Output:
Q11. How to denote the user about the software loading process? Which component is
facilitating the same? Explain with code specification.
This is the class which creates the progress bar using its constructor JProgressBar () to show
the status of our process completion.
The constructor JProgressBar() takes two argument as parameter in which, first is the initial
value of the progress bar which is shown in the starting and another argument is the counter
value by which the value of the progress bar is incremented.
setStringPainted(boolean):
This is the method of the JProgressBar class which shows the complete process in percent
on the progress bar. It takes a Boolean value as a parameter. If we pass the true then the
value will be seen on the progress bar otherwise not seen.
setValue():
This is the method of the JProgressBar class which sets the value to the progress bar.
Timer ():
This constructor takes two arguments as parameter first is the interval (in milliseconds) of the
timer and second one is the listener object. Time is started using the start () method of the
Timer class.
Example of JProgressBar with source code
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ProgressSample
{
public static void main(String args[])
{
35 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
JFrame f = new JFrame("JProgressBar Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
f.add(progressBar, BorderLayout.NORTH);
f.setSize(300, 100);
f.setVisible(true);
}
}
36 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Unit-III
Topics:
Servlet & Working with Servlet
37 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q1. What are servlets? What are advantages of using servlets?
 Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
 Using Servlets, we can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.
 Following diagram shows the position of Servlets in a Web Application.
 Java Servlets are Java classes run by a web server that has an interpreter that supports the
Java Servlet specification.
 Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java's enterprise edition
 Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Advantages of servlet
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the resources on
a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software.
Q2. What is servlet? What are different tasks carried out by servlets?
Servlets perform the following major tasks:
 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
 Send the explicit data to the clients (browsers). This document can be sent in a variety of
formats, including text (HTML or XML), binary (GIF images), Excel, etc.
38 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
Q3. What is CGI? What are the disadvantages of CGI?
CGI (Common Gateway Interface)
 CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Common Gateway Interface)
Disadvantages of CGI
 The biggest disadvantage of CGI programming is lack of scalability and reduced speed. Each
time a request is received by the Web server, an entirely new process thread is created.
 It uses platform dependent language e.g. C, C++, Perl.
 If number of client’s increases, it takes more time for sending response.
 For each request, it starts a process and Web server is limited to start processes.
 A process thread consume a lot of server side resources especially in multi –user situation
 Difficult for beginners to program modules in this environment
 Sharing resources such as data base connections between scripts or multi cells to the same
scripts was not available, leading to repeated execution of expensive operation.
Q4. Explain the life cycle of servlet
Life Cycle of a Servlet
The web container maintains the life cycle of a servlet instance. The life cycle of the servlet
conists of following phases as folows:
 Servlet class is loaded.
 Servlet instance is created.
 init method is invoked.
 service method is invoked.
 destroy method is invoked.
Below diagram shows the life-cycle of servlet as follows.
39 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
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 destroy () method, it shifts to the end state.
Servlet class is loaded
The class loader 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.
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.
init method is invoked
The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface.
Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
service method is invoked
The web container calls the service method each time when request for the servlet is received.
If servlet is not initialized, it follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service method. Notice that servlet is
initialized only once.
The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest req, ServletResponse res) throws ServletException
destroy method is invoked
40 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc.
The syntax of the destroy method of the Servlet interface is given below:
public void destroy()throws ServletException
Q5. Short note on Servlet API
Servlet API consists of 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.
The javax.servlet package
Interfaces Classes
Servlet GenericServlet
ServletRequest ServletInputStream
ServletResponse ServletOutputStream
RequestDispatcher ServletException
ServletConfig ServletContextEvent
ServletContext UnavailableException
The javax.servlet.http package
Interfaces Classes
HttpServletRequest HttpServlet
HttpServletResponse Cookie
HttpSession HttpSessionEvent
HttpSessionListener
Q6. Explain the structure of web.xml file with respect to servlet.
Below example demonstrate the structure of web.xml with respect to servlet.
<web-app>>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
The <servlet> tag configures the servlet. In our simple example, we just need to specify the
class name for the servlet.
The <servlet-mapping> tag specifies the URLs which will invoke the servlet. In our case, the
/hello URL invokes the servlet.
41 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q7. Explain the web application directory structure.
Below diagram shows the web application directory structure.
The root directory, we can put all files that should be accessible in our web application. For
instance, if our web application is mapped to the URL.
The WEB-INF directory is located just below the web app root directory. This directory is a
Meta information directory. Files stored in here are not supposed to be accessible from a
browser.
Inside the WEB-INF directory there are two important directories. These are described below.
The web.xml file contains information about the web application, which is used by the Java
web server / servlet container in order to properly deploy and execute the web application.
The classes directory contains all compiled Java classes that are part of our web application.
The lib directory contains all JAR files used by our web application. This directory most often
contains any third party libraries that our application is using.
Q8. Explain GenericServlet with its constructors and methods.
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides
the implementation of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
It consists of following methods.
Method Description
init(ServletConfig config) Returns the parameter value for the specified
parameter name.
service(ServletRequest request,
ServletResponse response)
Returns the names of the context's initialization
parameters.
destroy() Sets the given object in the application scope.
getServletConfig() Returns the attribute for the specified name.
getServletInfo() Removes the attribute with the given name from the
servlet context.
getServletName() It returns the name of the servlet object.
Q9. What is request Dispatcher? What are its two methods?
42 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
 The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp.
 This interface can also be used to include the content of another resource also. It is one of
the ways of servlet collaboration.
 There are two methods defined in the RequestDispatcher interface. They are:
Method Description
forward() Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML) on the server.
include () Includes the content of a resource (servlet, JSP
page, or HTML file) in the response.
As we see in the above figure, response of second servlet is sent to the client. Response of
the first servlet is not displayed to the user.
As we can see in the above figure, response of second servlet is included in the response of
the first servlet that is being sent to the client.
Q10. Explain the ServletConfig interface in java.
 An object of ServletConfig is created by the web container for each servlet. This object can
be used to get configuration information from web.xml file.
 If the configuration information is modified from the web.xml file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from
time to time.
 The core advantage of ServletConfig is that we don't need to edit the servlet file if information
is modified from the web.xml file.
It consists of following methods.
43 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Method Description
getInitParameter(String name) Returns the parameter value for the specified
parameter name.
getInitParameterNames() Returns the names of the context's initialization
parameters.
getServletName() Returns the name of the servlet.
getServletContext() Returns an object of ServletContext.
Q11. Why do we need the ServletContext interface in java?
 All Servlets belong to one ServletContext which can be called at context initialisation time.
 It enables applications to load servlets at run time.
 It contains methods to communicate with the server:
 Finding path information
 Accessing other servlets running on the server
 It used for writing to server log file.
There can be a lot of usage of ServletContext object. Some of them are as follows:
 The object of ServletContext provides an interface between the container and servlet.
 The ServletContext object can be used to get configuration information from the web.xml file.
 The ServletContext object can be used to set, get or remove attribute from the web.xml file.
 The ServletContext object can be used to provide inter-application communication.
It consists of following methods.
Method Description
getInitParameter(String name) Returns the parameter value for the specified
parameter name.
getInitParameterNames() Returns the names of the context's initialization
parameters.
setAttribute(String name, Object obj) Sets the given object in the application scope.
getAttribute(String name) Returns the attribute for the specified name.
removeAttribute(String name) Removes the attribute with the given name from
the servlet context.
Q12. What are HTTPServletRequest and HTTPServletResponse?
HttpServletRequest and HttpServletResponse classes are just extensions of ServletRequest
and ServletResponse with HTTP-specific information stored in them.
HTTPServletRequest
44 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
 It extends the ServletRequest interface to provide request information for HTTP servlets. The
servlet container creates an HttpServletRequest object and passes it as an argument to the
servlet's service methods (doGet, doPost, etc).
 The request object is an instance of a javax.servlet.http.HttpServletRequest object.
 It consists of following methods.
Method Description
getCookies() Returns an array containing all of the Cookie objects
the client sent with this request.
getAttributeNames() Returns an Enumeration containing the names of
the attributes available to this request.
getSession() Returns the current session associated with this
request, or if the request does not have a session,
creates one.
getContentType() Returns the MIME type of the body of the request, or
null if the type is not known.
getParameter(String name) Returns the value of a request parameter as a
String, or null if the parameter does not exist.
HTTPServletResponse
 It provides methods for extracting HTTP parameters from the query string or the request
body depending on type of request GET or POST.
 The response object is an instance of a javax.servlet.http.HttpServletResponse object.
 It consists of following methods.
Method Description
addCookies() Adds the specified cookie to the response.
sendRedirect(String location) Sends a temporary redirect response to the client
using the specified redirect location URL.
setContentType(String type) Sets the content type of the response being sent to
the client, if the response has not been committed
yet.
setStatus(int sc) Sets the status code for this response.
getParameter(String name) Returns the value of a request parameter as a
String, or null if the parameter does not exist.
Q13. Short note on HTTPSession.
 Session simply means a particular interval of time.
 Session Tracking is a way to maintain state (data) of a user. It is also known as session
management in servlet.
 Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we
need to maintain the state of a user to recognize to particular user.
 HTTP is stateless that means each request is considered as the new request. It is shown in
the figure given below:
45 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
An object of HttpSession can be used to perform two tasks:
 Bind objects
 View and manipulate information about a session, such as the session identifier, creation
time, and last accessed time
 It consists of following methods.
Method Description
getId() Returns a string containing the unique identifier value.
getCreationTime() Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
getLastAccessedTime() Returns the last time the client sent a request associated with
this session, as the number of milliseconds since midnight
January 1, 1970 GMT.
Source Code
HttpSession session=request.getSession(false);
String n= (String)session.getAttribute("uname");
Q14. What is a cookie? How to create and use in servlet.
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser. After
that if request is sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie
46 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple sessions. It is not removed each time when user closes the browser. It
is removed only if user logout or sign out.
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
 It will not work if cookie is disabled from the browser.
 Only textual information can be set in Cookie object.
Creation of cookie
Cookie ck=new Cookie("user","Allwin");//creating cookie object
response.addCookie(ck);//adding cookie in the response
Retrieving information from cookie
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
}
Deletion of cookie
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
Q15. Write a servlet program to display the factorial of a given number.
Home.html
<html>
<head>
<title>Factorial</title>
</head>
<body>
<form method="get" action="FactorialServlet">
<table>
<tr><td>Enter a value to find its factorial</td><td><input type="text"
name="text1"/></td></tr>
<tr><td></td><td><input type="submit" value="ok"/></td></tr>
</table>
</form>
</body>
</html>
FactorialServlet.java
47 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
package Factorial
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FactorialServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int num = Integer.parseInt(request.getParameter("text1"));
out.println(this.fact(num));
}
long fact(long a)
{
if (a <= 1)
return 1;
else {
a = a * fact(a - 1);
return a;
}
}
}
48 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Unit-IV
Topics:
Java Server Pages(JSP) | JDBC
49 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q1. What is JSP? What are advantages and disadvantages of JSP?
 JavaServer Pages (JSP) is a technology for developing web pages that support dynamic
content which helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.
 A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application.
 Web developers write JSPs as text files that combine HTML or XHTML code, XML elements,
and embedded JSP actions and commands.
 Using JSP, we can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
 JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages and sharing information between requests, pages etc.
Advantages of JSP:
 HTML friendly simple and easy language and tags
 Supports java code
 Supports standard web site development tools
 Rich UI features
 Much Java knowledge is not required
Disadvantages
 As JSP pages are translated into servlet and compiled, it is difficult to trace the errors
occurred in JSP page
 JSP pages requires double the disk spaces
 JSP requires more time to execute when it is accessed for the first time
Q2. Write the advantages of JSP over Servlet.
There are many advantages of JSP over servlet. These are as follows:
 JSP is the extension to the servlet technology. We can use all the features of 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.
 JSP can be easily managed because we can easily separate our business logic with
presentation logic.
 In servlet, we mix our business logic with the presentation logic.
 If JSP page is modified, we don't need to redeploy the project. The servlet code needs to be
updated and recompiled if we have to change the look and feel of the application.
 Nobody can borrow the code
 Faster loading of pages
 No browser compatibility issues
Q3. Explain the life cycle of JSP Page.
A JSP life cycle can be defined as the entire process from its creation till the destruction
which is similar to a servlet life cycle with an additional step which is required to compile a
JSP into servlet.
50 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
The following are the paths followed by a JSP
 Compilation
 Initialization
 Execution
 Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as
follows:
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If
you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit()
{
// Initialization code...
}
JSP Execution:
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP
engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its
parameters as follows:
void _jspService(HttpServletRequest request,HttpServletResponse response)
{
51 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
// Service handling code...
}
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from
use by a container.
jspDestroy method used when we need to perform any cleanup, such as releasing database
connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
// cleanup code goes here.
}
Q4. Explain the JSP document and various component reslated to it.
There are many component of JSP document. These are as follows:
 JSP Directives
 JSP Declaration
 JSP Expression
 JSP Scriptlet
 JSP Comment
 JSP Action Tag
JSP Directives
The jsp directives are messages that tells the web container how to translate a JSP page into
the corresponding servlet.
There are three types of directives:
page directive
include directive
taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
JSP Declaration
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
52 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Example:
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
JSP Expresssion
The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.
Syntax of JSP expression tag
<%= statement %>
Example:
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
JSP Scriptlet
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what
are the scripting elements first.
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example:
<html>
<body>
53 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
<% out.print("welcome to jsp"); %>
</body>
</html>
JSP Comment
JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>
Example:
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
JSP Action Tag
There are many JSP action tags or elements. Each JSP action tag is used to perform some specific
tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.
Q5. Explain the <jsp: include> and <jsp: forward> element used in JSP.
The <jsp: include> Action
This action lets you insert files into the page being generated. The syntax looks like this:
<jsp: include page="relative URL" flush="true" />
54 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested.
Following is the lists of attributes associated with include action:
Attribute Purpose
page The relative URL of the page to be included.
flush The Boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Example:
Date.jsp
<p>
Today's date: <%= (new java.util.Date()).toString()%>
</p>
Main.jsp
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page="date.jsp" flush="true" />
</center>
</body>
</html>
The <jsp: forward> Action
The forward action terminates the action of the current page and forwards the request to another
resource such as a static page, another JSP page, or a Java Servlet.
The simple syntax of this action is as follows
<jsp: include page="relative URL" flush="true" />
Following is the lists of attributes associated with include action:
Attribute Purpose
page The relative URL of the page to be included.
flush The Boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Example:
Date.jsp
<p>
55 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Today's date: <%= (new java.util.Date()).toString()%>
</p>
Main.jsp
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:forward page="Date.jsp" flush="true" />
</center>
</body>
</html>
Q6. Explain different types of directives used in JSP
JSP directives provide directions and instructions to the container, telling it how to handle
certain aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the following
form:
<%@ directive attribute="value" %>
There are three types of directive tag:
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as scripting language,
error page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the
page
The page Directive:
The page directive is used to provide instructions to the container that pertain to the current
JSP page.
Attributes: Following is the list of attributes associated with page directive:
Attribute Purpose
language Defines the programming language used in the JSP page.
import Specifies a list of packages or classes for use in the JSP as the Java
import statement does for Java classes.
extends Specifies a superclass that the generated servlet must extend
contentType Defines the character encoding scheme.
errorPage Defines the URL of another JSP that reports on Java unchecked runtime
exceptions.
session Specifies whether or not the JSP page participates in HTTP sessions
56 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Include Directive:
Include directive is used to includes a file during the translation phase. This directive tells
the container to merge the content of other external files with the current JSP during the
translation phase.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
The filename in the include directive is actually a relative URL. If we just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as
our JSP.
The taglib Directive:
The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides a means for identifying the custom tags in your JSP
page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
Q7. How can you add a bean to a JSP page?
The jsp: useBean action tag is used to locate or instantiate a bean class. If bean object of the
Bean class is already created, it doesn't create the bean depending on the scope.
Syntax of jsp: useBean action tag
<jsp: useBean id= "instanceName" scope= "page | request | session | application” class=
"packageName.className" type= "packageName.className” > </jsp: useBean>
Attributes and Usage of jsp: useBean action tag
 Id: is used to identify the bean in the specified scope.
 Scope: represents the scope of the bean. It may be page, request, session or application.
The default scope is page.
 Class: instantiates the specified bean class but it must have no-argument or no constructor
and must not be abstract.
Example
package MyPackage;
public class Calculator{
public int cube(int n){return n*n*n;}
}
index.jsp file
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
 To access the properties of bean, the syntax is as follows:
<jsp:getProperty name=”BeanName” property=”PropertyName” />
 To set the properties of bean, the syntax is as follows:
<jsp:setProperty name=”BeanName” property=”PropertyName” value=”Newvalue”/>
57 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q8. Explain any 5 implicit objects used in JSP.
Implicit Objects are the Java objects that the JSP Container makes available to developers
in each page and developer can call them directly without being explicitly declared. JSP
Implicit Objects are also called pre-defined variables.
JSP supports following Implicit Objects which are listed below:
Object Description
request This is the HttpServletRequest object associated with the request.
response This is the HttpServletResponse object associated with the response to
the client.
out This is the PrintWriter object used to send output to the client.
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with application context.
config This is the ServletConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher
performance JspWriters.
page This is simply a synonym for this, and is used to call the methods defined
by the translated servlet class.
Q9. Write a JSP application that computes the cubes of the numbers from 1 to 10. Simple
code is expected with the output.
Source Code:
<%
int i,sum=0;
for (i=1;i<=10;i++)
{
sum=sum+(i*i*i)
}
out.print(“Total sum of cubes of 1 to 10:”+sum);
%>
Q10. Short note on JDBC
JDBC is a Java standard that provides the interface for connecting from Java to relational
databases. The JDBC standard is defined by Sun Microsystems and implemented through
the standard JDBC API.
JDBC stands for Java Database Connectivity, which is a standard Java API for database
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks commonly associated with database
usage:
 Making a connection to a database
58 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
 Creating SQL or MySQL statements
 Executing that SQL queries in the database
 Viewing & Modifying the resulting records
Java API that can access any kind of tabular data, especially data stored in a Relational
Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX.
JDBC provides object-oriented access to databases by defining classes and interfaces that
represent objects such as:
 Database Connections
 SQL Statements
 Result Set
 Database Metadata
 Prepared Statements
 Callable Statements
 Driver Manager
Q11. Explain JDBC architecture.
The JDBC API uses a Driver Manager and database precise drivers to provide clear
connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct
driver is used to access each data source.
The Driver Manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application:
The JDBC API supports both two-tier and three-tier processing models for database access
but in general JDBC Architecture consists of two layers:
The JDBC API is the top layer and is the programming interface in Java to structured query
language (SQL) which is the standard for accessing relational databases.
59 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
The JDBC API communicates with the JDBC Driver Manager API, sending it various SQL
statements. The manager communicates with the various third party drivers that actually
connect to the database and return the information from the query.
Q12. Explain the components of JDBC.
Following is list of common JDBC Components:
The JDBC API provides the following interfaces and classes:
DriverManager: This class manages a list of database drivers. It matches connection
requests from the java application with the proper database driver using communication sub
protocol. The first driver that recognizes a certain sub protocol under JDBC will be used to
establish a database Connection.
Driver: This interface handles the communications with the database server. We will interact
directly with Driver objects very rarely. Instead, we use DriverManager objects, which
manage objects of this type. It also abstracts the details associated with working with Driver
objects
Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is through
connection object only.
Statement: We use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
ResultSet: These objects hold data retrieved from a database after we execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its data.
SQLException: This class handles any errors that occur in a database application.
Q13. What is JDBC driver? Explain the types of JDBC Drivers.
The JDBC API defines the Java interfaces and classes that programmers use to connect to
databases and send queries. A JDBC driver implements these interfaces and classes for a
particular DBMS vendor.
The JDBC driver converts JDBC calls into a network or database protocol or into a database
library API call that makes communication with the database.
There are four types of JDBC drivers as follows:
Type 1- JDBC-ODBC Bridge Driver:
This driver converts JDBC API calls into Microsoft Open Database Connectivity (ODBC) calls
that are then passed to the ODBC driver. The ODBC binary code must be loaded on every
client computer that uses this type of driver.
Advantage: The JDBC-ODBC Bridge allows access to almost any database, since the
database's ODBC drivers are already available.
Disadvantages:
 The Bridge driver is not coded completely in Java; So Type 1 drivers are not portable.
 It is not good for the Web Application because it is not portable.
 It is comparatively slowest than the other driver types.
 The client system requires the ODBC Installation to use the driver.
60 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Type 2 - Native-API/ Partly Java Driver:
This driver converts JDBC API calls into DBMS precise client API calls. Similar to the bridge
driver, this type of driver requires that some binary code be loaded on each client computer.
Advantage:
This type of divers are normally offer better performance than the JDBC-ODBC Bridge as the
layers of communication are less than that it and also it uses Resident/Native API which is
Database specific.
Disadvantage:
 Mostly out of date now
 It is usually not thread safe.
 This API must be installed in the Client System; therefore this type of drivers cannot be used
for the Internet Applications.
 Like JDBC-ODBC Bridge drivers, it is not coded in Java which cause to portability issue.
 If we modify the Database then we also have to change the Native API as it is specific to a
database.
Type 3 - JDBC-Net/Pure Java Driver:
This driver sends JDBC API calls to a middle-tier Net Server that translates the calls into the
DBMS precise Network protocol. The translated calls are then sent to a particular DBMS.
Advantage:
61 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
 This type of drivers is the most efficient amongst all driver types.
 This driver is totally coded in Java and hence Portable. It is suitable for the web application.
 This driver is server based, so there is no need for any vendor database library to be present
on client machines.
 With this type of driver there are many opportunities to optimize portability, performance, and
scalability.
 The Net protocol can be designed to make the client JDBC driver very small and fast to load.
 This normally provides support for features such as caching, load balancing etc.
 This driver is very flexible allows access to multiple databases using one driver.
Disadvantage:
 This driver requires another server application to install and maintain.
 Traversing the record set may take longer, since the data comes through the back-end
server.
Type 4 - Native-protocol/Pure Java Driver:
This driver converts JDBC API calls directly into the DBMS precise network protocol without
a middle tier. This allows the client applications to connect directly to the database server.
Advantage:
 The Performance of this type of driver is normally quite good.
 This driver is completely written in Java to achieve platform independence and eliminate
deployment administration issues. It is most suitable for the web.
 In this driver numbers of translation layers are very less i.e. type 4 JDBC drivers don't need
to translate database requests to ODBC or a native connectivity interface or to pass the
request on to another server.
 We don’t need to install special software on the client or server.
 These drivers can be downloaded dynamically.
Disadvantage:
 With this type of drivers, the user needs a different driver for each database.
62 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q14. List the steps to connect database using JDBC with example.
Following are seven steps are used to connect database using JDBC.
 Import the package.
 Load the driver.
 Establish the connection
 Create the statement
 Excecute the statement
 Process the Result
 Close the connection
Example:
import java.sql.*; //Step1
class InsertPrepared
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Step2
Connection con=DriverManager.getConnection( "jdbc:odbc:Employee"); //Step3
Statement st = con.createStatement(); //Step4
String sql = "select * from Employee where Eno=101";
ResultSet rs = st.executeQuery(sql); //Step5
rs.next(); //Step6
System.out.print(rs.getInt(1) + "t");
System.out.print(rs.getString(2)+”t");
System.out.println(rs.getInt(3)));
con.close(); //Step7
}
}
catch(Exception e){ System.out.println(e);}
}
63 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q15. What is a Statement in JDBC? Explain the various kinds of statements that can be
created in JDBC.
A statement in JDBC is used to execute SQL queries after connecting to the database.
Three ways of executing a query:
 Standard Statement
 Prepared Statement
 Callable Statement
Standard Statement
 Statement objects are never instantiated directly.
 To do so, the createStatement () of Connection is used.
Statement stmt=dbcon.createStatement ()
ResultSet rs=stmt.executeQuery (“Select * from student”);
 A query that returns data can be executed using executeQuery () of Statement.
 This method executes the statement and returns ResultSet object that contains the resulting
data
 For inserts, updates, deletes use executeUpdate ().
PreparedStatement
PreparedStatement pstmt = con.preparedStatement (“Insert into student (fname,lname) values(?,?)”);
 PreparedStatement object is an SQL statement that is pre-compiled and stored.
 This object can then be executed multiple times much more efficiently than preparing and
issuing the same statement each time it is needed.
 The question marks represent dynamic query parameters. These parameters can be
changed each time the prepared statement is called.
CallableStatement
CallableStatement cstmt = con.prepareCall(“{call getBooks(?,?)}”);
 CallableStatement is used to execute SQL stored procedures.
 Methods are provided to specify input parameters and retrieve return values.
Q16. Write an exhaustive note on “PreparedStatement”. Attach code specification to
support your answer.
The PreparedStatement interface is a sub-interface of Statement. It is used to execute
parameterized query.
The performance of the application will be faster if we use PreparedStatement interface
because query is compiled only once. The prepareStatement () method of Connection
interface is used to return the object of PreparedStatement.
Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement.
In addition, it adds a set of methods that are needed for setting the values to be sent to the
database in place of the placeholders for IN parameters. Also, the three methods execute,
executeQuery, and executeUpdate are modified so that they take no argument.
Before a PreparedStatement object is executed, the value of each? Parameter must be set.
This is done by calling a setXXX method, where XXX is the appropriate type for the
parameter. The first argument to the setXXX methods is the ordinal position of the parameter
to be set, with numbering starting at 1. The second argument is the value to which the
parameter is to be set.
64 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Example of PreparedStatement interface that inserts the record:
import java.sql.*;
class InsertPrepared
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection( "jdbc:odbc:Employee");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setInt(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
catch(Exception e){ System.out.println(e);}
}
}
Q17. Write short note on “CallableStatement”. Attach code specification to support your
answer.
 CallableStatement interface is used to call the stored procedures and functions.
 We can have business logic on the database by the use of stored procedures and functions
that will make the performance better because these are precompiled.
 Suppose we need the get the age of the employee based on the date of birth, we may create
a function that receives date as the input and returns age of the employee as the output.
Below is stored procedure created in SQL Server to insert data.
create PROCEDURE Employee_Insert
(
@Eno INTEGER,
@Ename VARCHAR(10),
@Salary INTEGER
)
AS
BEGIN
insert into Employee values( @Eno, @Ename, @Salary)
END
Source Code:
import java.sql.*;
public class CallableStatement_Ex
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
65 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Connection con=DriverManager.getConnection("jdbc:odbc:Test");
System.out.println("Connection success");
CallableStatement stmt=con.prepareCall("{call Employee_Insert(?,?,?)}");
stmt.setInt(1,101);
stmt.setString(2,"Amit");
stmt.setInt(3,15000);
stmt.execute();
System.out.println("success");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Q18. Write a JDBC program that inserts values in database. [Table Name: Employee, Fileds
: Empid, Name, Dept, Designation]
import java.sql.*;
import java.io.*;
class JdbcDemo
{
public static void main(String args[])throws Exception
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:EmployeeDB");
Statement st = con.createStatement();
st.executeUpdate("insert into Employee (EmpID, Name, Dept , Designation) values
(5,’John’,'IT','Manager'));
}
catch(SQLException s){System.out.println(s);}
}
}
Q19. Short note on ResultSetMetaData.
JDBC Meta Data is the collective information about the data structure and property of a
column available in table. The Metadata of any table tells us the name of the columns,
datatype used in column and constraint used to enter the value of data into column of the
table.
It provides following methods.
executeQuery ( ): The method retrieves a record set from a table in database. The retrieve
record set is assigned to a result set.
66 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
getMetaData ( ): The Result Set call gets Metadata ( ), which return us the property of the
retrieve record set (length, field, and column).Meta Data account for data element and its
attribute.
getcolumncount ( ): The method returns us an integer data type and provides you the
number of column in the Result set object.
import java.sql.*;
class InsertPrepared
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection( "jdbc:odbc:Employee");
Statement st = con.createStatement();
String sql = "select * from person";
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
System.out.println("Table Name : " + metaData.getTableName(2));
System.out.println("Field tsizetDataType");
for (int i = 0; i < rowCount; i++)
{
System.out.print(metaData.getColumnName(i + 1) + "t");
System.out.print(metaData.getColumnDisplayS ize(i + 1)+"t");
System.out.println(metaData.getColumnTypeName(i + 1));
}
}
catch(Exception e){ System.out.println(e);}
}
67 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Unit-V
Topics:
Java Server Faces | Enterprise Java Beans
68 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q1.What is the concept of MVC Architecture?
Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following three
parts:
 Model - The lowest level of the pattern which is responsible for maintaining data.
 View - This is responsible for displaying all or a portion of the data to the user.
 Controller - Software Code that controls the interactions between the Model and View.
The MVC abstraction can be graphically represented as follows.
The model
The model is responsible for managing the data of the application. It responds to the request
from the view and it also responds to instructions from the controller to update itself.
The view
A presentation of data in a particular format, triggered by a controller's decision to present
the data. They are script based templating systems like JSP, ASP, PHP and very easy to
integrate with AJAX technology.
The controller
The controller is responsible for responding to user input and performs interactions on the
data model objects. The controller receives the input; it validates the input and then performs
the business operation that modifies the state of the data model.
Q2. What is facelet? What are its features?
 Facelets is commonly used term to refer to Java Server Faces View Definition Framework
which is page declaration language developed for use with Java server Faces technology.
 The concept of VDL introduced in JavaServer Faces 2.0 allows declaration of UI components
in different presentation technologies. Both JSP and Facelets are considered different
implementation of VDL.
69 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
 Facelet is built specifically for Java Server Faces. It is now the preferred technology for
building JavaServer Faces based applications and offers several advantages over using JSP
technology.
 Facelets is a powerful but lightweight page declaration language that is used to build
JavaServer Faces views using HTML style templates and to build component trees.
Facelets features include the following:
 Facelets as presentation technology.
 Templating and Composite Components through Facelets.
 New HTML tags for easier page creation.
 Bookmark ability to generate hyperlinks based on component properties at render time.
 New components and event types for additional functionality.
 Resource registration and relocation using annotations.
 Implicit Navigation Rules if none are present in the application configuration resource files.
 Support for Bean Validation.
 Project Stage to describe the status of the application in the project lifecycle.
 Support for Ajax Integration.
Q3. What is Java Server Faces? State its components.
 The JSF specification defines a set of standard UI components and provides an Application
Programming Interface (API) for developing components. JSF enables the reuse and
extension of the existing standard UI components.
 Java based Server Side User Interface Component Framework for building Java web
applications.
 Suited for use with applications based on Model View Controller (MVC)
 MVC design is separating the roles of Server Side Programmers, HTML code writers,
Graphic Designers.
 Standard Web Component Technology
 JSP and Servlets are not component based.
 Facelet is a term used to refer to JSF view definition Framework which is a page declaration
language.
JSF Components
 An API and reference implementation for representing UI components
 State management
 Server-side validation
 Data conversion
 Page navigation specification
 UI components like input fields, buttons, links etc.
 User input validations
 Easy error handling
 JavaBean management
 Event handling
 Tag libraries for expressing UI components
70 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271
Q4. Explain the lifecycle phases of JSF.
Below diagram shows the lifecycle of Java Server Faces (JSF) as follows
JSF application lifecycle consist of six phases which are as follows
 Restore view phase
 Apply request values phase
 Process validations phase
 Update model values phase
 Invoke application phase
 Render response phase
Phase 1: Restore view
JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives
a request.
During this phase, the JSF builds the view, wires event handlers and validators to UI
components and saves the view in the FacesContext instance. The FacesContext instance
will now contains all the information required to process a request.
Phase 2: Apply request values
After the component tree is created or restored each component in component tree uses
decodes method to extract its new value from the request parameters. Component stores
this value. If the conversion fails, an error message is generated and queued on
FacesContext. This message will be displayed during the render response phase, along with
any validation errors.
If any decode methods or event listeners called renderResponse on the current
FacesContext instance, the JSF moves to the render response phase.
Phase 3: Process validation
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit
Advance java for bscit

More Related Content

What's hot (7)

Androd Listeners
Androd ListenersAndrod Listeners
Androd Listeners
 
Web Design & Development - Session 6
Web Design & Development - Session 6Web Design & Development - Session 6
Web Design & Development - Session 6
 
Robotlegs Introduction
Robotlegs IntroductionRobotlegs Introduction
Robotlegs Introduction
 
P18030492101
P18030492101P18030492101
P18030492101
 
Layout manager
Layout managerLayout manager
Layout manager
 
Gui in java
Gui in javaGui in java
Gui in java
 
Android Lesson 3 - Intent
Android Lesson 3 - IntentAndroid Lesson 3 - Intent
Android Lesson 3 - Intent
 

Similar to Advance java for bscit

engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)jammiashok123
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingPayal Dungarwal
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intentPERKYTORIALS
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVASrajan Shukla
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in JavaAyesha Kanwal
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxusvirat1805
 
How to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptxHow to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptxFlutter Agency
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Javasuraj pandey
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxudithaisur
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandlingArati Gadgil
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024nehakumari0xf
 

Similar to Advance java for bscit (20)

Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
What is Event
What is EventWhat is Event
What is Event
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
How to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptxHow to use Listener Class in Flutter.pptx
How to use Listener Class in Flutter.pptx
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
Event handling
Event handlingEvent handling
Event handling
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 

More from YogeshDhamke2

Tybscit sem v nov 2015
Tybscit sem v nov 2015Tybscit sem v nov 2015
Tybscit sem v nov 2015YogeshDhamke2
 
Software testing main
Software testing mainSoftware testing main
Software testing mainYogeshDhamke2
 
solve pratical and imp quseation and solution for bscit
solve pratical and imp quseation and solution for bscitsolve pratical and imp quseation and solution for bscit
solve pratical and imp quseation and solution for bscitYogeshDhamke2
 
Network security main
Network security mainNetwork security main
Network security mainYogeshDhamke2
 
Most important questions_sem5
Most important questions_sem5Most important questions_sem5
Most important questions_sem5YogeshDhamke2
 
Hospital management synopsis
Hospital management synopsisHospital management synopsis
Hospital management synopsisYogeshDhamke2
 
Hospital management synopsis
Hospital management synopsisHospital management synopsis
Hospital management synopsisYogeshDhamke2
 
B.sc . i.t.-sem..-v-net-copy-may-2017
B.sc . i.t.-sem..-v-net-copy-may-2017B.sc . i.t.-sem..-v-net-copy-may-2017
B.sc . i.t.-sem..-v-net-copy-may-2017YogeshDhamke2
 
After effects data driven animation assets
After effects data driven animation assetsAfter effects data driven animation assets
After effects data driven animation assetsYogeshDhamke2
 
2016 sem 5 For tybscit
2016 sem 5 For tybscit2016 sem 5 For tybscit
2016 sem 5 For tybscitYogeshDhamke2
 
How.to.make.a.website.for.beginners
How.to.make.a.website.for.beginnersHow.to.make.a.website.for.beginners
How.to.make.a.website.for.beginnersYogeshDhamke2
 
Updated black book ice cream parlour word file For TYBSCIT
Updated black book ice cream parlour word file For TYBSCIT Updated black book ice cream parlour word file For TYBSCIT
Updated black book ice cream parlour word file For TYBSCIT YogeshDhamke2
 
Updated black book ice cream parlour TYBSCIT Final year project in PDF
Updated black book ice cream parlour TYBSCIT Final year project in PDFUpdated black book ice cream parlour TYBSCIT Final year project in PDF
Updated black book ice cream parlour TYBSCIT Final year project in PDFYogeshDhamke2
 
Project documentation format
Project documentation formatProject documentation format
Project documentation formatYogeshDhamke2
 
online-shopping-documentation-srs for TYBSCIT sem 6
 online-shopping-documentation-srs for TYBSCIT sem 6 online-shopping-documentation-srs for TYBSCIT sem 6
online-shopping-documentation-srs for TYBSCIT sem 6YogeshDhamke2
 
[[Srs]] online shopping website for TYBSC IT
[[Srs]] online shopping website for TYBSC IT[[Srs]] online shopping website for TYBSC IT
[[Srs]] online shopping website for TYBSC ITYogeshDhamke2
 

More from YogeshDhamke2 (19)

Tybscit sem v nov 2015
Tybscit sem v nov 2015Tybscit sem v nov 2015
Tybscit sem v nov 2015
 
Software testing main
Software testing mainSoftware testing main
Software testing main
 
solve pratical and imp quseation and solution for bscit
solve pratical and imp quseation and solution for bscitsolve pratical and imp quseation and solution for bscit
solve pratical and imp quseation and solution for bscit
 
Network security main
Network security mainNetwork security main
Network security main
 
Most important questions_sem5
Most important questions_sem5Most important questions_sem5
Most important questions_sem5
 
Hospital management synopsis
Hospital management synopsisHospital management synopsis
Hospital management synopsis
 
Hospital management synopsis
Hospital management synopsisHospital management synopsis
Hospital management synopsis
 
Basic tags
Basic tagsBasic tags
Basic tags
 
B.sc . i.t.-sem..-v-net-copy-may-2017
B.sc . i.t.-sem..-v-net-copy-may-2017B.sc . i.t.-sem..-v-net-copy-may-2017
B.sc . i.t.-sem..-v-net-copy-may-2017
 
Asp.net main
Asp.net mainAsp.net main
Asp.net main
 
After effects data driven animation assets
After effects data driven animation assetsAfter effects data driven animation assets
After effects data driven animation assets
 
html tags
 html tags html tags
html tags
 
2016 sem 5 For tybscit
2016 sem 5 For tybscit2016 sem 5 For tybscit
2016 sem 5 For tybscit
 
How.to.make.a.website.for.beginners
How.to.make.a.website.for.beginnersHow.to.make.a.website.for.beginners
How.to.make.a.website.for.beginners
 
Updated black book ice cream parlour word file For TYBSCIT
Updated black book ice cream parlour word file For TYBSCIT Updated black book ice cream parlour word file For TYBSCIT
Updated black book ice cream parlour word file For TYBSCIT
 
Updated black book ice cream parlour TYBSCIT Final year project in PDF
Updated black book ice cream parlour TYBSCIT Final year project in PDFUpdated black book ice cream parlour TYBSCIT Final year project in PDF
Updated black book ice cream parlour TYBSCIT Final year project in PDF
 
Project documentation format
Project documentation formatProject documentation format
Project documentation format
 
online-shopping-documentation-srs for TYBSCIT sem 6
 online-shopping-documentation-srs for TYBSCIT sem 6 online-shopping-documentation-srs for TYBSCIT sem 6
online-shopping-documentation-srs for TYBSCIT sem 6
 
[[Srs]] online shopping website for TYBSC IT
[[Srs]] online shopping website for TYBSC IT[[Srs]] online shopping website for TYBSC IT
[[Srs]] online shopping website for TYBSC IT
 

Recently uploaded

भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 

Recently uploaded (20)

भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 

Advance java for bscit

  • 1. 1 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Unit-I Topics: Event Handling | Abtract Window Toolkit
  • 2. 2 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q1. Explain the delegation event model in event handling.  Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism has the code which is known as event handler that is executed when an event occurs.  Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.  The Delegation Event Model has the following key participants namely: Events: In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Source: The source is an object on which event occurs. Source is responsible for providing information of the occurred event to its handler. Java provide as with classes for source object. Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For Example, the method that registers a keyboard event listener is called addKeyListener( ). Listener: It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received, the listener processes the event and then returns.  The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code Q2 List various the various Event classes and Event listener. Event classes Table enumerates the most important of these event classes and provides a brief description of when they are generated. Event Class Description ActionEvent Generated when a button is pressed, a list is double-clicked, or a menuitem is selected. AdjustmentEvent Generated when a scroll bar is manipulated. FocusEvent Generated when a component gains or loses keyboard focus. ItemEvent Generated when a check box or a list item is clicked; also occurs when achoice selection is made or a checkable menu is selected or deselected. KeyEvent Generated when input is received from the keyboard.
  • 3. 3 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component. TextEvent Generated when the value of a text area or text field is changed. WindowEvent Generated when a window os activated, closed, deactivated, deiconified,iconified, opened, or quit. Event Listener Following Table lists commonly used listener interfaces and provides a brief description of the methods that they define. Interface Description ActionListener Defines one method to receive action events. AdjustmentListener Defines one method to receive adjustment events ItemListener Defines one method to recognize when the state of an item changes. KeyListener Defines three methods to recognize when a key is pressed, released, or typed. MouseListener Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released. MouseMotionListener Defines two methods to recognize when the mouse is dragged or moved. TextListener Defines one method to recognize when a text value changes. WindowListener Defines seven methods to recognize when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit. Q3. Write a short note on “Event Listeners”. Explain the working with code specification. The event model is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source. Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects. Each event is represented by an object that gives information about the event and identifies the event source.
  • 4. 4 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 class Abc extends Frame implements ActionListener { Button ok,cancel; TextBox t1; Abc() { t1=new TextBox(); ok=new Button(“OK”); cancel=new Button(“CANCEL”); ok.addActionListener(this); cancel.addActionListener(this); add(ok); add(cancel); add(t1); } Public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand()==”OK”) t1.setText(“ You clicked OK button”) ; else if(ae.getActionCommand()==”CANCEL”) t1.setText(“You clicked Cancel button”); } public static void main(String arg[]) { new Abc();} } } Q4. Write a java program to handle the mouse related events. Example: import java.awt.*; import java.awt.event.*; public class MouseListenerEx extends Frame implements MouseListener { int x=0, y=0; String str= ""; MouseListenerEx (String title) { super(title); addWindowListener(new MyWindowAdapter(this)); addMouseListener(this); setSize(300,300); setVisible(true); } public void mouseClicked(MouseEvent e) {
  • 5. 5 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 str= "MouseClicked"; x = e.getX(); y = getY(); repaint(); } public void mousePressed(MouseEvent e) { str = "MousePressed"; x = e.getX(); y = getY(); repaint(); } public void mouseReleased(MouseEvent e) { str = "MouseReleased"; x = e.getX(); y = getY(); repaint(); } public void mouseEntered(MouseEvent e) { str= "MouseEntered"; x = e.getX(); y = getY(); repaint(); } public void mouseExited(MouseEvent e) { str = "MouseExited"; x = e.getX(); y = getY(); repaint(); } public void paint(Graphics g) { g.drawString(str + " at " + x + "," + y, 50,50); } public static void main(String[] args) { MouseListenerEx m= new MouseListenerEx ("Window With Mouse Events Example"); } } class MyWindowAdapter extends WindowAdapter {
  • 6. 6 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 MouseListenerEx myWindow = null; MyWindowAdapter(MouseListenerEx myWindow) { this.myWindow = myWindow; } public void windowClosing(WindowEvent we) { myWindow.setVisible(false); } } Q5. Write a short note on AWT The Abstract Window Toolkit (AWT) is class library provides a user interface toolkit called the Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible. At the lowest level, the operating system transmits information from the mouse and keyboard to the program as input, and provides pixels for program output. The AWT provides a well-designed object-oriented interface to these low-level services and resources. Because the Java programming language is platform-independent, the AWT must also be platform-independent. The AWT was designed to provide a common set of tools for graphical user interface design that work on a variety of platforms. The AWT classes are contained in the java.awt package. It is one of Java’s largest packages. We will list some of the AWT classes: Class Description Button Creates a push button control. Checkbox Creates a check box control. CheckboxGroup Creates a group of check box controls. Choice Creates a pop-up list. Color Manages colors in a portable, platform-independent fashion. FlowLayout The flow layout manager. Flow layout positions components left to right, top to bottom. Frame Creates a standard window that has a title bar, resize corners, and
  • 7. 7 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 a menu bar. GridLayout The grid layout manager. Grid layout displays components in a two-dimensional grid. Label Creates a label that displays a string. List Creates a list from which the user can choose. Similar to the standard Windows list box. ScrollPane A container that provides horizontal and/or vertical scroll bars for another component. TextArea Creates a multiline edit control. TextField Creates a single-line edit control. Q6. What are different operations that can be carried out on Frame Window? The class Frame is a top level window with border and title. It uses BorderLayout as default layout manager. Using below method various operation can be performed. Method Description setVisisble() Sets whether this frame is visible to user or not. setSize() Sets the size of frame in width and height setTitle() Sets the title for this frame to the specified string. setResizable() Sets whether this frame is resizable by the user. setMenuBar() Sets the menu bar for this frame to the specified menu bar. Example: import java.awt.*; import java.awt.event.*; public class FrameDemo extends Frame { Label l; public FrameDemo() { setLayout(new FlowLayout()); l=new Label(“Hello World”); setTitle("Frame Demo"); setSize(400,300); add(l); setVisible(true); } } public static void main(String ar[]) { FrameDemo f=new FrameDemo(); } }
  • 8. 8 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q7. With respect to AWT explain following controls: 1. Button 2. Checkbox 3. Choice 4. List 5. Scrollbar Button Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. Below example demonstrate use of Button in AWT: import java.awt.*; import java.awt.event.*; public class ButtonDemo extends Frame { Button b; public ButtonDemo() { setLayout(new FlowLayout()); b=new Button(“Click Here”); setTitle("Button Demo"); setSize(400,300); add(b); setVisible(true); } } public static void main(String ar[]) { ButtonDemo f=new ButtonDemo(); } } Checkbox Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing what the checkbox does.The state of a checkbox can be changed by clicking on it. Below example demonstrate use of Checkbox in AWT: import java.awt.*; import java.awt.event.*; public class CheckboxDemo extends Frame {
  • 9. 9 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Checkbox c1,c2,c3; Label l; public CheckboxDemo () { setLayout(new FlowLayout()); l=new Label(“Select Your Hobbies:”); c1=new Checkbox(“Cricket”); c2=new Checkbox(“Carrom”); c3=new Checkbox(“Football”); setTitle("Checkbox Demo"); setSize(400,300); add(l); add(c1); add(c2); add(c3); setVisible(true); } } public static void main(String ar[]) { CheckboxDemo f=new CheckboxDemo(); } } Choice Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu. Below example demonstrate use of Choice in AWT: import java.awt.*; import java.awt.event.*; public class ChoiceDemo extends Frame { Choice ddl; Label l; public ChoiceDemo () { setLayout(new FlowLayout()); l=new Label(“Select State:”); ddl=new Choice(); ddl.add(“Maharashtra”); ddl.add(“Uttar Pradesh”); ddl.add(“Goa”); ddl.add(“Gujrat”); setTitle("Choice Demo"); setSize(400,300); add(l); add(ddl);
  • 10. 10 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 setVisible(true); } } public static void main(String ar[]) { ChoiceDemo f=new ChoiceDemo (); } } List The List represents a list of text items. The list can be configured to that user can choose either one item or multiple items. Below example demonstrate use of List in AWT: import java.awt.*; import java.awt.event.*; public class ListDemo extends Frame { List lst; Label l; public ListDemo() { setLayout(new FlowLayout()); l=new Label(“Select Hobbies:”); lst=new List(4,true); lst.add(“Cricket”); lst.add(“Football”); lst.add(“Music”); lst.add(“Singing”); setTitle("List Demo"); setSize(400,300); add(l); add(lst); setVisible(true); } } public static void main(String ar[]) { ListDemo f=new ListDemo (); } } Scrollbar Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
  • 11. 11 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Below example demonstrate use of Scrollbar in AWT: import java.awt.*; import java.awt.event.*; public class ScrollbarDemo extends Frame { public ScrollbarDemo () { setLayout(new FlowLayout()); Scrollbar horizontalScroller = new Scrollbar(Scrollbar.HORIZONTAL); Scrollbar verticalScroller = new Scrollbar(); verticalScroller.setOrientation(Scrollbar.VERTICAL); horizontalScroller.setMaximum (100); horizontalScroller.setMinimum (1); verticalScroller.setMaximum (100); verticalScroller.setMinimum (1); setTitle("Scrollbar Demo"); setSize(400,300); add(horizontalScroller); add(verticalScroller); setVisible(true); } } public static void main(String ar[]) { ScrollbarDemo f=new ScrollbarDemo (); } } Q8. How does AWT create Radio Buttons? Explain with syntax and code specification. OR What is CheckBoxGroup? Explain with Example. The java AWT, top-level window, is represented by the CheckBoxGroup. In this program, we will see how to create and show the CheckboxGroup component on the frame. In below program a radio button is created that is an item that can be selected or deselected and displays that state to the user. Here we are creating a group of buttons in which we can select only one option at a time. CheckBoxGroup object=new CheckBoxGroup (); import java.awt.*; import java.awt.event.*; public class RadioButtonEx{ public static void main(String[] args) { Frame fm=new Frame("RedioButton Group"); Label la=new Label("What is your choice:"); fm.setLayout(new GridLayout(0, 1));
  • 12. 12 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 CheckboxGroup cg1=new CheckboxGroup(); fm.add(la); fm.add(new Checkbox("Maths", cg1, true)); fm.add(new Checkbox("Physics", cg1, false)); fm.add(new Checkbox("Chemistry", cg1, false)); fm.add(new Checkbox("English", cg1, false)); fm.setSize(250,200); fm.setVisible(true); fm.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } }); } } Output: Q9. What are adapter classes? Why are they used?  An adapter class provides the default implementation of all methods in an event listener interface. An adapter class provides an empty implementation of all methods in an event listener interface i.e. this class itself write definition for methods which are present in particular event listener interface.  Adapter classes are very useful when we want to process only few of the events that are handled by a particular event listener interface.  We can define a new class by extending one of the adapter classes and implement only those events relevant to us.  “Every listener that includes more than one abstract method has got a corresponding adapter class”. The advantage of adapter is that we can override any one or two methods we like instead of all.  Adapter classes are useful when we want to receive and process only some of the events that are handled by a particular event listener interface. For Example The MouseMotionAdapter class has 2 methods, mouseDragged( ) & mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If we were interested in only mouse drag events, then we could simply extend MouseMotionAdapter and override mouseDragged( ).
  • 13. 13 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 The empty implementation of mouseMoved( ) would handle the mouse motion events for us. Some of the Adapter classes are mentioned below. Adapter Classes KeyAdpater MouseAdapter MouseMotionAdapter WindowAdapter Example: import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="TAdapterDemo" width=300 height=100> </applet> */ public class TAdapterDemo extends Applet { public void init( ){ addMouseListener( new MouseAdapter( ){ int X, Y; public void mouseReleased(MouseEvent me){ X = me.getX( ); Y = me.getY( ); Graphics g = TAdapterDemo.this.getGraphics(); g.drawString("Mouse Realeased", X,Y); } }); } } Q10. What are inner classes? Explain with example  In object-oriented programming, an inner class or nested class is a class declared entirely within the body of another class or interface. It is distinguished from a subclass. So an inner class is a class defined within another class, or even within an expression.  Inner classes can be used to simplify the code when using event adapter classes as shown below. Example: class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } class Inner
  • 14. 14 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 { void display() { System.out.println("display: outer_x = " + outer_x); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } Q11. What are anonymous classes? Explain with example An anonymous inner class is one that is not assigned a name. This section illustrates how an anonymous inner class can facilitate the writing of event handlers. Consider the applet shown in the following listing. As before, its goal is to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse is pressed. Example import java.applet.*; import java.awt.event.*; /* <applet code="Abc" width=200 height=100> </applet> */ public class Abc extends Applet { public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } }); } } Q12. What are the different Layout Managers classes in java? Explain Card Layout With Example. This class support following various types of layout as follows. LayoutManager Description BorderLayout The BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. CardLayout The CardLayout object treats each component in the container as a card. Only one card is visible at a time. FlowLayout The FlowLayout is the default layout. It layouts the components
  • 15. 15 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 in a directional flow. GridLayout The GridLayout manages the components in form of a rectangular grid. CardLayout The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout. Constructors of CardLayout class: CardLayout (): creates a card layout with zero horizontal and vertical gap. CardLayout (int hgap, int vgap): creates a card layout with the given horizontal and vertical gap. Commonly used methods of CardLayout class: public void next(Container parent): is used to flip to the next card of the given container. public void previous(Container parent): is used to flip to the previous card of the given container. public void first(Container parent): is used to flip to the first card of the given container. public void last(Container parent): is used to flip to the last card of the given container. public void show(Container parent, String name): is used to flip to the specified card with the given name. Example: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CardLayoutExample extends JFrame implements ActionListener{ CardLayout card; JButton b1,b2,b3; Container c; CardLayoutExample(){ c=getContentPane(); card=new CardLayout(40,30); c.setLayout(card); b1=new JButton("Apple"); b2=new JButton("Boy"); b3=new JButton("Cat"); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); c.add("a",b1);c.add("b",b2);c.add("c",b3); } public void actionPerformed(ActionEvent e) { card.next(c);
  • 16. 16 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 } public static void main(String[] args) { CardLayoutExample cl=new CardLayoutExample(); cl.setSize(400,400); cl.setVisible(true); } } Output: GridLayout The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. Constructors of GridLayout class: GridLayout(): creates a grid layout with one column per component in a row. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps. Example: import java.awt.*; import javax.swing.*; public class GridLayoutEx{ JFrame f; GridLayoutEx(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7");
  • 17. 17 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new GridLayoutEx(); } } Output: FlowLayout The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel. Fields of FlowLayout class: public static final int LEFT public static final int RIGHT public static final int CENTER public static final int LEADING public static final int TRAILING Constructors of FlowLayout class: FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.
  • 18. 18 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap. Example: import java.awt.*; import javax.swing.*; public class FlowLayoutEx { JFrame f; FlowLayoutEx(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.setLayout(new FlowLayout(FlowLayout.RIGHT)); f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new FlowLayoutEx(); } } Output: Q13. Explain the Border layout used in java with the help of a program. OR What is the default layout of the Frame? Explain the same.  BorderLayout is the default layout manager for all Windows, such as Frames and Dialogs. It uses five areas to hold components: north, south, east, west, and center.  All extra space is placed in the center area. When adding a component to a container with a border layout, use one of these five constants.
  • 19. 19 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Example: import java.awt.*; import java.awt.event.*; public class BorderLayoutDemo extends Frame { Button b1,b2,b3,b4,b5; public BorderLayoutDemo() { BorderLayout b=new BorderLayout(); setLayout(b); b1=new Button("Center"); b2=new Button("South"); b3=new Button("North"); b4=new Button("East"); b5=new Button("West"); setTitle("Border Layout Example"); add(b1,BorderLayout.CENTER); add(b2,BorderLayout.SOUTH); add(b3,BorderLayout.NORTH); add(b4,BorderLayout.EAST); add(b5,BorderLayout.WEST); setSize(500,500); setVisible(true); } public static void main(String ar[]) { BorderLayoutDemo bl=new BorderLayoutDemo(); } } Output: Q14. Write a java AWT program that creates the following GUI. Code Sample: import java.awt.*; import java.awt.event.*;
  • 20. 20 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 public class Login extends Frame { Label l1,l2; TextField txtUser,txtPwd; Button b; public Login() { l1=new Label("User Name:"); l2=new Label("Password:"); txtUser=new TextField(15); txtPwd=new TextField(15); txtPwd.setEchoChar('#'); b=new Button("Login"); setLayout(new FlowLayout()); setSize(300,300); setTitle("Login Form"); add(l1); add(txtUser); add(l2); add(txtPwd); add(b); setVisible(true); } public static void main(String ar[]) { Login l=new Login(); } } Output:
  • 21. 21 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Unit-II Topics: Swing
  • 22. 22 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q1. What are swings in java? Explain the features of swing  Swing/JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications.  The swing API contains 100% pure java versions of the AWT components, plus many additional components that are also 100% pure java, because swing does not contain or depend on native code.  Swing is the package or set of classes that provide more powerful and flexible component than that of ‘AWT’.  It supplies several exiting addition including tabbed panes, trees and tables.  Even familiar component like buttons have more capabilities in swing i.e. buttons may have both image and text associated with it.  The hierarchy of java swing API is given below. Following are features of swing. Swing Components Are Lightweight This means that they are written entirely in Java and do not map directly to platform specific peers. Because lightweight components are rendered using graphics primitives, they can be transparent which enables non rectangular shapes. Thus, lightweight components are more efficient and more flexible. Swing Supports a Pluggable Look and Feel Each Swing component is rendered by Java code rather than by native peers, the look and feel of a component is under the control of Swing. It is possible to “plug in” a new look and feel for any given component without creating any side effects in the code that uses that component. The MVC Architecture
  • 23. 23 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 This is Essential feature of Swing that is using MVC we can change internal representation of table, trees and list. New Components There are various new components provided by swing which are as follows Image Button Tabbed Panes Sliders Toolbars Text Areas List Trees Tables Q2. Explain the new features of JFC. The JFC (Java Foundation Classes) are a set of GUI components and services which simplify the development and deployment of commercial quality of desktop and Internet or Intranet applications. Its features are: Java Foundation classes are core to the Java 2 Platform. All JFC components are JavaBeans components and therefore reusable, interoperable, and portable. JFC offers an open architecture. Third-party JavaBeans components can be used to enhance applications written using JFC. It is truly cross-platform. Q3. Compare Swing and AWT. There are many differences between java awt and swing that are given below. A.W.T Swing AWT components are platform-dependent. Java swing components are platform- independent AWT components are heavyweight. Swing components are lightweight AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel. AWT provides less components than Swing Swing provides more powerful components such as tables, lists. AWT doesn't follow MVC architecture. Swing follows MVC architecture. It does not consist of new components. It consists of new components such as Sliders, Tabbed Button, Toolbars and Tables and so on AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has very much richer functionality. Controls does not start with character J. In swing Controls start with character J. Ex. JButton , JTextFiled Q12. Write a java program using JCheckBox and JRadioButton.
  • 24. 24 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 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. Constructor of JRadioButton: JRadioButton(): creates an unselected radio button with no text. JRadioButton(String s): creates an unselected radio button with specified text. JRadioButton(String s, boolean selected): creates a radio button with the specified text and selected status. Example of JRadioButton with source code import javax.swing.*; import java.awt.*; import java.awt.event.*; class Xyz extends JFrame { JPanel jpl; JLabel lbl; JRadioButton rnd1,rnd2; ButtonGroup bgrp; Xyz() { jpl=new JPanel(); bgrp=new ButtonGroup(); lbl=new JLabel("Select Job Type:"); rnd1=new JRadioButton("Full Time"); rnd2=new JRadioButton("Part Time"); bgrp.add(rnd1); bgrp.add(rnd2); setTitle("JCheckbox Example"); setSize(300,300); jpl.add(lbl); jpl.add(rnd1); jpl.add(rnd2); add(jpl); setVisible(true); } } class JRadioButtonEx { public static void main(String ar[]) { Xyz x1=new Xyz(); } }
  • 25. 25 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 JCheckBox The JCheckBox class is used to create the checkbox and use can select multiple option. Constructor of JCheckBox: JCheckBox (): creates an unselected checkbox with no text. JCheckBox (String s): creates an unselected checkbox with specified text. Example of JCheckBox with source code import javax.swing.*; import java.awt.*; import java.awt.event.*; class Xyz extends JFrame { JPanel jpl; JCheckBox chk1,chk2; Xyz() { jpl=new JPanel(); chk1=new JCheckBox("Cricket"); chk2=new JCheckBox("Basketball"); setTitle("JCheckbox Example"); setSize(300,300); jpl.add(chk1); jpl.add(chk2); add(jpl); setVisible(true); } } class JCheckboxEx { public static void main(String ar[]) { Xyz x1=new Xyz(); } } Q4. Write a java SWING program that creates the JTree GUI. JTree is a Swing component with which we can display hierarchical data. JTree is quite a complex component. A JTree has a 'root node' which is the top-most parent for all nodes in the tree. A node is an item in a tree. A node can have many children nodes. These children nodes themselves can have further children nodes. If a node doesn't have any children node, it is called a leaf node. Example of JTree with source code
  • 26. 26 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 import javax.swing.*; import javax.swing.tree.*; import java.awt.event.*; class Abc extends JFrame { JTree tree; JPanel jpl; public Abc() { DefaultMutableTreeNode r=new DefaultMutableTreeNode("Course"); DefaultMutableTreeNode i=new DefaultMutableTreeNode("Bsc-IT"); DefaultMutableTreeNode cs=new DefaultMutableTreeNode("Bsc-CS"); r.add(i); r.add(cs); DefaultMutableTreeNode fi=new DefaultMutableTreeNode("FYIT"); DefaultMutableTreeNode si=new DefaultMutableTreeNode("SYIT"); DefaultMutableTreeNode ti=new DefaultMutableTreeNode("TYIT"); i.add(fi); i.add(si); i.add(ti); DefaultMutableTreeNode fcs=new DefaultMutableTreeNode("FYCS"); DefaultMutableTreeNode scs=new DefaultMutableTreeNode("SYCS"); DefaultMutableTreeNode tcs=new DefaultMutableTreeNode("TYCS"); cs.add(fcs); cs.add(scs); cs.add(tcs); tree=new JTree(r); jpl=new JPanel(); jpl.add(tree); add(jpl); setTitle("JTree Example"); setSize(500,500); setVisible(true); } class JTreeEx { public static void main(String ar[]) { Abc a1=new Abc(); } }
  • 27. 27 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Output: Q5. Write a java program to create different tabs using JTabbedPane. A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. With the JTabbedPane class, we can have several components, such as panels, share the same space. The user chooses which component to view by selecting the tab corresponding to the desired component Example of JTabbedPane with source code import javax.swing.*; class Abc extends JFrame { JPanel jpl; JTabbedPane jtp; JButton b1,b2; Abc() { jpl=new JPanel(); b1=new JButton("Button1"); b2=new JButton("Button2"); jtp=new JTabbedPane(2); jtp.add("Tap1",b1); jtp.add("Tap2",b2); jpl.add(jtp); setTitle("JFrame Example"); setSize(300,300); add(jpl); setVisible(true); } } class JTappedPaneEx {
  • 28. 28 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 public static void main(String ar[]) { Abc a1=new Abc(); } } Output: Q6. Explain JPopupMenu Class with Example Popup menu represents a menu which can be dynamically popped up at a specified position within a component. JPopupMenu Constructor JPopupMenu (): Constructs a JPopupMenu without an "invoker". JPopupMenu (String label): Constructs a JPopupMenu with the specified title. Example of JPopupMenu with source code import javax.swing.*; import java.awt.event.*; class Abc extends JFrame { JPopupMenu jpm; JMenuItem i1,i2,i3,i4; public Abc() { jpm=new JPopupMenu(); i1=new JMenuItem("New"); i2=new JMenuItem("Save"); i3=new JMenuItem("Open"); i4=new JMenuItem("Exit"); jpm.add(i1); jpm.add(i2); jpm.add(i3); jpm.add(i4); setTitle("JPopupMenu Example"); addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent me) { jpm.show(me.getComponent(),me.getX(),me.getY()); } } ); setSize(500,500); setVisible(true);
  • 29. 29 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 } } class JPopupMenuEx { public static void main(String ar[]) { Abc a1=new Abc(); } } Output: Q7. How are menus created in java? What are the classes used for creating menus? Explain with example. The JMenuBar class provides an implementation of a menu bar. For creating menu we use JMenuItem and JMenu classes. Example of JMenu with source code import javax.swing.*; import java.awt.*; class Abc extends JFrame { JMenuBar jmb; JMenu m1,m2; JMenuItem i1,i2,i3,i4; Abc() { jmb=new JMenuBar(); m1=new JMenu("File"); m2=new JMenu("Edit"); jmb.add(m1); jmb.add(m2);
  • 30. 30 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 i1=new JMenuItem("New"); i2=new JMenuItem("Save"); i3=new JMenuItem("Save As"); i4=new JMenuItem("Exit"); m1.add(i1); m1.add(i2); m1.add(i3); m1.add(i4); setLayout(new FlowLayout()); setTitle("JFrame Example"); setSize(300,300); setJMenuBar(jmb); setVisible(true); } } class JMenuBarEx { public static void main(String ar[]) { Abc a1=new Abc(); } } Output: Q8. Explain JScrollPane and JScrollBar with example. JScrollPane  It provides a scrollable view of a lightweight component. A JScrollPane manages a viewport, optional vertical and horizontal scroll bars, and optional row and column heading viewports.  JScrollPane does not support heavyweight components. JScrollBar  The JScrollBar lets the user graphically select a value by sliding a knob within a bounded interval.  It is us a very useful component when we want to display large amount of elements on the screen. Constructors:
  • 31. 31 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 JScrollBar ( ): It Creates a JScrollBar instance with a range of 0-100, an initial value of 0, and vertical orientation. JScrollBar (int Orientation): It creates a JScrollBar instance with a range of 0-100, an initial value of 0, and the specified orientation. Methods: getValue ( ) : It gives the current value of scroll bar. setMaximum (int Max) :The maximum value of the scrollbar is maximum – extent. setMinimum (int Min) : Returns the minimum value supported by the scrollbar (usually zero). setValue (int Value) :Sets the scrollbar's value. Example of JScrollPane with source code import javax.swing.*; import java.awt.*; import java.awt.event.*; class Xyz extends JFrame { JPanel jpl; JLabel lbl; JTextArea txtAdd; JScrollPane jsp; Xyz() { String str="Plase mention address here"; jpl=new JPanel(); lbl=new JLabel("Address:"); txtAdd=new JTextArea(str,6,16); jsp=new JScrollPane(txtAdd); setTitle("JCheckbox Example"); setSize(300,300); jpl.add(lbl); jpl.add(jsp); add(jpl); setVisible(true); } } class JScrollPaneEx { public static void main(String ar[]) { Xyz x1=new Xyz(); } } Q9. Explain JColorChooser with example. The JColorChooser class is used to create a color chooser dialog box so that user can select any color. JPopupMenu Constructor
  • 32. 32 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 JColorChooser (): is used to create a color chooser pane with white color initially. JColorChooser (Color c): is used to create a color chooser pane with the specified color initially. Example of JColorChooser with source code import javax.swing.*; import java.awt.*; import java.awt.event.*; class Abc extends JFrame implements ActionListener { JButton b; JPanel jpl; Abc() { b=new JButton("Color"); b.addActionListener(this); jpl=new JPanel(); setTitle("JColorChooser Example"); setSize(300,300); jpl.add(b); add(jpl); setVisible(true); } public void actionPerformed(ActionEvent e) { Color initialcolor=Color.RED; Color color=JColorChooser.showDialog(this,"Select a color",initialcolor); setBackground(color); } } class JColorChooserEx { public static void main(String ar[]) { Abc a1=new Abc(); } } Output:
  • 33. 33 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q10. How do divide frame window in 2 parts? Explain with code specification. The JSplitPane is commonly used component because it lets we want split our window horizontally or vertically in order to create a wide variety of GUI elements to suit our application’s needs. In short in order to create a JSplitPane component in Java, one should follow these steps:  Create a new JFrame.  Call setLayout(new FlowLayout()) to set flow layout for the frame.  Create two String arrays that will containt the contents of the two areas of theJSplitPane.  Create two JScrollPane components.  Create a new JSplitPane with the above JScrollPane components in each side.  Use frame.getContentPane().add(splitPane) to add the spilt pane to our frame Example of JMenu with source code import java.awt.*; import javax.swing.*; class Abc extends JFrame { JPanel p1,p2; Abc() { String[] options1 = { "Bird", "Cat", "Dog", "Rabbit", "Pig" }; JComboBox combo1 = new JComboBox(options1); String[] options2 = { "Car", "Motorcycle", "Airplane", "Boat" }; JComboBox combo2 = new JComboBox(options2); p1 = new JPanel(); p1.add(combo1); p2 = new JPanel(); p2.add(combo2); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, p1, p2); setTitle("Split Pane Example"); setSize(200, 200); setLayout(new FlowLayout());
  • 34. 34 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 add(splitPane); setVisible(true); } } class JSplitPaneEx { public static void main(String[]ar) { Abc a1=new Abc(); } } Output: Q11. How to denote the user about the software loading process? Which component is facilitating the same? Explain with code specification. This is the class which creates the progress bar using its constructor JProgressBar () to show the status of our process completion. The constructor JProgressBar() takes two argument as parameter in which, first is the initial value of the progress bar which is shown in the starting and another argument is the counter value by which the value of the progress bar is incremented. setStringPainted(boolean): This is the method of the JProgressBar class which shows the complete process in percent on the progress bar. It takes a Boolean value as a parameter. If we pass the true then the value will be seen on the progress bar otherwise not seen. setValue(): This is the method of the JProgressBar class which sets the value to the progress bar. Timer (): This constructor takes two arguments as parameter first is the interval (in milliseconds) of the timer and second one is the listener object. Time is started using the start () method of the Timer class. Example of JProgressBar with source code import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class ProgressSample { public static void main(String args[]) {
  • 35. 35 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 JFrame f = new JFrame("JProgressBar Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JProgressBar progressBar = new JProgressBar(); progressBar.setValue(25); progressBar.setStringPainted(true); Border border = BorderFactory.createTitledBorder("Reading..."); progressBar.setBorder(border); f.add(progressBar, BorderLayout.NORTH); f.setSize(300, 100); f.setVisible(true); } }
  • 36. 36 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Unit-III Topics: Servlet & Working with Servlet
  • 37. 37 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q1. What are servlets? What are advantages of using servlets?  Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server.  Using Servlets, we can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.  Following diagram shows the position of Servlets in a Web Application.  Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification.  Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition  Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI. Advantages of servlet  Performance is significantly better.  Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.  Servlets are platform-independent because they are written in Java.  Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.  The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software. Q2. What is servlet? What are different tasks carried out by servlets? Servlets perform the following major tasks:  Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.  Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.  Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.  Send the explicit data to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
  • 38. 38 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271  Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. Q3. What is CGI? What are the disadvantages of CGI? CGI (Common Gateway Interface)  CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process. Common Gateway Interface) Disadvantages of CGI  The biggest disadvantage of CGI programming is lack of scalability and reduced speed. Each time a request is received by the Web server, an entirely new process thread is created.  It uses platform dependent language e.g. C, C++, Perl.  If number of client’s increases, it takes more time for sending response.  For each request, it starts a process and Web server is limited to start processes.  A process thread consume a lot of server side resources especially in multi –user situation  Difficult for beginners to program modules in this environment  Sharing resources such as data base connections between scripts or multi cells to the same scripts was not available, leading to repeated execution of expensive operation. Q4. Explain the life cycle of servlet Life Cycle of a Servlet The web container maintains the life cycle of a servlet instance. The life cycle of the servlet conists of following phases as folows:  Servlet class is loaded.  Servlet instance is created.  init method is invoked.  service method is invoked.  destroy method is invoked. Below diagram shows the life-cycle of servlet as follows.
  • 39. 39 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 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 destroy () method, it shifts to the end state. Servlet class is loaded The class loader 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. 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. init method is invoked The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below: public void init(ServletConfig config) throws ServletException service method is invoked The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below: public void service(ServletRequest req, ServletResponse res) throws ServletException destroy method is invoked
  • 40. 40 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: public void destroy()throws ServletException Q5. Short note on Servlet API Servlet API consists of 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. The javax.servlet package Interfaces Classes Servlet GenericServlet ServletRequest ServletInputStream ServletResponse ServletOutputStream RequestDispatcher ServletException ServletConfig ServletContextEvent ServletContext UnavailableException The javax.servlet.http package Interfaces Classes HttpServletRequest HttpServlet HttpServletResponse Cookie HttpSession HttpSessionEvent HttpSessionListener Q6. Explain the structure of web.xml file with respect to servlet. Below example demonstrate the structure of web.xml with respect to servlet. <web-app>> <servlet> <servlet-name>hello</servlet-name> <servlet-class>test.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app> The <servlet> tag configures the servlet. In our simple example, we just need to specify the class name for the servlet. The <servlet-mapping> tag specifies the URLs which will invoke the servlet. In our case, the /hello URL invokes the servlet.
  • 41. 41 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q7. Explain the web application directory structure. Below diagram shows the web application directory structure. The root directory, we can put all files that should be accessible in our web application. For instance, if our web application is mapped to the URL. The WEB-INF directory is located just below the web app root directory. This directory is a Meta information directory. Files stored in here are not supposed to be accessible from a browser. Inside the WEB-INF directory there are two important directories. These are described below. The web.xml file contains information about the web application, which is used by the Java web server / servlet container in order to properly deploy and execute the web application. The classes directory contains all compiled Java classes that are part of our web application. The lib directory contains all JAR files used by our web application. This directory most often contains any third party libraries that our application is using. Q8. Explain GenericServlet with its constructors and methods. GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method. GenericServlet class can handle any type of request so it is protocol-independent. It consists of following methods. Method Description init(ServletConfig config) Returns the parameter value for the specified parameter name. service(ServletRequest request, ServletResponse response) Returns the names of the context's initialization parameters. destroy() Sets the given object in the application scope. getServletConfig() Returns the attribute for the specified name. getServletInfo() Removes the attribute with the given name from the servlet context. getServletName() It returns the name of the servlet object. Q9. What is request Dispatcher? What are its two methods?
  • 42. 42 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271  The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.  This interface can also be used to include the content of another resource also. It is one of the ways of servlet collaboration.  There are two methods defined in the RequestDispatcher interface. They are: Method Description forward() Forwards a request from a servlet to another resource (servlet, JSP file, or HTML) on the server. include () Includes the content of a resource (servlet, JSP page, or HTML file) in the response. As we see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user. As we can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client. Q10. Explain the ServletConfig interface in java.  An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file.  If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.  The core advantage of ServletConfig is that we don't need to edit the servlet file if information is modified from the web.xml file. It consists of following methods.
  • 43. 43 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Method Description getInitParameter(String name) Returns the parameter value for the specified parameter name. getInitParameterNames() Returns the names of the context's initialization parameters. getServletName() Returns the name of the servlet. getServletContext() Returns an object of ServletContext. Q11. Why do we need the ServletContext interface in java?  All Servlets belong to one ServletContext which can be called at context initialisation time.  It enables applications to load servlets at run time.  It contains methods to communicate with the server:  Finding path information  Accessing other servlets running on the server  It used for writing to server log file. There can be a lot of usage of ServletContext object. Some of them are as follows:  The object of ServletContext provides an interface between the container and servlet.  The ServletContext object can be used to get configuration information from the web.xml file.  The ServletContext object can be used to set, get or remove attribute from the web.xml file.  The ServletContext object can be used to provide inter-application communication. It consists of following methods. Method Description getInitParameter(String name) Returns the parameter value for the specified parameter name. getInitParameterNames() Returns the names of the context's initialization parameters. setAttribute(String name, Object obj) Sets the given object in the application scope. getAttribute(String name) Returns the attribute for the specified name. removeAttribute(String name) Removes the attribute with the given name from the servlet context. Q12. What are HTTPServletRequest and HTTPServletResponse? HttpServletRequest and HttpServletResponse classes are just extensions of ServletRequest and ServletResponse with HTTP-specific information stored in them. HTTPServletRequest
  • 44. 44 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271  It extends the ServletRequest interface to provide request information for HTTP servlets. The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).  The request object is an instance of a javax.servlet.http.HttpServletRequest object.  It consists of following methods. Method Description getCookies() Returns an array containing all of the Cookie objects the client sent with this request. getAttributeNames() Returns an Enumeration containing the names of the attributes available to this request. getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. getContentType() Returns the MIME type of the body of the request, or null if the type is not known. getParameter(String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. HTTPServletResponse  It provides methods for extracting HTTP parameters from the query string or the request body depending on type of request GET or POST.  The response object is an instance of a javax.servlet.http.HttpServletResponse object.  It consists of following methods. Method Description addCookies() Adds the specified cookie to the response. sendRedirect(String location) Sends a temporary redirect response to the client using the specified redirect location URL. setContentType(String type) Sets the content type of the response being sent to the client, if the response has not been committed yet. setStatus(int sc) Sets the status code for this response. getParameter(String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. Q13. Short note on HTTPSession.  Session simply means a particular interval of time.  Session Tracking is a way to maintain state (data) of a user. It is also known as session management in servlet.  Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of a user to recognize to particular user.  HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
  • 45. 45 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 An object of HttpSession can be used to perform two tasks:  Bind objects  View and manipulate information about a session, such as the session identifier, creation time, and last accessed time  It consists of following methods. Method Description getId() Returns a string containing the unique identifier value. getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. getLastAccessedTime() Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. Source Code HttpSession session=request.getSession(false); String n= (String)session.getAttribute("uname"); Q14. What is a cookie? How to create and use in servlet. A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user. Types of Cookie There are 2 types of cookies in servlets. Non-persistent cookie Persistent cookie
  • 46. 46 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. Persistent cookie It is valid for multiple sessions. It is not removed each time when user closes the browser. It is removed only if user logout or sign out. Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage of Cookies  It will not work if cookie is disabled from the browser.  Only textual information can be set in Cookie object. Creation of cookie Cookie ck=new Cookie("user","Allwin");//creating cookie object response.addCookie(ck);//adding cookie in the response Retrieving information from cookie Cookie ck[]=request.getCookies(); for(int i=0;i<ck.length;i++) { out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie } Deletion of cookie Cookie ck=new Cookie("user","");//deleting value of cookie ck.setMaxAge(0);//changing the maximum age to 0 seconds response.addCookie(ck);//adding cookie in the response Q15. Write a servlet program to display the factorial of a given number. Home.html <html> <head> <title>Factorial</title> </head> <body> <form method="get" action="FactorialServlet"> <table> <tr><td>Enter a value to find its factorial</td><td><input type="text" name="text1"/></td></tr> <tr><td></td><td><input type="submit" value="ok"/></td></tr> </table> </form> </body> </html> FactorialServlet.java
  • 47. 47 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 package Factorial import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FactorialServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int num = Integer.parseInt(request.getParameter("text1")); out.println(this.fact(num)); } long fact(long a) { if (a <= 1) return 1; else { a = a * fact(a - 1); return a; } } }
  • 48. 48 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Unit-IV Topics: Java Server Pages(JSP) | JDBC
  • 49. 49 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q1. What is JSP? What are advantages and disadvantages of JSP?  JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.  A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application.  Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.  Using JSP, we can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.  JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc. Advantages of JSP:  HTML friendly simple and easy language and tags  Supports java code  Supports standard web site development tools  Rich UI features  Much Java knowledge is not required Disadvantages  As JSP pages are translated into servlet and compiled, it is difficult to trace the errors occurred in JSP page  JSP pages requires double the disk spaces  JSP requires more time to execute when it is accessed for the first time Q2. Write the advantages of JSP over Servlet. There are many advantages of JSP over servlet. These are as follows:  JSP is the extension to the servlet technology. We can use all the features of 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.  JSP can be easily managed because we can easily separate our business logic with presentation logic.  In servlet, we mix our business logic with the presentation logic.  If JSP page is modified, we don't need to redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.  Nobody can borrow the code  Faster loading of pages  No browser compatibility issues Q3. Explain the life cycle of JSP Page. A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
  • 50. 50 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 The following are the paths followed by a JSP  Compilation  Initialization  Execution  Cleanup The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows: JSP Compilation: When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. JSP Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method: public void jspInit() { // Initialization code... } JSP Execution: Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows: void _jspService(HttpServletRequest request,HttpServletResponse response) {
  • 51. 51 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 // Service handling code... } JSP Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. jspDestroy method used when we need to perform any cleanup, such as releasing database connections or closing open files. The jspDestroy() method has the following form: public void jspDestroy() { // cleanup code goes here. } Q4. Explain the JSP document and various component reslated to it. There are many component of JSP document. These are as follows:  JSP Directives  JSP Declaration  JSP Expression  JSP Scriptlet  JSP Comment  JSP Action Tag JSP Directives The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet. There are three types of directives: page directive include directive taglib directive Syntax of JSP Directive <%@ directive attribute="value" %> JSP Declaration The JSP declaration tag is used to declare fields and methods. The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet.
  • 52. 52 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 The syntax of the declaration tag is as follows: <%! field or method declaration %> Example: <html> <body> <%! int data=50; %> <%= "Value of the variable is:"+data %> </body> </html> <html> <body> <%! int cube(int n){ return n*n*n*; } %> <%= "Cube of 3 is:"+cube(3) %> </body> </html> JSP Expresssion The code placed within JSP expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method. Syntax of JSP expression tag <%= statement %> Example: <html> <body> <%= "welcome to jsp" %> </body> </html> JSP Scriptlet In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the scripting elements first. A scriptlet tag is used to execute java source code in JSP. Syntax is as follows: <% java source code %> Example: <html> <body>
  • 53. 53 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 <% out.print("welcome to jsp"); %> </body> </html> JSP Comment JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. Following is the syntax of JSP comments: <%-- This is JSP comment --%> Example: <html> <head><title>A Comment Test</title></head> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html> JSP Action Tag There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks. The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are given below. Q5. Explain the <jsp: include> and <jsp: forward> element used in JSP. The <jsp: include> Action This action lets you insert files into the page being generated. The syntax looks like this: <jsp: include page="relative URL" flush="true" />
  • 54. 54 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested. Following is the lists of attributes associated with include action: Attribute Purpose page The relative URL of the page to be included. flush The Boolean attribute determines whether the included resource has its buffer flushed before it is included. Example: Date.jsp <p> Today's date: <%= (new java.util.Date()).toString()%> </p> Main.jsp <html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:include page="date.jsp" flush="true" /> </center> </body> </html> The <jsp: forward> Action The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet. The simple syntax of this action is as follows <jsp: include page="relative URL" flush="true" /> Following is the lists of attributes associated with include action: Attribute Purpose page The relative URL of the page to be included. flush The Boolean attribute determines whether the included resource has its buffer flushed before it is included. Example: Date.jsp <p>
  • 55. 55 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Today's date: <%= (new java.util.Date()).toString()%> </p> Main.jsp <html> <head> <title>The include Action Example</title> </head> <body> <center> <h2>The include action Example</h2> <jsp:forward page="Date.jsp" flush="true" /> </center> </body> </html> Q6. Explain different types of directives used in JSP JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form: <%@ directive attribute="value" %> There are three types of directive tag: Directive Description <%@ page ... %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. <%@ include ... %> Includes a file during the translation phase <%@ taglib ... %> Declares a tag library, containing custom actions, used in the page The page Directive: The page directive is used to provide instructions to the container that pertain to the current JSP page. Attributes: Following is the list of attributes associated with page directive: Attribute Purpose language Defines the programming language used in the JSP page. import Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes. extends Specifies a superclass that the generated servlet must extend contentType Defines the character encoding scheme. errorPage Defines the URL of another JSP that reports on Java unchecked runtime exceptions. session Specifies whether or not the JSP page participates in HTTP sessions
  • 56. 56 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Include Directive: Include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. The general usage form of this directive is as follows: <%@ include file="relative url" > The filename in the include directive is actually a relative URL. If we just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as our JSP. The taglib Directive: The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page. The taglib directive follows the following syntax: <%@ taglib uri="uri" prefix="prefixOfTag" > Q7. How can you add a bean to a JSP page? The jsp: useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is already created, it doesn't create the bean depending on the scope. Syntax of jsp: useBean action tag <jsp: useBean id= "instanceName" scope= "page | request | session | application” class= "packageName.className" type= "packageName.className” > </jsp: useBean> Attributes and Usage of jsp: useBean action tag  Id: is used to identify the bean in the specified scope.  Scope: represents the scope of the bean. It may be page, request, session or application. The default scope is page.  Class: instantiates the specified bean class but it must have no-argument or no constructor and must not be abstract. Example package MyPackage; public class Calculator{ public int cube(int n){return n*n*n;} } index.jsp file <jsp:useBean id="obj" class="com.javatpoint.Calculator"/> <% int m=obj.cube(5); out.print("cube of 5 is "+m); %>  To access the properties of bean, the syntax is as follows: <jsp:getProperty name=”BeanName” property=”PropertyName” />  To set the properties of bean, the syntax is as follows: <jsp:setProperty name=”BeanName” property=”PropertyName” value=”Newvalue”/>
  • 57. 57 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q8. Explain any 5 implicit objects used in JSP. Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables. JSP supports following Implicit Objects which are listed below: Object Description request This is the HttpServletRequest object associated with the request. response This is the HttpServletResponse object associated with the response to the client. out This is the PrintWriter object used to send output to the client. session This is the HttpSession object associated with the request. application This is the ServletContext object associated with application context. config This is the ServletConfig object associated with the page. pageContext This encapsulates use of server-specific features like higher performance JspWriters. page This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. Q9. Write a JSP application that computes the cubes of the numbers from 1 to 10. Simple code is expected with the output. Source Code: <% int i,sum=0; for (i=1;i<=10;i++) { sum=sum+(i*i*i) } out.print(“Total sum of cubes of 1 to 10:”+sum); %> Q10. Short note on JDBC JDBC is a Java standard that provides the interface for connecting from Java to relational databases. The JDBC standard is defined by Sun Microsystems and implemented through the standard JDBC API. JDBC stands for Java Database Connectivity, which is a standard Java API for database independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage:  Making a connection to a database
  • 58. 58 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271  Creating SQL or MySQL statements  Executing that SQL queries in the database  Viewing & Modifying the resulting records Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. JDBC provides object-oriented access to databases by defining classes and interfaces that represent objects such as:  Database Connections  SQL Statements  Result Set  Database Metadata  Prepared Statements  Callable Statements  Driver Manager Q11. Explain JDBC architecture. The JDBC API uses a Driver Manager and database precise drivers to provide clear connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The Driver Manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application: The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers: The JDBC API is the top layer and is the programming interface in Java to structured query language (SQL) which is the standard for accessing relational databases.
  • 59. 59 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 The JDBC API communicates with the JDBC Driver Manager API, sending it various SQL statements. The manager communicates with the various third party drivers that actually connect to the database and return the information from the query. Q12. Explain the components of JDBC. Following is list of common JDBC Components: The JDBC API provides the following interfaces and classes: DriverManager: This class manages a list of database drivers. It matches connection requests from the java application with the proper database driver using communication sub protocol. The first driver that recognizes a certain sub protocol under JDBC will be used to establish a database Connection. Driver: This interface handles the communications with the database server. We will interact directly with Driver objects very rarely. Instead, we use DriverManager objects, which manage objects of this type. It also abstracts the details associated with working with Driver objects Connection: This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only. Statement: We use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures. ResultSet: These objects hold data retrieved from a database after we execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. SQLException: This class handles any errors that occur in a database application. Q13. What is JDBC driver? Explain the types of JDBC Drivers. The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor. The JDBC driver converts JDBC calls into a network or database protocol or into a database library API call that makes communication with the database. There are four types of JDBC drivers as follows: Type 1- JDBC-ODBC Bridge Driver: This driver converts JDBC API calls into Microsoft Open Database Connectivity (ODBC) calls that are then passed to the ODBC driver. The ODBC binary code must be loaded on every client computer that uses this type of driver. Advantage: The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Disadvantages:  The Bridge driver is not coded completely in Java; So Type 1 drivers are not portable.  It is not good for the Web Application because it is not portable.  It is comparatively slowest than the other driver types.  The client system requires the ODBC Installation to use the driver.
  • 60. 60 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Type 2 - Native-API/ Partly Java Driver: This driver converts JDBC API calls into DBMS precise client API calls. Similar to the bridge driver, this type of driver requires that some binary code be loaded on each client computer. Advantage: This type of divers are normally offer better performance than the JDBC-ODBC Bridge as the layers of communication are less than that it and also it uses Resident/Native API which is Database specific. Disadvantage:  Mostly out of date now  It is usually not thread safe.  This API must be installed in the Client System; therefore this type of drivers cannot be used for the Internet Applications.  Like JDBC-ODBC Bridge drivers, it is not coded in Java which cause to portability issue.  If we modify the Database then we also have to change the Native API as it is specific to a database. Type 3 - JDBC-Net/Pure Java Driver: This driver sends JDBC API calls to a middle-tier Net Server that translates the calls into the DBMS precise Network protocol. The translated calls are then sent to a particular DBMS. Advantage:
  • 61. 61 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271  This type of drivers is the most efficient amongst all driver types.  This driver is totally coded in Java and hence Portable. It is suitable for the web application.  This driver is server based, so there is no need for any vendor database library to be present on client machines.  With this type of driver there are many opportunities to optimize portability, performance, and scalability.  The Net protocol can be designed to make the client JDBC driver very small and fast to load.  This normally provides support for features such as caching, load balancing etc.  This driver is very flexible allows access to multiple databases using one driver. Disadvantage:  This driver requires another server application to install and maintain.  Traversing the record set may take longer, since the data comes through the back-end server. Type 4 - Native-protocol/Pure Java Driver: This driver converts JDBC API calls directly into the DBMS precise network protocol without a middle tier. This allows the client applications to connect directly to the database server. Advantage:  The Performance of this type of driver is normally quite good.  This driver is completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.  In this driver numbers of translation layers are very less i.e. type 4 JDBC drivers don't need to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server.  We don’t need to install special software on the client or server.  These drivers can be downloaded dynamically. Disadvantage:  With this type of drivers, the user needs a different driver for each database.
  • 62. 62 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q14. List the steps to connect database using JDBC with example. Following are seven steps are used to connect database using JDBC.  Import the package.  Load the driver.  Establish the connection  Create the statement  Excecute the statement  Process the Result  Close the connection Example: import java.sql.*; //Step1 class InsertPrepared { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Step2 Connection con=DriverManager.getConnection( "jdbc:odbc:Employee"); //Step3 Statement st = con.createStatement(); //Step4 String sql = "select * from Employee where Eno=101"; ResultSet rs = st.executeQuery(sql); //Step5 rs.next(); //Step6 System.out.print(rs.getInt(1) + "t"); System.out.print(rs.getString(2)+”t"); System.out.println(rs.getInt(3))); con.close(); //Step7 } } catch(Exception e){ System.out.println(e);} }
  • 63. 63 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q15. What is a Statement in JDBC? Explain the various kinds of statements that can be created in JDBC. A statement in JDBC is used to execute SQL queries after connecting to the database. Three ways of executing a query:  Standard Statement  Prepared Statement  Callable Statement Standard Statement  Statement objects are never instantiated directly.  To do so, the createStatement () of Connection is used. Statement stmt=dbcon.createStatement () ResultSet rs=stmt.executeQuery (“Select * from student”);  A query that returns data can be executed using executeQuery () of Statement.  This method executes the statement and returns ResultSet object that contains the resulting data  For inserts, updates, deletes use executeUpdate (). PreparedStatement PreparedStatement pstmt = con.preparedStatement (“Insert into student (fname,lname) values(?,?)”);  PreparedStatement object is an SQL statement that is pre-compiled and stored.  This object can then be executed multiple times much more efficiently than preparing and issuing the same statement each time it is needed.  The question marks represent dynamic query parameters. These parameters can be changed each time the prepared statement is called. CallableStatement CallableStatement cstmt = con.prepareCall(“{call getBooks(?,?)}”);  CallableStatement is used to execute SQL stored procedures.  Methods are provided to specify input parameters and retrieve return values. Q16. Write an exhaustive note on “PreparedStatement”. Attach code specification to support your answer. The PreparedStatement interface is a sub-interface of Statement. It is used to execute parameterized query. The performance of the application will be faster if we use PreparedStatement interface because query is compiled only once. The prepareStatement () method of Connection interface is used to return the object of PreparedStatement. Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. In addition, it adds a set of methods that are needed for setting the values to be sent to the database in place of the placeholders for IN parameters. Also, the three methods execute, executeQuery, and executeUpdate are modified so that they take no argument. Before a PreparedStatement object is executed, the value of each? Parameter must be set. This is done by calling a setXXX method, where XXX is the appropriate type for the parameter. The first argument to the setXXX methods is the ordinal position of the parameter to be set, with numbering starting at 1. The second argument is the value to which the parameter is to be set.
  • 64. 64 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Example of PreparedStatement interface that inserts the record: import java.sql.*; class InsertPrepared { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection( "jdbc:odbc:Employee"); PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)"); stmt.setInt(1,101);//1 specifies the first parameter in the query stmt.setInt(2,"Ratan"); int i=stmt.executeUpdate(); System.out.println(i+" records inserted"); con.close(); } catch(Exception e){ System.out.println(e);} } } Q17. Write short note on “CallableStatement”. Attach code specification to support your answer.  CallableStatement interface is used to call the stored procedures and functions.  We can have business logic on the database by the use of stored procedures and functions that will make the performance better because these are precompiled.  Suppose we need the get the age of the employee based on the date of birth, we may create a function that receives date as the input and returns age of the employee as the output. Below is stored procedure created in SQL Server to insert data. create PROCEDURE Employee_Insert ( @Eno INTEGER, @Ename VARCHAR(10), @Salary INTEGER ) AS BEGIN insert into Employee values( @Eno, @Ename, @Salary) END Source Code: import java.sql.*; public class CallableStatement_Ex { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  • 65. 65 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Connection con=DriverManager.getConnection("jdbc:odbc:Test"); System.out.println("Connection success"); CallableStatement stmt=con.prepareCall("{call Employee_Insert(?,?,?)}"); stmt.setInt(1,101); stmt.setString(2,"Amit"); stmt.setInt(3,15000); stmt.execute(); System.out.println("success"); } catch(Exception e) { System.out.println(e); } } } Q18. Write a JDBC program that inserts values in database. [Table Name: Employee, Fileds : Empid, Name, Dept, Designation] import java.sql.*; import java.io.*; class JdbcDemo { public static void main(String args[])throws Exception { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:EmployeeDB"); Statement st = con.createStatement(); st.executeUpdate("insert into Employee (EmpID, Name, Dept , Designation) values (5,’John’,'IT','Manager')); } catch(SQLException s){System.out.println(s);} } } Q19. Short note on ResultSetMetaData. JDBC Meta Data is the collective information about the data structure and property of a column available in table. The Metadata of any table tells us the name of the columns, datatype used in column and constraint used to enter the value of data into column of the table. It provides following methods. executeQuery ( ): The method retrieves a record set from a table in database. The retrieve record set is assigned to a result set.
  • 66. 66 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 getMetaData ( ): The Result Set call gets Metadata ( ), which return us the property of the retrieve record set (length, field, and column).Meta Data account for data element and its attribute. getcolumncount ( ): The method returns us an integer data type and provides you the number of column in the Result set object. import java.sql.*; class InsertPrepared { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection( "jdbc:odbc:Employee"); Statement st = con.createStatement(); String sql = "select * from person"; ResultSet rs = st.executeQuery(sql); ResultSetMetaData metaData = rs.getMetaData(); int rowCount = metaData.getColumnCount(); System.out.println("Table Name : " + metaData.getTableName(2)); System.out.println("Field tsizetDataType"); for (int i = 0; i < rowCount; i++) { System.out.print(metaData.getColumnName(i + 1) + "t"); System.out.print(metaData.getColumnDisplayS ize(i + 1)+"t"); System.out.println(metaData.getColumnTypeName(i + 1)); } } catch(Exception e){ System.out.println(e);} }
  • 67. 67 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Unit-V Topics: Java Server Faces | Enterprise Java Beans
  • 68. 68 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q1.What is the concept of MVC Architecture? Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts:  Model - The lowest level of the pattern which is responsible for maintaining data.  View - This is responsible for displaying all or a portion of the data to the user.  Controller - Software Code that controls the interactions between the Model and View. The MVC abstraction can be graphically represented as follows. The model The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself. The view A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology. The controller The controller is responsible for responding to user input and performs interactions on the data model objects. The controller receives the input; it validates the input and then performs the business operation that modifies the state of the data model. Q2. What is facelet? What are its features?  Facelets is commonly used term to refer to Java Server Faces View Definition Framework which is page declaration language developed for use with Java server Faces technology.  The concept of VDL introduced in JavaServer Faces 2.0 allows declaration of UI components in different presentation technologies. Both JSP and Facelets are considered different implementation of VDL.
  • 69. 69 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271  Facelet is built specifically for Java Server Faces. It is now the preferred technology for building JavaServer Faces based applications and offers several advantages over using JSP technology.  Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following:  Facelets as presentation technology.  Templating and Composite Components through Facelets.  New HTML tags for easier page creation.  Bookmark ability to generate hyperlinks based on component properties at render time.  New components and event types for additional functionality.  Resource registration and relocation using annotations.  Implicit Navigation Rules if none are present in the application configuration resource files.  Support for Bean Validation.  Project Stage to describe the status of the application in the project lifecycle.  Support for Ajax Integration. Q3. What is Java Server Faces? State its components.  The JSF specification defines a set of standard UI components and provides an Application Programming Interface (API) for developing components. JSF enables the reuse and extension of the existing standard UI components.  Java based Server Side User Interface Component Framework for building Java web applications.  Suited for use with applications based on Model View Controller (MVC)  MVC design is separating the roles of Server Side Programmers, HTML code writers, Graphic Designers.  Standard Web Component Technology  JSP and Servlets are not component based.  Facelet is a term used to refer to JSF view definition Framework which is a page declaration language. JSF Components  An API and reference implementation for representing UI components  State management  Server-side validation  Data conversion  Page navigation specification  UI components like input fields, buttons, links etc.  User input validations  Easy error handling  JavaBean management  Event handling  Tag libraries for expressing UI components
  • 70. 70 | Salvi College Prof: Sonu Raj |sonuraj681@gmail.com | 8080837038 |8976249271 Q4. Explain the lifecycle phases of JSF. Below diagram shows the lifecycle of Java Server Faces (JSF) as follows JSF application lifecycle consist of six phases which are as follows  Restore view phase  Apply request values phase  Process validations phase  Update model values phase  Invoke application phase  Render response phase Phase 1: Restore view JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request. During this phase, the JSF builds the view, wires event handlers and validators to UI components and saves the view in the FacesContext instance. The FacesContext instance will now contains all the information required to process a request. Phase 2: Apply request values After the component tree is created or restored each component in component tree uses decodes method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors. If any decode methods or event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase. Phase 3: Process validation