AdvancedJava By Anwat sir
AdvancedJava By Anwat sir
Unit-I
Abstract Window Toolkit & Swing
A. Introduction
AWT Classes
1 Component
A Component is an abstract super class for GUI controls and it represents any object
of its subclasses with graphical representation.
2 Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as containers such
as Frame, Dialog and Panel.
3 Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
4 Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc
5 Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
6 Label
A Label object is a component for placing text in a container.
7 Button
This class creates a labeled button.
8 Check Box
A check box is a graphical component that can be in either an on (true) or off (false) state.
11 Text Field
A TextField object is a text component that allows for the editing of a single line of text.
12 Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of text.
13 Choice
A Choice control is used to show pop up menu of choices. Selected choice is shown on the
top of the menu.
15 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.
16 Dialog
A Dialog control represents a top-level window with a title and a border used to take some
form of input from the user.
17 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.
Windows Fundamental:
The two most common windows are those derived from Panel, which is used by applets, and those
derived from Frame, which creates a standard application window. Following are the window fundamental
classes used to create top level windows that can open on OS desktops or Web Browsers and hold
other components and containers.
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class that
encapsulates all of the attributes of a visual component. All user interface elements that are displayed on
the screen and that interact with the user are subclasses of Component. It defines over a hundred
public methods.
Container
The Container class is a subclass of Component. It has additional methods that allow other
Component objects to be nested within it. A container is responsible for laying out (that is, positioning)
any components that it contains. It does this through the use of various layout managers.
Panel
The Panel class is a concrete subclass of Container. Panel is the super class for Applet. When screen
output is directed to an applet, it is drawn on the surface of a Panel object. A Panel is a window that
does not contain a title bar, menu bar, or border. Other components can be added to a Panel object by
its add( ) method.
Window
The Window class creates a top-level window. Atop-level window is not contained within any other
object; it sits directly on the desktop. Generally, you won‟t create Window objects directly. Instead, you
will use a subclass of Window called Frame, described next.
Frame
Frame is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. Frame
class is used to create standard top level windows that can open on desktop. It provides more
features than Window class to design a standard GUI application window.
newFrame.setTitle("Nikita Education");
newFrame.setSize(500,500);
newFrame.setVisible(true);
}
}
/* <applet code="MyAppletFrame.class"
Height=500 Width=500></applet> */
Implements event
4. Frame close event handler for
WindowEvent
import java.awt.*;
import java.awt.event.*;
public class FrameCloseEvent extends Frame implements WindowListener{
public FrameCloseEvent(){
setTitle("Frame Window");
Handler
setSize(500,500);
setVisible(true); registration with
addWindowListener(this); source i.e. Frame
}
public void windowClosing(WindowEvent we){
System.exit(0); Event handler
} method defines
public void windowOpened(WindowEvent we){} action steps
public void windowClosed(WindowEvent we){}
public void windowIconified(WindowEvent we){}
public void windowDeiconified(WindowEvent we){}
public void windowActivated(WindowEvent we){} It is compulsory to
public void windowDeactivated(WindowEvent we){} define all the
public static void main(String [] args){ methods of interface
FrameCloseEvent newFrame=new FrameCloseEvent(); in its subclass
}
}
C. AWT Controls
Controls are components that allow a user to interact with your application in various ways. All AWT
controls are placed inside a container and a layout manager automatically positions components within
a container. Thus, the appearance of a window is determined by a combination of the controls that it
contains and the layout manager used to position them. The AWT supports the following types of
controls: Labels, Push buttons, Check boxes, Choice lists, Lists, Scroll bars, Text editing etc.
These controls are subclasses of Component class. The HeadlessException is thrown by all AWT
Controls.
C.1. Adding and Removing Controls inside a container i.e. Frame or Panel
To show control in a window, you must add it to the Frame or Panel. To do this, you must first
create an instance of the desired control and then add it to a window by calling add( )
method, which is defined by Container class.
Component add(Component compObj)
void remove(Component obj)
C.2. Standard Steps to Add Controls inside a container i.e. Frame or Panel:
D. Label
import java.awt.*;
import java.awt.event.*;
public class LabelDemo extends Frame{
public LabelDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
E. Button
Button(String text)
Constructs a new button with specified label.
String getActionCommand()
Returns the command name of the action event fired by this button.
String getLabel()
Gets the label of this button.
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame implements ActionListener{
String msg = "";
Button yes, no, maybe;
public ButtonDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
F. Checkbox
Checkbox(String label)
Creates a check box with the specified label.
CheckboxGroup getCheckboxGroup()
Determines this check box's group.
String getLabel()
Gets the label of this check box.
boolean getState()
Determines whether this check box is in the on or off state.
void setCheckboxGroup(CheckboxGroup g)
Sets this check box's group to the specified check box group.
import java.awt.*;
import java.awt.event.*;
public class CheckboxDemo extends Frame implements ItemListener{
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public CheckboxDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie){
repaint();
}
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 50, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 50, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 50, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 50, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 50, 160);
}
public static void main(String [] args){
CheckboxDemo obj1=new CheckboxDemo();
}
}
G. CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one and only one check box in
the group can be checked at any one time. These check boxes are often called radio buttons.
Checkbox getSelectedCheckbox()
Gets the current choice from this check box group.
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupDemo extends Frame
implements ItemListener{
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;
public CheckboxGroupDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
H. Choice
void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this Choice menu.
int getItemCount()
Returns the number of items in this Choice menu.
int getSelectedIndex()
Returns the index of the currently selected item.
String getSelectedItem()
Gets a representation of the current choice as a string.
import java.awt.*;
import java.awt.event.*;
public class ChoiceDemo extends Frame implements ItemListener{
Choice os, browser;
String msg = "";
public ChoiceDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
os = new Choice();
browser = new Choice();
I. List
List(int rows)
Creates a new scrolling list initialized with the specified number of visible lines.
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this list.
void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this list.
int getItemCount()
Gets the number of items in the list.
String[] getItems()
Gets the items in the list.
int getSelectedIndex()
Gets the index of the selected item on the list,
int[] getSelectedIndexes()
Gets the selected indexes on the list.
String getSelectedItem()
Gets the selected item on this scrolling list.
String[] getSelectedItems()
Gets the selected items on this scrolling list.
import java.awt.*;
import java.awt.event.*;
public class ListDemo extends Frame implements ActionListener{
List os, browser;
String msg = "";
public ListDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
os = new List(4, true);
browser = new List(4, false);
J. Scrollbar
Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll
bars may be oriented horizontally or vertically. A scroll bar is actually a composite of several individual
parts such as min & max value, slider box, arrow keys, initial value etc. Scrollbar control
represents a scroll bar component in order to enable user to select from range of values.
Scrollbar(int orientation)
Constructs a new scroll bar with the specified orientation.
Scrollbar(int orientation, int value, int visible, int minimum, int maximum)
Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and
maximum values.
int getBlockIncrement()
Gets the block increment of this scroll bar.
int getMaximum()
Gets the maximum value of this scroll bar.
int getMinimum()
Gets the minimum value of this scroll bar.
int getUnitIncrement()
Gets the unit increment for this scrollbar.
int getValue()
Gets the current value of this scroll bar.
void setBlockIncrement(int v)
Sets the block increment for this scroll bar.
void setMinimum(int newMinimum): Sets the minimum value of this scroll bar.
void setUnitIncrement(int v)
Sets the unit increment for this scroll bar.
import java.awt.*;
import java.awt.event.*;
public class ScrollbarDemo extends Frame
implements AdjustmentListener, MouseMotionListener{
Scrollbar vertSB, horzSB;
String msg = "";
public ScrollbarDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new BorderLayout());
add(vertSB,BorderLayout.EAST);
add(horzSB,BorderLayout.SOUTH);
// register to receive adjustment events
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
// Update scroll bars to reflect mouse dragging.
public void mouseDragged(MouseEvent me) {
int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me){}
public void paint(Graphics g)
{
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 50, 450);
// show current mouse drag position
g.drawString(">>>>>", horzSB.getValue(),
vertSB.getValue());
}
public static void main(String [] args){
ScrollbarDemo obj1=new ScrollbarDemo();
}
}
K. TextField
TextField(int columns)
Constructs a new empty text field with the specified number of columns.
TextField(String text)
Constructs a new text field initialized with the specified text.
int getColumns()
Gets the number of columns in this text field.
char getEchoChar()
Gets the character that is to be used for echoing.
void setEchoChar(char c)
Sets the echo character for this text field.
void setText(String t)
Sets the text that is presented by this text component to be the specified text.
String getSelectedText( )
void select(int startIndex, int endIndex)
import java.awt.*;
import java.awt.event.*;
public class TextFieldDemo extends Frame implements
ActionListener{
TextField name, pass;
public TextFieldDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('*');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 50, 100);
g.drawString("Selected text in name: "+
name.getSelectedText(), 50, 120);
g.drawString("Password:"+pass.getText(), 50, 140);
}
public static void main(String [] args){
TextFieldDemo obj1=new TextFieldDemo();
}
}
L. TextArea
TextArea(String text)
Constructs a new text area with the specified text.
int getColumns()
Returns the number of columns in this text area.
int getRows()
Returns the number of rows in the text area.
import java.awt.*;
import java.awt.event.*;
public class TextAreaDemo extends Frame{
TextField name, pass;
public TextAreaDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
String val =
"Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.\n" +
"Building on a rich heritage, Java has advanced both\n" +
"the art and science of computer language design.\n\n" +
"One of the reasons for Java's ongoing success is its\n" +
"constant, steady rate of evolution. Java has never stood\n" +
"still. Instead, Java has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +
"Moreover, Java has often led the way, charting the\n" +
"course for others to follow.";
M. Layout Manager
A layout manager automatically arranges your controls within a window by using some type of
algorithm Sometimes device to device size information gets changed then manual placement of
components become tedious. A layout manager is an instance of any class that implements the
LayoutManager interface. The layout manager is set by the setLayout( ) method.
FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
GridLayout
The GridLayout manages the components in form of a rectangular grid.
CardLayout
The CardLayout object treats each component in the container as a card. Only one card is visible at a
time.
GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout aligns the component
vertically,horizontally or along their baseline without requiring the components of same size.
N. BorderLayout
BorderLayout is the default layout manager for Window means for Frame. The BorderLayout class
implements a common layout style for top-level windows. It has four narrow, fixed-width components
at the edges and one large area in the center. The four sides are referred to as north, south, east,
and west. The middle area is called the center.
BorderLayout(int hgap, int vgap): Constructs a border layout with the specified gaps between
components.
import java.awt.*;
import java.awt.event.*;
public class BorderLayoutDemo extends Frame implements ActionListener
{
Label l1,l2;
TextField t1;
Button yes, no;
String msg="";
public BorderLayoutDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new BorderLayout());
l1=new Label("This is NORTH");
l1.setAlignment(Label.CENTER);
t1=new TextField("This is CENTER");
l2=new Label("This is SOUTH");
l2.setAlignment(Label.CENTER);
yes = new Button("This is EAST");
no = new Button("This is WEST");
add(l1,BorderLayout.NORTH);
add(t1,BorderLayout.CENTER);
add(l2,BorderLayout.SOUTH);
add(yes,BorderLayout.EAST);
add(no,BorderLayout.WEST);
yes.addActionListener(this);
no.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {}
public static void main(String [] args){
BorderLayoutDemo obj1=new BorderLayoutDemo();
}
}
O. FlowLayout
FlowLayout is the default layout manager for Panel means for Applet. FlowLayout implements a
simple layout style, which is similar to how words flow in a text editor. Adds components from left to
right, top to bottom. components are laid out line-by-line beginning at the upper-left corner. In all
cases, when a line is filled, layout advances to the next line.
O.1. Important Constants
static int CENTER -- This value indicates that each row of components should be centered.
static int LEADING -- This value indicates that each row of components should be justified to the
leading edge of the container's orientation, for example, to the left in left-to-right orientations.
static int LEFT -- This value indicates that each row of components should be left-justified.
static int RIGHT -- This value indicates that each row of components should be right-justified.
static int TRAILING -- This value indicates that each row of components should be justified to the
trailing edge of the container's orientation, for example, to the right in left-to-right orientations.
FlowLayout(int align)
Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical
gap.
import java.awt.*;
import java.awt.event.*;
public class FlowLayoutDemo extends Frame implements ActionListener{
Label l1,l2;
TextField t1,t2;
Button yes, no, maybe;
String msg="";
public FlowLayoutDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
FlowLayout obj=new FlowLayout(FlowLayout.CENTER);
setLayout(obj);
l1=new Label("Enter Name");
t1=new TextField(25);
l2=new Label("Enter Password");
t2=new TextField(25);
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(l1);
add(t1);
add(l2);
add(t2);
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")){
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 100, 250);
}
public static void main(String [] args){
FlowLayoutDemo obj1=new FlowLayoutDemo();
}
}
P. GridLayout
GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout, you
define the number of rows and columns. The class GridLayout arranges components in a rectangular
grid.
import java.awt.*;
import java.awt.event.*;
public class GridLayoutDemo extends Frame{
public GridLayoutDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new GridLayout(4,4));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
int k = (i * 4) + j;
if(k > 0)
add(new Button("" + k));
}
}
}
public static void main(String [] args){
GridLayoutDemo obj1=new GridLayoutDemo();
}
}
Q. CardLayout
The CardLayout class is unique among the other layout managers in that it stores several different
layouts. Each layout can be thought of as being on a separate index card in a deck that can be
shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional
components that can be dynamically enabled and disabled upon user input. You can prepare the other
layouts and have them hidden, ready to be activated when needed.
import java.awt.*;
import java.awt.event.*;
public class CardLayoutDemo extends Frame implements ActionListener,
MouseListener{
Checkbox winXP, winVista, solaris, mac;
Panel osCards;
CardLayout cardLO; Clicked on windows button
Button Win, Other;
public CardLayoutDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
Win = new Button("Windows");
Other = new Button("Other"); Clicked on other button
add(Win);
add(Other);
cardLO = new CardLayout();
osCards = new Panel();
osCards.setLayout(cardLO);
// set panel layout to card layout
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// add Windows check boxes to a panel
Panel winPan = new Panel();
winPan.add(winXP);
winPan.add(winVista);
// add other OS check boxes to a panel
Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);
// add panels to card deck panel
osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");
// add cards to main applet panel
add(osCards);
// register to receive action events
Win.addActionListener(this);
Other.addActionListener(this);
// register mouse events
addMouseListener(this);
}
public void mousePressed(MouseEvent me) {
cardLO.next(osCards);
}
// Provide empty implementations for the other MouseListener methods.
public void mouseClicked(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void mouseReleased(MouseEvent me) {}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource().equals(Win)) {
cardLO.show(osCards, "Windows");
}
else {
cardLO.show(osCards, "Other");
}
}
public static void main(String [] args){
CardLayoutDemo obj1=new CardLayoutDemo();
}
}
R. GridBagLayout
import java.awt.*;
import java.awt.event.*;
public class AwtLayoutDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;
public AwtLayoutDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo();
awtLayoutDemo.showGridBagLayoutDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Nikita Education [NET]");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
Nikita Education ( NET ) [ 9689925884 ] 26
Basics of Advance Java API
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showGridBagLayoutDemo(){
headerLabel.setText("Layout in action: GridBagLayout");
Panel panel = new Panel();
panel.setBackground(Color.darkGray);
panel.setSize(300,300);
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new Button("Button 1"),gbc);
gbc.gridx = 1;
gbc.gridy = 0;
panel.add(new Button("Button 2"),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
panel.add(new Button("Button 3"),gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(new Button("Button 4"),gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
panel.add(new Button("Button 5"),gbc);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
A top-level window can have a menu bar associated with it. A menu bar displays a list of top-level
menu choices. Each choice is associated with a drop-down menu. This concept is implemented in the
AWT by the following classes: MenuBar, Menu, and MenuItem. In general, a menu bar contains one
or more Menu objects. Each Menu object contains a list of MenuItem objects. Each MenuItem object
represents something that can be selected by the user. To create menu based application using above
classes perform following steps:
o Create instance of MenuBar
o Set menubar on container i.e. Frame using setMenuBar(MenuBar obj)
o Create instances of top level menus using Menu class
o Create instances of menu items using MenuItem class
o Add MenuItem into the Menu using add(MenuItem obj)
o Add Menu into MenuBar using add(MenuItem obj)
MenuComponent
It is the top level class for all menu related controls.
MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
Menu
The Menu object is a pull-down menu component which is displayed from the menu bar.
CheckboxMenuItem
CheckboxMenuItem is subclass of MenuItem.
S.1. MenuBar
The MenuBar class provides menu bar bound to a frame and is platform specific.
S.1.1. Constructors
MenuBar()
Creates a new menu bar.
S.1.2. Methods
Menu add(Menu m)
Adds the specified menu to the menu bar.
Menu getMenu(int i)
Gets the specified menu.
int getMenuCount()
Gets the number of menus on the menu bar.
void remove(MenuComponent m)
Removes the specified menu component from this menu bar.
void setHelpMenu(Menu m)
Sets the specified menu to be this menu bar's help menu.
S.2. Menu
The Menu class represents pull-down menu component which is deployed from a menu bar.
S.2.1. Constructors
Menu(): Constructs a new menu with an empty label.
Menu(String label)
Constructs a new menu with the specified label.
S.2.2. Methods
MenuItem add(MenuItem mi)
Adds the specified menu item to this menu.
void addSeparator()
Adds a separator line, or a hypen, to the menu at the current position.
int getItemCount()
Get the number of items in this menu.
void removeAll()
Removes all items from this menu.
S.3. MenuItem
The MenuBar class represents the actual item in a menu. All items in a menu should derive from class
MenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.
S.3.1. Constructors
MenuItem()
Constructs a new MenuItem with an empty label and no keyboard shortcut.
MenuItem(String label)
Constructs a new MenuItem with the specified label and no keyboard shortcut.
S.3.2. Methods
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this menu item.
void deleteShortcut()
Delete any MenuShortcut object associated with this menu item.
String getActionCommand()
Gets the command name of the action event that is fired by this menu item.
String getLabel()
Gets the label for this menu item.
boolean isEnabled()
Checks whether this menu item is enabled.
void setEnabled(boolean b)
Sets whether or not this menu item can be chosen.
void setShortcut(MenuShortcut s)
Set the MenuShortcut object associated with this menu item.
S.4. CheckboxMenuItem
The CheckboxMenuItem class represents a check box which can be included in a menu. Selecting the
check box in the menu changes control's state from on to off or from off to on.
S.4.1. Constructors
CheckboxMenuItem(label)
Create a check box menu item with the specified label.
S.4.2. Methods
void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box menu item.
boolean getState(): Determines whether the state of this check box menu item is "on" or "off."
void setState(boolean b)
Sets this check box menu item to the specifed state.
import java.awt.*;
import java.awt.event.*;
class MyMenuHandler implements ActionListener, ItemListener{
MenuDemo menuFrame;
public MyMenuHandler(MenuDemo menuFrame){
this.menuFrame = menuFrame;
}
mbar=new MenuBar();
setMenuBar(mbar);
file=new Menu("File");
item1=new MenuItem("New.....");
file.add(item1);
item2=new MenuItem("Open.....");
file.add(item2);
item3=new MenuItem("Close.....");
file.add(item3);
item4=new MenuItem("-");
file.add(item4);
item5=new MenuItem("Quit.....");
file.add(item5);
mbar.add(file);
edit=new Menu("Edit");
item6=new MenuItem("Cut");
edit.add(item6);
item7=new MenuItem("Copy");
edit.add(item7);
item8=new MenuItem("Paste");
edit.add(item8);
item9=new MenuItem("-");
edit.add(item9);
sub=new Menu("Special");
item10=new MenuItem("First");
sub.add(item10);
item11=new MenuItem("Second");
sub.add(item11);
item12=new MenuItem("Third");
sub.add(item12);
edit.add(sub);
if(debug.getState())
g.drawString("Debug is on.", 50, 220);
else
g.drawString("Debug is off.", 50, 220);
if(test.getState())
g.drawString("Testing is on.", 50, 240);
else
g.drawString("Testing is off.", 50, 240);
}
public static void main(String [] args){
MenuDemo obj1=new MenuDemo();
}
}
T.1. Dialog
Dialog boxes are primarily used to obtain user input and are often child windows of a top-level window.
Dialog boxes don‟t have menu bars. Dialog boxes may be modal or modeless. When a modal dialog
box is active, all input is directed to it until it is closed. This means that you cannot access other parts of
your program until you have closed the dialog box. When a modeless dialog box is active, input focus
can be directed to another window in your program. Thus, other parts of your program remain active and
accessible. Dialog boxes are of type Dialog. It is used to take some form of input from the user. It
inherits the Window class. Unlike Frame, it doesn't have maximize and minimize buttons.
T.1.1. Constructors
Dialog(Frame owner)
Constructs an initially invisible, modeless Dialog with the specified owner Frame and an empty title.
T.1.2. Methods
String getTitle()
Gets the title of the dialog.
boolean isModal()
Indicates whether the dialog is modal.
void setModal(boolean modal): Specifies whether this dialog should be modal.
void setTitle(String title): Sets the title of the Dialog.
void setVisible(boolean b): Shows or hides this Dialog depending on the value of parameter b.
T.2. FileDialog
Java provides a built-in dialog box that lets the user specify a file. To create a file dialog box, instantiate
an object of type FileDialog. This causes a file dialog box to be displayed. Usually, this is the standard
file dialog box provided by the operating system. FileDialog control represents a dialog window from
which the user can select a file.
T.2.1. Constants
static int LOAD -- This constant value indicates that the purpose of the file dialog window is to
locate a file from which to read.
static int SAVE -- This constant value indicates that the purpose of the file dialog window is to
locate a file to which to write.
T.2.2. Constructors
FileDialog(Frame parent)
Creates a file dialog for loading a file.
T.2.2. Methods
String getDirectory()
Gets the directory of this file dialog.
String getFile()
Gets the selected file of this file dialog.
int getMode()
Indicates whether this file dialog box is for loading from a file or for saving to a file.
//Program 1: MenuDemo.java
import java.awt.*;
import java.awt.event.*;
public class MenuDemo extends Frame{
String msg = "";
MenuBar mbar;
Menu file, edit, sub;
MenuItem item1, item2, item3, item4, item5;
MenuItem item6, item7, item8, item9;
mbar=new MenuBar();
setMenuBar(mbar);
file=new Menu("File");
item1=new MenuItem("New.....");
file.add(item1);
item2=new MenuItem("Open.....");
file.add(item2);
item3=new MenuItem("Close.....");
file.add(item3);
item4=new MenuItem("-");
file.add(item4);
item5=new MenuItem("Quit.....");
file.add(item5);
mbar.add(file);
edit=new Menu("Edit");
item6=new MenuItem("Cut");
edit.add(item6);
item7=new MenuItem("Copy");
edit.add(item7);
item8=new MenuItem("Paste");
edit.add(item8);
item9=new MenuItem("-");
edit.add(item9);
sub=new Menu("Special");
item10=new MenuItem("First");
sub.add(item10);
item11=new MenuItem("Second");
sub.add(item11);
item12=new MenuItem("Third");
sub.add(item12);
edit.add(sub);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
}
public void paint(Graphics g) {
g.drawString(msg, 50, 200);
if(debug.getState())
g.drawString("Debug is on.", 50, 220);
else
g.drawString("Debug is off.", 50, 220);
if(test.getState())
g.drawString("Testing is on.", 50, 240);
else
g.drawString("Testing is off.", 50, 240);
}
public static void main(String [] args){
MenuDemo obj1=new MenuDemo();
}
}
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
public void itemStateChanged(ItemEvent ie)
{
menuFrame.repaint();
}
}
//Program 3: SampleDialog.java
import java.awt.*;
import java.awt.event.*;
class SampleDialog extends Dialog implements ActionListener
{
SampleDialog(Frame parent, String title)
{
super(parent, title, false);
setLayout(new FlowLayout());
setSize(300, 200);
add(new Label("Press this button:"));
Button b;
add(b = new Button("Cancel"));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
dispose();
}
public void paint(Graphics g)
{
g.drawString("This is in the dialog box", 10, 70);
}
}
SWING
Swing features:
Pluggable look & feel
Uses MVC architecture
Lightweight components
Platform Independent
Advance features such as JTable, JTabbedPane, JScrollPane etc
Classes Hierarchy
Component
A Component is the abstract base class for the non menu user-interface controls of SWING. Component
represents an object with graphical representation
Container
A Container is a component that can contain other SWING components.
JComponent
A JComponent is a base class for all swing UI components. In order to use a swing component that
inherits from JComponent, component must be in a containment hierarchy whose root is a top-level
Swing container.
JLabel
A JLabel object is a component for placing text in a container.
JButton
This class creates a labeled button.
JColorChooser
A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.
JCheck Box
A JCheckBox is a graphical component that can be in either an on (true) or off (false) state.
JRadioButton
The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in
a group.
JList
A JList component presents the user with a scrolling list of text items.
JComboBox
A JComboBox component presents the user with a to show up menu of choices.
JTextField
A JTextField object is a text component that allows for the editing of a single line of text.
JTextArea
A JTextArea object is a text component that allows for the editing of a multiple lines of text.
ImageIcon
A ImageIcon control is an implementation of the Icon interface that paints Icons from Images
JScrollbar
A Scrollbar control represents a scroll bar component in order to enable user to select from range of
values.
JOptionPane
JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of
something.
JFileChooser
A JFileChooser control represents a dialog window from which the user can select a file.
JProgressBar
As the task progresses towards completion, the progress bar displays the task's percentage of
completion.
JSlider
A JSlider lets the user graphically select a value by sliding a knob within a bounded interval.
JSpinner
A JSpinner is a single line input field that lets the user select a number or an object value from an ordered
sequence.
A. JFrame
Important Constants
static int EXIT_ON_CLOSE -- The exit application default window close operation.
static int DISPOSE_ON_CLOSE -- The dispose-window default window close operation.
static int DO_NOTHING_ON_CLOSE -- The do-nothing default window close operation.
static int HIDE_ON_CLOSE -- The hide-window default window close operation
Important Constructors
JFrame()
Constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc)
Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
JFrame(String title)
Creates a new, initially invisible Frame with the specified title.
Important Methods
void setDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a "close" on this frame.
import java.awt.*;
import javax.swing.*;
public class MySwingFrame extends JFrame
{
public MySwingFrame()
{
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MySwingFrame newFrame=new MySwingFrame();
}
}
B. JApplet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*<object code="MySwingApplet" width=220 height=90></object>*/
public class MySwingApplet extends JApplet{
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
public void init(){
makeGUI();
}
private void makeGUI(){
setLayout(new FlowLayout());
jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Alpha was pressed.");
}
});
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Beta was pressed.");
}
});
add(jbtnAlpha);
add(jbtnBeta);
jlab = new JLabel("Press a button. Nikita Education");
add(jlab);
}
}
Swing Controls:
JLabel(Icon image)
Creates a JLabel instance with the specified image.
JLabel(String text)
Creates a JLabel instance with the specified text.
int getHorizontalAlignment()
Returns the alignment of the label's contents along the X axis.
Icon getIcon()
Returns the graphic image (glyph, icon) that the label displays.
String getText()
Returns the text string that the label displays.
int getVerticalAlignment()
Returns the alignment of the label's contents along the Y axis.
ImageIcon(Image image)
Creates an ImageIcon from an image object.
ImageIcon(String filename)
Creates an ImageIcon from the specified file.
int getIconHeight()
Gets the height of the icon.
int getIconWidth()
Gets the width of the icon.
Image getImage()
Returns this icon's Image.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JLabelDemo extends JFrame{
public JLabelDemo(){
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
D. JTextField
Important Constructors
JTextField()
Constructs a new TextField.
JTextField(int columns)
Constructs a new empty TextField with the specified number of columns.
JTextField(String text)
Constructs a new TextField initialized with the specified text.
Important Methods
void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this textfield.
int getColumns()
Returns the number of columns in this TextField.
int getHorizontalAlignment()
Returns the horizontal alignment of the text.
String getText()
Returns the text contained in this TextComponent.
void selectAll()
Selects all the text in the TextComponent
void setText(String t)
Sets the text of this TextComponent to the specified text.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JTextFieldDemo extends JFrame{
JTextField jtf;
JLabel lb;
String msg="";
public JTextFieldDemo(){
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf = new JTextField("Nikita Education [NET]",15);
add(jtf);
jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
lb.setText(jtf.getText());
}
});
lb=new JLabel();
add(lb);
}
public static void main(String[] args) {
JTextFieldDemo newFrame=new JTextFieldDemo();
}
}
E. JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of multiple
line text. It inherits JTextComponent class.
Commonly used Constructors:
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text initially.
JTextArea(int row, int column) Creates a text area with the specified number of rows and columns that
displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns that
column) displays specified text.
import javax.swing.*;
public class TextAreaExample{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to Nikita");
area.setBounds(10,30, 200,200);
f.add(area);
f.setTitle("Nikita Education [NET]");
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new TextAreaExample();
}
}
F. JPasswordField
import javax.swing.*;
public class PasswordFieldExample{
public static void main(String[] args) {
JFrame f=new JFrame("Nikita Education [NET]");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
G. Swing Buttons
Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton. All are
subclasses of the AbstractButton class, which extends JComponent. Thus, all buttons share a set of
common traits. AbstractButton contains many methods that allow you to control the behavior of buttons.
AbstractButton
Important Methods useful for all swing buttons i.e. JButton, JToggleButton, JCheckBox, JRadioButton
Modifier and Type Method and Description
void addActionListener(ActionListener l)
Adds an ActionListener to the button.
void addItemListener(ItemListener l)
Adds an ItemListener to the checkbox.
String getActionCommand()
Returns the action command for this button.
Icon getIcon() : Returns the default icon.
Icon getSelectedIcon()
Returns the selected icon for the button.
String getText() : Returns the button's text.
void setActionCommand(String actionCommand)
Sets the action command for this button.
void setDisabledIcon(Icon disabledIcon)
Sets the disabled icon for the button.
void setEnabled(boolean b)
Enables (or disables) the button.
void setHorizontalAlignment(int alignment)
Sets the horizontal alignment of the icon and text.
void setIcon(Icon defaultIcon)
Sets the button's default icon.
void setPressedIcon(Icon pressedIcon)
Sets the pressed icon for the button.
void setSelected(boolean b)
Sets the state of the button.
void setSelectedIcon(Icon selectedIcon)
Sets the selected icon for the button.
void setText(String text)
Sets the button's text.
H. JButton
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JButtonDemo extends JFrame implements ActionListener{
JLabel jlab;
public JButtonDemo() {
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
I. JToggleButton
A useful variation on the push button is called a toggle button. A toggle button looks just like a push
button, but it acts differently because it has two states: pushed and released. Each time a toggle
button is pushed, it toggles between its two states. Toggle buttons are objects of the ToggleButton
class. JToggleButton is a superclass for JCheckBox and JRadioButton. JToggleButton defines the
basic functionality of all two-state components.
Important Constructors
JToggleButton()
Creates an initially unselected toggle button without setting the text or image.
JToggleButton(Icon icon)
Creates an initially unselected toggle button with the specified image but no text.
JToggleButton(Icon icon, boolean selected)
Creates a toggle button with the specified image and selection state, but no text.
JToggleButton(String text)
Creates an unselected toggle button with the specified text.
JToggleButton(String text, boolean selected)
Creates a toggle button with the specified text and selection state.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JToggleButtonDemo extends JFrame{
JLabel jlab;
JToggleButton jtbn;
public JToggleButtonDemo() {
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlab = new JLabel("Button is off.");
jtbn = new JToggleButton("On/Off");
jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");
}
});
add(jtbn);
add(jlab);
}
public static void main(String[] args)
{
JToggleButtonDemo newFrame=new JToggleButtonDemo();
}
}
J. JCheckBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JCheckBoxDemo extends JFrame implements ItemListener
{
JLabel jlab;
public JCheckBoxDemo(){
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
K. JRadioButton
Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at
any one time. They are supported by the JRadioButton class, which extends JToggleButton. The
JRadioButton class is used to create a radio button. Radio buttons must be configured into a group.
Only one of the buttons in the group can be selected at any time. A button group is created by the
ButtonGroup class.
ButtonGroup
Creates group of mutually exclusive buttons.
Constructors: public ButtonGroup()
Method: void add(AbstractButton ab)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JRadioButtonDemo extends JFrame implements
ActionListener{
JLabel jlab;
public JRadioButtonDemo(){
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
L. JComboBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JComboBoxDemo extends JFrame{
JLabel jlab;
ImageIcon a,b,c,d,e;
JComboBox jcb;
String flags[] = { "a", "b", "c", "d", "e" };
public JComboBoxDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jcb = new JComboBox(flags);
add(jcb);
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) jcb.getSelectedItem();
jlab.setIcon(new ImageIcon(s + ".gif"));
}});
jlab = new JLabel(new ImageIcon("a.gif"));
add(jlab);
}
public static void main(String[] args){
JComboBoxDemo newFrame=new JComboBoxDemo();
}
}
M. JList
1. In Swing, the basic list class is called JList. It supports the selection of one or more items from a
list. Although the list often consists of strings, it is possible to create a list of just about any object
that can be displayed. JList is so widely used in Java
2. JList is based on two models.
3. The first is ListModel. This interface defines how access to the list data is achieved.
4. The second model is the ListSelectionModel interface, which defines methods that determine what
list item or items are selected.
5. Although a JList will work properly by itself, most of the time you will wrap a JList inside a
JScrollPane. This way, long lists will automatically be scrollable, which simplifies GUI design
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JListDemo extends JFrame{
JList jlst;
JLabel jlab;
JScrollPane jscrlp;
String Cities[] = { "New York", "Chicago", "Houston",
"Denver", "Los Angeles", "Seattle",
"London", "Paris", "New Delhi",
"Hong Kong", "Tokyo", "Sydney" };
public JListDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jlst = new JList(Cities);
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jscrlp = new JScrollPane(jlst);
jscrlp.setPreferredSize(new Dimension(120, 90));
jlab = new JLabel("Choose a City");
jlst.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent le) {
int idx = jlst.getSelectedIndex();
if(idx != -1)
jlab.setText("Current selection: " + Cities[idx]);
else
jlab.setText("Choose a City");
}});
add(jscrlp);
add(jlab);
}
public static void main(String[] args) {
JListDemo newFrame=new JListDemo();
}
}
N. JPanel
import java.awt.*;
import javax.swing.*;
public class PanelExample{
PanelExample(){
JFrame f= new JFrame("Nikita Education [NET]");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new PanelExample();
}
}
O. JTabbedPane
Steps:
1. Create an instance of JTabbedPane.
2. Add each tab by calling addTab( ).
3. Add the tabbed pane to the content pane.
Methods:
void addTab(String name, Component comp) -- add instance of new tab to the tabbed pane.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class CitiesPanel extends JPanel {
public CitiesPanel() {
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel{
public FlavorsPanel() {
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
public class JTabbedPaneDemo extends JFrame {
public JTabbedPaneDemo() {
setTitle("Nikita Education [NET]");
setSize(800,600);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
P. JScrollPane
3. JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll
bars
4. The viewable area of a scroll pane is called the viewport.
5. It is a window in which the component being scrolled is displayed.
6. Thus, the viewport displays the visible portion of the component being scrolled.
7. The scroll bars scroll the component through the viewport.
8. In its default behavior, a JScrollPane will dynamically add or remove a scroll bar as needed
Steps:
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane
Constructors:
JScrollPane(Component comp)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JScrollPaneDemo extends JFrame
{
public JScrollPaneDemo()
{
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
jp.add(new JButton("Button " + b));
++b;
}
}
JScrollPane jsp = new JScrollPane(jp);
add(jsp);
}
public static void main(String[] args)
{
JScrollPaneDemo newFrame=new JScrollPaneDemo();
}
}
Q. JScrollBar
JScrollBar(int orientation) Creates a scrollbar with the specified orientation and the
initial values.
JScrollBar(int orientation, int value, int Creates a scrollbar with the specified orientation, value,
extent, int min, int max) extent, minimum, and maximum.
import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Nikita Education [NET]");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new ScrollBarExample();
}
}
R. JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a complex
component. It has a 'root node' at the top most which is a parent for all nodes in the tree. It inherits
JComponent class.
1. A tree is a component that presents a hierarchical view of data.
2. The user has the ability to expand or collapse individual subtrees in this display.
3. Trees are implemented in Swing by the JTree class.
4. JTree relies on two models: TreeModel and TreeSelectionModel.
5. A JTree generates a variety of events, but three relate specifically to trees:
TreeExpansionEvent, TreeSelectionEvent, and TreeModelEvent
Steps:
1. Create an instance of JTree.
2. Create a JScrollPane and specify the tree as the object to be scrolled.
3. Add the tree to the scroll pane.
4. Add the scroll pane to the content pane
DefaultMutableTreeNode
The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node
in a tree.
Constructors:
DefaultMutableTreeNode(Object obj)
Methods:
void add(MutableTreeNode child)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class JTreeDemo extends JFrame{
JTree tree;
JLabel jlab;
public JTreeDemo(){
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
S. JTable
JTable is a component that displays rows and columns of data. You can drag the cursor on column
boundaries to resize columns. You can also drag a column to a new position. Depending on its
configuration, it is also possible to select a row, column, or cell within the table, and to change the
data within a cell. JTable is a sophisticated component that offers many more options and features.
JTable relies on three models. The first is the table model, which is defined by the TableModel
interface. This model defines those things related to displaying data in a two-dimensional format.
The second is the table column model, which is represented by TableColumnModel. JTable is
defined in terms of columns, and it is TableColumnModel that specifies the characteristics of a column
The third model determines how items are selected, and it is specified by the ListSelectionModel.
Steps:
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane. Add the scroll pane to the content pane
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JTableDemo extends JFrame
{
JTree tree;
JLabel jlab;
public JTableDemo() {
setTitle("Nikita Education [NET]");
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Initialize column headings.
String[] colHeads = { "Name", "Extension", "ID#" };
// Initialize data.
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
{ "Anne", "1237", "333" },
{ "John", "5656", "314" },
{ "Matt", "5672", "217" },
{ "Claire", "6741", "444" },
{ "Erwin", "9023", "519" },
{ "Ellen", "1134", "532" },
{ "Jennifer", "5689", "112" },
{ "Ed", "9030", "133" },
{ "Helen", "6751", "145" }
};
T. JProgressBar
import javax.swing.*;
public class ProgressBarExample extends JFrame
{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample() {
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setTitle("Nikita Education [NET]");
setLayout(null);
}
Nikita Education ( NET ) [ 9689925884 ] 61
Basics of Advance Java API
U. JDialog
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample{
private static JDialog d;
DialogExample(){
JFrame f= new JFrame();
JButton a=new JButton("Show Message");
a.addActionListener ( new ActionListener(){
public void actionPerformed( ActionEvent e ){
d = new JDialog(f , "NET - Dialog", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener(){
public void actionPerformed( ActionEvent e ){
DialogExample.d.setVisible(false);
}});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,200);
d.setVisible(true);
}});
a.setBounds(50,30,200,30);
f.add(a);
f.setSize(500,500);
f.setTitle("Nikita Education [NET]");
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new DialogExample();
}
}
V. JFileChooser
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements ActionListener{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample() {
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
Unit-II
Event Handling
A. Introduction
Applets are event-driven programs that use a graphical user interface to interact with the user.
Furthermore, any program that uses a graphical user interface, such as a Java application written for
Windows, is event driven. Thus, you cannot write these types of programs without a solid command of
event handling. Events are supported by a number of packages, including java.util, java.awt, and
java.awt.event. Most events to which your program will respond are generated when the user interacts
with a GUI-based program. There are several types of events, including those generated by the mouse,
the keyboard, and various GUI controls, such as a push button, scroll bar, or check box etc.
The delegation event model is based on the Event Sources and Event Listeners. Event Listener is handler
that receives the messages / events. The Event Source is any object which creates the message / event.
The Event Delegation model is based on – The Event Classes, The Event Listeners, and Event Objects.
Events: Event is an object that describes a state of change in a source. Event may be generated as a
consequence of a person interacting with the GUI elements such as pressing a button, entering a
character through keyboard, selecting an item from a list.
Event Sources: "Source" is an object that generates an event. listeners must register with the source in
order to receive event notification.
Event Listeners: A listener is an object that is notified when an event occurs. To do so 2 things should
be satisfied. 1) It must have been registered with one or more sources to receive notification. 2) It must
implement methods to receive and process these notifications.
The modern approach to handling events is based on the delegation event model.
In this model source generates an event and sends it to one or more listeners.
The listener simply waits until it receives an event.
Once received, the listener processes the event and then returns.
The advantage of this design is that the application logic that processes events is clearly separated
from the user interface logic that generates those events.
User interface logic is able to delegate the processing of an event to a separate piece of code.
In the delegation model, listeners must register with the source in order to receive event
notification. An each type of event has its own registration method and following is the general
form of it.
public void addTypeListener(TypeListener el)
For Example:
addActionListener(ActionListener obj);
addKeyListener(KeyListener obj);
addMouseListener(MouseListener obj);
addItemListener(ItemListener obj);
C. Event Classes
TextEvent Instances of this class describe text events. These are generated by text
fields and text areas when characters are entered by a user or program.
TextEvent defines the integer constant TEXT_VALUE_CHANGED.
WindowEvent There are ten types of window events. WindowEvent is a subclass of
ComponentEvent. The WindowEvent class defines integer constants that
can be used to identify them.
D. Listener Interfaces
//AEvent2.java
import java.awt.*;
import java.awt.event.*;
AEvent2()
{
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
//Outer.java
import java.awt.event.*;
Outer(AEvent2 obj)
{
this.obj=obj;
}
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
F. Event Classes
EventObject Class
The classes that represent events are at the core of Java‟s event handling mechanism. Thus, a discussion
of event handling must begin with the event classes. It is important to understand, however, that Java
defines several types of event classes. The most widely used events are those defined by the AWT and
those defined by Swing. This chapter focuses on the AWT events. (Most of these events also apply to
Swing.) At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the super
class for all events. It‟s one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event. EventObject contains two methods: getSource() and
toString(). The getSource( ) method returns the source of the event. Its general form is shown here:
Object getSource( )
The package java.awt.event defines many types of events that are generated by various user interface
elements. Commonly used constructors and methods in each class are described in the following sections.
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is
selected. You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:
String getActionCommand( )
For example, when a button is pressed, an action event is generated that has a command name equal to
the label on that button.
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events. The
AdjustmentEvent class defines integer constants that can be used to identify them. The constants and
their meanings are shown here:
A FocusEvent is generated when a component gains or loses input focus. These events are identified by
the integer constants FOCUS_GAINED and FOCUS_LOST. FocusEvent is a subclass of ComponentEvent.
An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item is
selected or deselected. There are two types of item events, which are identified by the following integer
constants:
In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that signifies a change of
state. The getItem( ) method can be used to obtain a reference to the item that generated an event. Its
signature is shown here:
Object getItem( )
A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are
identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two
events are generated when any key is pressed or released. The last event occurs only when a character is
generated. Remember, not all keypresses result in characters. For example, pressing SHIFT does not
generate a character. There are many other integer constants that are defined by KeyEvent. For example,
VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters.
Here are some others:
The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or
alt. KeyEvent is a subclass of InputEvent
There are eight types of mouse events. MouseEvent is a subclass of InputEvent. The MouseEvent class
defines the following integer constants that can be used to identify them:
Instances of this class describe text events. These are generated by text fields and text areas when
characters are entered by a user or program. TextEvent defines the integer constant
TEXT_VALUE_CHANGED.
There are ten types of window events. WindowEvent is a subclass of ComponentEvent. The
WindowEvent class defines integer constants that can be used to identify them. The constants and their
meanings are shown here:
G. Listener Interfaces
As explained, the delegation event model has two parts: sources and listeners. Listeners are created by
implementing one or more of the interfaces defined by the java.awt.event package. When an event
occurs, the event source invokes the appropriate method defined by the listener and provides an event
object as its argument. The following sections examine the specific methods that are contained in each
interface.
This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its
general form is shown here:
void actionPerformed(ActionEvent ae)
This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment event
occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)
This interface defines four methods that are invoked when a component is resized, moved, shown, or
hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
This interface contains two methods. When a component is added to a container, componentAdded( ) is
invoked. When a component is removed from a container, componentRemoved( ) is invoked. Their
general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
This interface defines two methods. When a component obtains keyboard focus, focusGained() is
invoked. When a component loses keyboard focus, focusLost( ) is called. Their general forms are shown
here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
Nikita Education ( NET ) [ 9689925884 ] 72
Basics of Advance Java API
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes. Its general form is shown here:
void itemStateChanged(ItemEvent ie)
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a
key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been
entered. For example, if a user presses and releases the A key, three events are generated in sequence:
key pressed, typed, and released. If a user presses and releases the HOME key, two key events are
generated in sequence: key pressed and released. The general forms of these methods are shown here:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called.
When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are
invoked when the mouse is pressed and released, respectively. The general forms of these methods are
shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse
is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their general
forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is moved.
Its general form is shown here:
void mouseWheelMoved(MouseWheelEvent mwe)
This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or
text field. Its general form is shown here:
void textChanged(TextEvent te)
This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are called
when a window gains or loses input focus. Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods are
invoked when a window is activated or deactivated, respectively. If a window is iconified, the
windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is
called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are
called, respectively. The windowClosing() method is called when a window is being closed. The general
forms of these methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
H. Adapter Classes
Java provides a special feature, called an adapter class that can simplify the creation of event handlers in
certain situations. An adapter class provides an empty implementation of all methods in an event listener
interface. Adapter classes are useful when you want to receive and process only some of the events that
are handled by a particular event listener interface. You can define a new class to act as an event listener
by extending one of the adapter classes and implementing only those events in which you are interested.
1. ComponentAdapter 4. FocusAdapter
2. KeyAdapter 5. MouseAdapter
3. WindowAdapter
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
I. Inner Classes
A class within another class is known as Inner class or Nested class. The scope of the inner is bounded by
the scope of its enclosing class.
A static nested class is the one that has static modifier applied. Because it is static it cannot refer to non-
static members of its enclosing class directly.
Non-static Nested class is most important type of nested class. It is also known as Inner class. It has
access to all variables and methods of Outer class and may refer to them directly. But the reverse is not
true, that is, Outer class cannot directly access members of Inner class. One more important thing to
notice about an Inner class is that it can be created only within the scope of Outer class. Java compiler
generates an error if any code outside Outer class attempts to instantiate Inner class.
class Outer{
public void display(){
Inner in=new Inner();
in.show();
}
class Inner{
public void show(){
System.out.println("Inside inner");
}
}
public static void main(String[] args){
Outer ot=new Outer();
ot.display();
}
}
class Outer{
int count;
public void display(){
for(int i=0;i<5;i++){
class Inner{
//Inner class defined inside for loop
public void show(){
System.out.println("Inside inner "+(count++));
}
}
Inner in=new Inner(); Output :
in.show(); Inside inner 0
} Inside inner 1
Inside inner 2
}
Inside inner 3
public static void main(String[] args){
Inside inner 4
Outer ot=new Outer();
ot.display();
}
}
class Outer{
int count;
public void display(){
Inner in=new Inner();
in.show();
}
class Inner{
public void show(){
System.out.println("Inside inner "+(++count));
}
}
}
Output :
Inside inner 1
class Test{
public static void main(String[] args){
Outer ot=new Outer();
Outer.Inner in= ot.new Inner();
in.show();
}
}
iv. Anonymous class: A class without any name is called Anonymous class.
interface Animal{
void type();
}
Unit-III
Networking & Security
Computer Network: A computer network is a group of computer systems and other computing
hardware devices that are linked together through communication channels to facilitate communication
and resource-sharing among a wide range of users. Networks are commonly categorized based on their
characteristics. Eg. LAN, MAN, WAN, Internet, Intranet, WiFi.
IP Address: IP address is short for Internet Protocol (IP) address. An IP address is an identifier for a
computer or device on a TCP/IP network. Networks using the TCP/IP protocol route messages based on
the IP address of the destination.
i. IPv4: Internet Protocol Version 4 (IPv4) is the fourth revision of the IP and a widely used protocol
in data communication over different kinds of networks. It uses 32 bit IP address.
ii. IPv6: IPv6) is the successor to Internet Protocol Version 4 (IPv4). IPv6 was designed as an
evolutionary upgrade to the Internet Protocol. It uses 128 bit IP address.
Subnet Mask: An IP address has two components, the network address and the host address. A subnet
mask separates the IP address into the network and host addresses (<network><host>). A Subnet mask
is a 32-bit number that masks an IP address, and divides the IP address into network address and host
address. Subnet Mask is made by setting network bits to all "1"s and setting host bits to all "0"s.
Subnetting: Divides the host part of an IP address into a subnet and host address
(<network><subnet><host>) if additional sub network is needed.
IP Classes: The IPv4 address space can be subdivided into 5 classes - Class A (1 - 126), B (128 - 191),
C (192 - 223), D (224 - 239) and E (240 - 254). Each class consists of a contiguous subset of the overall
IPv4 address range.
Client / Server: Client/server architecture is a computing model, in which the server hosts, delivers and
manages most of the resources and services to be consumed by the client. This type of architecture has
one or more client computers connected to a central server over a network or Internet connection. This
system shares computing resources.
Client: A client is a piece of computer hardware or software that accesses a service made available by a
server. Two types: Thin Client and Thick Client.
Server: A computer or device on a network that manages network resources. There are many different
types of servers. For example: File server, Print server, Network server, Database server.
Proxy Server: A server that sits between a client application, such as a Web browser, and a real server.
It intercepts all requests to the real server to see if it can fulfill the requests itself. If not, it forwards the
request to the real server.
TCP (Transmission Control Protocol): TCP is one of the main protocol in TCP/IP networks. TCP enables
two hosts to establish a connection and exchange streams of data. TCP guarantees delivery of data and
also guarantees that packets will be delivered in the same order in which they were sent.
UDP (User Datagram Protocol ): UDP is a connectionless protocol runs on top of IP networks. UDP/IP
provides very few error recovery services, offering instead a direct way to send and receive datagram‟s
over an IP network. It's used primarily for broadcasting messages over a network.
IP: The Internet Protocol (IP) is the method or protocol by which data is sent from one computer to
another on the Internet. Each computer (known as a host) on the Internet has at least one IP address
that uniquely identifies it from all other computers on the Internet.
URL (Uniform Resource Locator ) it is the global address of documents and other resources on the World
Wide Web. The first part of the URL is called a protocol identifier and it indicates what protocol to use and
the second part is called a resource name and it specifies the IP address or the domain name where the
resource is located. The protocol identifier and the resource name are separated by a colon and two
forward slashes.
WWW: The World Wide Web (abbreviated as WWW or W3, commonly known as the Web) is a system
of interlinked hypertext documents that are accessed via the Internet. With a web browser, one can view
web pages that may contain text, images, videos, and other multimedia and navigate between them via
hyperlinks. The documents are formatted in a markup language called HTML (Hypertext Markup
Language).
1. TCP stands for “Transmission Control Protocol” while UDP stands for “User datagram
Protocol”.
2. TCP is connection oriented protocol while UDP is connectionless protocol.
3. TCP is more reliable , UDP is not reliable.
4. UDP is more faster for data sending than TCP.
5. UDP makes error checking but no reporting but TCP makes checks for errors and reporting.
6. TCP gives guarantee that the order of data at receiving end is same as on sending end while UDP
has no such guarantee.
7. Header size of TCP is 20 bytes while that of UDP is 8 bytes.
8. TCP is heavy weight as it needs three packets to setup a connection while UDP is light weight.
9. TCP has acknowledgement segments but UDP has no acknowledgement.
10. TCP is used for application that require high reliability but less time critical whereas UDP is
used for application that are time sensitive but require less reliability.
B. Concept of Socket
Socket is a logical entity which provides end points to establish connection between processes or
computers. Socket is a logical entity which consist IP address and port number to uniquely identify
systems and processes over a network.
Types of sockets:
Stream Sockets: It is a connection oriented socket provides reliable and sequenced delivery of
information over a network using TCP protocol. Stream socket establishes a connection between
client and server using TCP protocol.
Datagram Sockets: It is a connectionless socket provides faster but unreliable and non-
sequenced delivery of information over a network using UDP protocol. Datagram socket sends
different packets of information over a network through all available paths.
Raw Sockets: These sockets provide users access to the underlying communication protocols,
which support socket abstractions. These sockets are normally datagram oriented, though their
exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not
intended for the general user; they have been provided mainly for those interested in developing
new communication protocols, or for gaining access to some of the more cryptic facilities of an
existing protocol.
Socket Primitives:
Socket primitives defines different stages or methods through which socket performs different operations
during communication between hosts. Following are different socket primitives.
C. Port
It is a sixteen bit unique number used to uniquely identify processes over a network. It is also called as a
numbered socket. A port number is the logical address of each application or process that uses a network
or the Internet to communicate. A port number uniquely identifies a network-based application on a
computer. Each application/program is allocated a 16-bit integer port number. This number is assigned
automatically by the OS, manually by the user or is set as a default for some popular applications.
Types of Ports:
Well known/reserved ports: Some port numbers are reserved for standard protocols and
applications by IANA are called as well-known or reserved ports. These numbers are pre-assigned
to standard protocols and no one can use these for general purposes. Total reserved ports are
1024 i.e. 0 to 1023.
Registered ports: Some port numbers can be registered by software companies for their
network applications or specific protocols are called as Registered Ports. Range of ports available
for registration is : 1024 to 49151.
Dynamic or private ports: Port numbers 49152 to 65535 are available for general purposes
or research purposes are called as dynamic or private ports. These port numbers can be used by
anybody for their private use.
Classes:
Interfaces:
E. InetAddress
Inet Address encapsulates both numerical IP address and the domain name for that address. Inet address
can handle both IPv4 and Ipv6 addresses. Inet Address class has no visible constructor. To create an inet
Address object, you have to use Factory methods.
Factory methods
Factory methods are the static methods of any class that returns the object of same class where these
methods are defined. Factory methods of InetAddress class returns an instance of InetAddress class
because it does not provides any visible constructor.
Instance Methods:
Instance methods are the non-static methods of any class which are defined in that class and accessed
only by object of that class. Instance method means member methods of object of a class. Instance
methods of InetAddress returns IP Address information of any host stored by its object.
Inet4Address / Inet6Address
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("nspl");
System.out.println(Address);
byte [] adr=Address.getAddress();
String adrStr=Address.getHostAddress();
String hostName=Address.getHostName();
boolean mltcst=Address.isMulticastAddress();
System.out.print("Byte Address is: ");
for (int i=0;i<adr.length ;i++)
{
System.out.print(" "+adr[i]);
}
}
}
F. URL
The URL (Uniform Resource Locator) provides a reasonably intelligible form to uniquely identify or
address information on the Internet. URLs are ubiquitous; every browser uses them to identify
information on the Web. Within Java‟s network class library, the URL class provides a simple, concise API
to access information across the Internet using URLs. All URLs share the same basic format, although
some variation is allowed. Here are two examples: http://www.nspl.in/ and
http://www.nspl.in:8486/index.htm.
A URL specification is based on four components: (1) The protocol to use, separated from the rest of
the locator by a colon (:). (2) The host name or IP address of the host to use; this is delimited on the
left by double slashes (//) and on the right by a slash (/) or optionally a colon (:). (3) The port number,
is an optional parameter, delimited on the left from the host name by a colon (:) and on the right by a
slash (/). (It defaults to port 80, the predefined HTTP port; thus, “:80” is redundant.) (4) The actual file
path. Most HTTP servers will append a file named index.html or index.htm to URLs that refer directly
to a directory resource. Thus, http://www.nspl.in is the same as http://www.nspl.in/index.htm.
To deal with above concept of URL, java.net package provides a URL class which has following
constructors and methods:
Method Summary
String getFile()
Gets the file name of this URL.
String getHost()
Gets the host name of this URL, if applicable.
String getPath()
Gets the path part of this URL.
int getPort()
Gets the port number of this URL.
String getProtocol()
Gets the protocol name of this URL.
To access the actual bits or content information of a URL, create a URLConnection object from it, using its
openConnection( ) method.
Example:
import java.net.*;
class URLDemo
{
public static void main(String args[])throws MalformedURLException
{
URL hp = new URL("http://www.nspl.in:80
/Temp/demo/proof.txt");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
}
G. URLConnection
URLConnection is a general-purpose class for accessing the attributes of a remote resource. Once you
make a connection to a remote server, you can use URLConnection to inspect the properties of the
remote object before actually transporting it locally. To get object of URLConnection class use its
openConnection() method on object of URL class.
Method Summary:
int getContentLength()
Returns the value of the content-length header field.
String getContentType()
Returns the value of the content-type header field.
long getDate()
Returns the value of the date header field.
long getExpiration()
Returns the value of the expires header field.
String getHeaderField(int n)
Returns the value for the nth header field.
String getHeaderField(String name)
Returns the value of the named header field.
InputStream getInputStream()
Returns an input stream that reads from this open connection.
OutputStream getOutputStream()
Returns an output stream that writes to this connection.
URL getURL()
Returns the value of this URLConnection's URL field.
Example:
import java.net.*;
import java.io.*;
import java.util.Date;
class URLConnectionDemo{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("http://www.nspl.in:80/Temp/index.html");
URLConnection hpCon = hp.openConnection();
// get date
long d = hpCon.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
H. HttpURLConnection
Method Summary:
String getHeaderField(int n)
Returns the value for the nth header field.
String getRequestMethod()
Get the request method.
int getResponseCode()
Gets the status code from an HTTP response message.
String getResponseMessage()
Gets the HTTP response message, if any, returned along with the response code from
a server.
void setRequestMethod(String method)
Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE
TRACE are legal, subject to protocol restrictions.
Example:
import java.net.*;
import java.io.*;
import java.util.*;
I. URI
A relatively recent addition to Java is the URI class, which encapsulates a Uniform Resource Identifier
(URI). URI‟s are similar to URL‟s. In fact, URLs constitute a subset of URIs. A URI represents a standard
way to identify a resource. URL also describes how to access the resource.
J. Cookies
Cookies are small files which are stored on a user's computer. They are designed to hold a modest
amount of data specific to a particular client and website, and can be accessed either by the web server
or the client computer. 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.
The java.net package includes classes and interfaces that help manage cookies and can be used to
create a stateful HTTP session. The classes are CookieHandler, CookieManager, and HttpCookie.
The interfaces are CookiePolicy and CookieStore.
1. CookieManager
Methods of CookieManager
Map<String,List<String>> get(URI uri, Map<String,List<String>> requestHeaders)
Gets all the applicable cookies from a cookie cache for the specified uri in
the request header.
CookieStore getCookieStore()
To retrieve current cookie store.
void put(URI uri, Map<String,List<String>> responseHeaders)
Sets all the applicable cookies, examples are response header fields that
are named Set-Cookie2, present in the response headers into a cookie
cache.
void setCookiePolicy(CookiePolicy cookiePolicy)
To set the cookie policy of this cookie manager.
K. Stream Socket
TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, and stream-based
connections between hosts on the Internet. A socket can be used to connect Java‟s I/O system to other
programs that may reside either on the local machine or on any other machine on the Internet. There are
two kinds of TCP sockets in Java. One is for servers, and the other is for clients.
The ServerSocket class is designed to be a “listener,” which waits for clients to connect before doing
anything. Thus, ServerSocket is for servers.
The Socket class is for clients. It is designed to connect to server sockets and initiate protocol
exchanges. Because client sockets are the most commonly used by Java applications, they are examined
here. The creation of a Socket object implicitly establishes a connection between the client and server.
K.1. ServerSocket
The ServerSocket class is used to create servers that listen for either local or remote client programs to
connect to them on published ports. ServerSockets are quite different from normal Sockets. When you
create a ServerSocket, it will register itself with the system as having an interest in client connections.
The constructors for ServerSocket reflect the port number that you want to accept connections on and,
optionally, how long you want the queue for said port to be. The queue length tells the system how many
client connections it can leave pending before it should simply refuse connections. The default is 50.
The constructors might throw an IOException under adverse conditions.
K.2. Socket
A socket is simply an endpoint for communications between the machines. The Socket class can be used
to create a socket. The java.net.Socket class represents the socket that both the client and the server
use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the
server obtains a Socket object from the return value of the accept() method.
public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.
Connects to the specified host and port, creating a socket on the local host at the specified address and
port.
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.
This method is identical to the previous constructor, except that the host is denoted by an InetAddress
object instead of a String.
public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
Program 1: MyServer.java
import java.net.*;
import java.io.*;
class MyServer
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=
new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("NET"))
{
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
Program 2: MyClient.java
import java.net.*;
import java.io.*;
class MyClient
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=
new DataOutputStream(s.getOutputStream());
L. Datagram Socket
Datagram socket is a type of interprocess communications socket or network socket which provides
a connectionless point for sending or receiving data packets. Each packet sent or received on a datagram
socket is individually addressed and routed. Order and reliability are not guaranteed with datagram
sockets, so multiple packets sent from one machine or process to another may arrive in any order or
might not arrive at all.
A datagram is an independent, self-contained message sent over the network whose arrival, arrival
time, and content are not guaranteed. It is a small piece of information transmitted over a connectionless
protocol. Datagrams are bundles of information passed between machines.
Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
L.1. DatagramSocket
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram
packets. A datagram is basically an information but there is no guarantee of its content, arrival or arrival
time.
L.2. DatagramPacket
DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive
in any order. Additionally, packet delivery is not guaranteed.
int getLength()
Returns the length of the data to be sent or the length of the data received.
int getPort()
Returns the port number on the remote host to which this datagram is being sent or
from which the datagram was received.
void setPort(int iport)
Sets the port number on the remote host to which this datagram is being sent.
Example:
import java.net.*;
class WriteServer{
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
M. Java Security
The Java platform provides a number of features designed for improving the security of Java
applications. This includes enforcing runtime constraints through the use of the Java Virtual
Machine (JVM), a security manager that sandboxes un-trusted code from the rest of the operating
system, and a suite of security APIs that Java developers can utilize.
1. The JVM:
The binary form of programs running on the Java platform is not native machine code but an
intermediate bytecode. The JVM performs verification on this bytecode before running it to prevent the
program from performing unsafe operations such as branching to incorrect locations, which may contain
data rather than instructions. It also allows the JVM to enforce runtime constraints such as array bounds
checking. This means that Java programs are significantly less likely to suffer from memory safety flaws
such as buffer overflow than programs written in languages such as C which do not provide such memory
safety guarantees. The platform does not allow programs to perform certain potentially unsafe operations
such as pointer arithmetic or unchecked type casts. It also does not allow manual control over memory
allocation and de-allocation; users are required to rely on the automatic garbage collection provided by
the platform. This also contributes to type safety and memory safety.
2. Security manager
The platform provides a security manager which allows users to run un-trusted bytecode in a
"sandboxed" environment designed to protect them from malicious or poorly written software by
preventing the un-trusted code from accessing certain platform features and APIs. For example, un-
trusted code might be prevented from reading or writing files on the local file system, running arbitrary
commands with the current user's privileges, accessing communication networks, accessing the internal
private state of objects using reflection, or causing the JVM to exit.
The security manager also allows Java programs to be cryptographically signed; users can choose to
allow code with a valid digital signature from a trusted entity to run with full privileges in circumstances
where it would otherwise be un-trusted.
Users can also set fine-grained access control policies for programs from different sources. For example, a
user may decide that only system classes should be fully trusted, that code from certain trusted entities
may be allowed to read certain specific files, and that all other code should be fully sandboxed.
3. Security APIs
The Java Class Library provides a number of APIs related to security, such as standard cryptographic
algorithms, authentication, and secure communication protocols. Java provides three main packages for
the security:
1. Java Cryptography Extension (JCE) provides
Encryption
Secure keys exchange
Secure message digest
An alternate key management system
2. Java Secure Socket Layer (JSSL) provides
Tools for secure communications
3. Java Authentication and Authorization System (JAAS) provides
Tools for authenticating the user of a program and authorize or deny the access to sensitive data.
Protect end user from the influence of developer
End user gives permissions to the developer to access resources of the user‟s end machine
JAAS allows developer to grant or deny access to their programs based on the credentials
provided by the users
The "Sandbox"
Java security relies entirely on software technology. Java accepts all downloaded programs and runs them
within a security "sandbox". This can be looked at as a security fence that surrounds the program and
keeps it away from your private data. As long as that fence has no holes, data is safe. Java security relies
on the software implementing the sandbox to work correctly. A Java program must play only inside its
sandbox. It can do anything within the boundaries of its sandbox, but it can't take any action outside of
those boundaries. For example, the sandbox for un-trusted Java applets prohibits many activities
including:
Reading or writing to the local disk
Making a network connection to any host, except the host from which the applet came
Creating a new process
Loading a new dynamic library and directly calling a native method
Features of Sandbox:
Byte-code verifier
Since Java code can be imported from anywhere in the network, it is critical to screen the code to be sure
that it was produced by a trustworthy compiler. The byte-code verifier, sometimes referred to as a mini-
theorem prover, tries to prove that a given series of Java byte codes are legal.
ClassLoader
The ClassLoader, which loads Java byte codes into the JVM, is an important link in the security chain. It
works in conjunction with the SecurityManager and the access controller to enforce security rules.
CodeSource
The CodeSource encapsulates the code's origin, which is specified as an URL, and the set of digital
certificates containing public keys corresponding to the set of private keys used to sign the code.
Permissions
Permission classes are at the very core of Java security and represent access to various system resources
such as files, sockets, and so on. A collection of permissions can be construed as a customizable security
policy for an installation.
Protection domains
It's possible to associate permissions with classes; however, it's more flexible to group classes into
protection domains and associate permissions with those domains.
Policy
The numerous mappings of permissions to classes are collectively referred to as policy. A policy file is
used to configure the policy for a particular implementation. It can be composed by a simple text editor
or using policy-tool.
SecurityManager
The class java.lang.SecurityManager is at the focal point of authorization in the implementation of the
sandbox model. SecurityManager is concrete, with a public constructor and appropriate checks in place to
ensure that it can be invoked in an authorized manner. SecurityManager consists of a number of check
methods.
AccessController
The java.security.AccessController class is used for three purposes:
To decide whether access to a critical system resource should be allowed or denied, based on the
security policy currently in effect
To mark code as privileged, thus affecting subsequent access determinations
To obtain a snapshot of the current calling context, so access-control decisions from a different
context can be made with respect to the saved context
The Keystore
The Keystore is a password-protected database that holds private keys and certificates. The password is
selected at the time of creation. Each database entry can be guarded by its own password for extra
security. Certificates accepted into the Keystore are considered to be trusted. Keystore information can be
used and updated by the security tools provided with the SDK.
Core security
Java 2's security pieces reside primarily in:
java.lang
java.security
java.security.cert
java.security.interfaces
java.security.spec
Producing secure programs requires secure designs. However, even the best designs can lead to insecure
programs if developers are unaware of the many security pitfalls inherent in Java programming. Secure
coding guidelines are important to achieve following objectives:
Improve the overall security of any Java application
Avoid injection attacks, such as SQL injection and XSS
Understand Java's memory model, with a thorough grounding of concurrency, and learn how to
prevent race conditions while avoiding deadlock
Learn when to throw and catch exceptions
Avoid I/O vulnerabilities, including file-based race conditions
Learn how historical exploits on Java were executed and later disabled
N.1. Fundamental
Prefer to have obviously no flaws rather than no obvious flaws
Design APIs to avoid security concerns
Avoid duplication
Restrict privileges
Establish trust boundaries
Minimize the number of permission checks
Encapsulate
Document security-related information
Unit-IV
Java Database Connectivity
A. Database Terminologies
Front end
It is a set of programs usually a graphical user interface (GUI) through which end user can interact with
the application or system. Java programming API‟s such as AWT, Swing, Applets, Servlets, or JSP‟s are
used to design GUI‟s or Web applications through which end user can interact with the application or
system. So the programs designed using these API‟s provides different services and features to end user.
Back end
It is a background or behind the scene service or application usually a database that stores information
passed by front end or responds to queries asked by front end through some intermediate. Software‟s like
Oracle, Sybase, MS SQL Server, MySQL, MS Access are known as a back end.
Advantage of this design is Flexibility in locating resources and expanding facilities, Better functionality for
the cost, better user interface, and easier maintenance. Hence DBMS system is implemented on
Client / Server methodology.
Nikita Education ( NET ) [ 9689925884 ] 103
Basics of Advance Java API
Advantages:
1. Easy to maintain and modification is bit easy
2. Communication is faster
Disadvantages:
1. In two tier architecture application performance will be degrade upon increasing the users.
2. Cost-ineffective
1) Client layer:
It is also called as Presentation layer which contains UI part of our application. This layer is used for the
design purpose where data is presented to the user or input is taken from the user. For example
designing registration form which contains text box, label, button etc.
2) Business layer:
In this layer all business logic written likes validation of data, calculations, data insertion etc. This acts as
a interface between Client layer and Data Access Layer. This layer is also called the intermediary layer
helps to make communication faster between client and data layer.
3) Data layer:
In this layer actual database is comes in the picture. Data Access Layer contains methods to connect with
database and to perform insert, update, delete, get data from database based on our input data.
Advantages
1. High performance, lightweight persistent objects
2. Scalability – Each tier can scale horizontally
3. Performance – Because the Presentation tier can cache requests, network utilization is minimized,
and the load is reduced on the Application and Data tiers.
4. High degree of flexibility in deployment platform and configuration
5. Better Re-use
6. Improve Data Integrity
7. Improved Security – Client is not direct access to database.
8. Easy to maintain and modification is bit easy, won‟t affect other modules
9. In three tier architecture application performance is good.
Disadvantages
1. Increase Complexity/Effort
B. JDBC
Java Database Connectivity (JDBC) is an application program interface (API) specification for connecting
programs written in Java to the data in popular databases. The application program interface lets you
encode access request statements in Structured Query Language (SQL) that are then passed to the
program that manages the database. It returns the results through a similar interface. Java JDBC is a java
API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the
database.
JDBC Features:
Get a connection: A java application can be connected to a database either using DriverManager
or DataSource object.
Connection Pooling: It allows the java application to reuse database connection that has been
created already instead of creating a new connection every time.
Rowsets: The rowsets object contains the tabular data. It makes the possible to pass the rows
data to the network. Therefore they are widely used in distributed application.
New data type supports: This is the ability of JDBC to manipulate large object such as BLOB
and CLOB without bringing them to the java programmer from the database server.
Batch Updating: This feature provides the ability to send multiple updates to the database to be
executed as batch rather than sending each update separately.
Result set enhancement:
o Scrollable Result set: It provides the ability to move the cursor backward and forward to a
specific position.
o Updateable Result set: It allows the modification of data in a database table using result set.
Savepoints: JDBC contains a Savepoint interface which contains a new method to set a
savepoints, to release a save point and to rollback a transaction to desired savepoints
C. JDBC API
JDBC API components are nothing but the collection of classes and interfaces which are necessary for
establishing communication with databases and java applications. Following are the important JDBC API:
The core API java.sql provides the API for accessing and processing the data stored in a database
(usually a relational database) using Java. This package provides the foundation and most commonly
used objects such as Connection, ResultSet, Statement, and PreparedStatement. The DriverManager
class is the main component here that loads drivers and retrieves a connection.
The extension API javax.sql provides the API for server-side data source access and processing from
Java. This package provides services for Java EE such as DataSource and RowSet. The DataSource
interface is an alternative to DriverManager for establishing a connection with a data source. JDBC
extension API also provides extension services such as connection pooling
D. JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general
JDBC Architecture consists of two layers:
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent 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.
JDBC Architecture
E. JDBC Components
F. DriverManager [Class]
The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that
are available and handles establishing a connection between a database and the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered themselves by calling the
method DriverManager.registerDriver().
G. Interfaces
G.1. Driver
Driver is the interface that every driver class must implement. The Java SQL framework allows for
multiple database drivers. Each driver should supply a class that implements the Driver interface. The
DriverManager will try to load as many drivers as it can find and then for any given connection request, it
will ask each driver in turn to try to connect to the target URL.
G.2. Connection
A Connection is the session between java application and database. The Connection interface is a factory
of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get
the object of Statement and DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(),rollback() etc. By default, connection commits the changes after
executing queries.
G.3. Statement
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
G.4. PreparedStatement
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized
query. Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter
methods of PreparedStatement. Improves performance: The performance of the application will be
faster if you use PreparedStatement interface because query is compiled only once.
G.5. CallableStatement
To call the stored procedures and functions, CallableStatement interface is used. 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 you need the get the age of the employee based on the
date of birth, you may create a function that receives date as the input and returns age of the employee
as the output.
G.6. ResultSet
The object of ResultSet maintains a cursor pointing to a particular row of data. Initially, cursor points to
before the first row. By default, ResultSet object can be moved forward only and it is not updatable. But
we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as
we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
G.7. ResultSetMetaData
The metadata means data about data i.e. we can get further information from the data. If you have to
get metadata of a table like total number of column, column name, column type etc., ResultSetMetaData
interface is useful because it provides methods to get metadata from the ResultSet object. Commonly
used methods of ResultSetMetaData interface
G.8. DatabaseMetaData
DatabaseMetaData interface provides methods to get meta data of a database such as database product
name, database product version, driver name, name of total number of tables, name of total number of
views etc.
H. JDBC Drivers
A JDBC driver is a software component enabling a Java application to interact with a database. JDBC
drivers are analogous to ODBC drivers, ADO.NET data providers, and OLE DB providers. To connect
with individual databases, JDBC (the Java Database Connectivity API) requires drivers for each
database. The JDBC driver gives out the connection to the database and implements the protocol for
transferring the query and result between client and database. JDBC Driver is a software component that
enables java application to interact with the database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
This driver is fully written in Java and hence Portable. It is suitable for the web.
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.
The type 3 driver typically provides support for features such as caching (connections, query
results, and so on), load balancing, and advanced system administration such as logging and
auditing.
This driver is very flexible allows access to multiple databases using one driver.
They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the record set may take longer,
since the data comes through the backend server.
Syntax:
public static void forName(String className)throws ClassNotFoundException
Example:
Class.forName("oracle.jdbc.driver.OracleDriver");
Syntax:
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String
password)
Example:
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system","password");
Syntax:
public Statement createStatement()throws SQLException
Example:
Statement stmt=con.createStatement();
Syntax:
public ResultSet executeQuery(String sql)throws SQLException
Example:
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Example: con.close();
First crate table „LOGIN‟ in MS Access database with two fields name (varchar) and password (varchar)
respectively and insert some records into table. Create dsn in ODBC tools named as „mydsn‟:
import java.sql.*;
class Test
{
public static void main(String ar[])
{
try{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
}catch(Exception ee){
System.out.println(ee);
}
}
}
K. JDBC Examples
import java.sql.*;
class SimpleJdbcDemoTwo
{
public static void main(String ar[])
{
try
{
String database="MyDemoDB.accdb";
String url="jdbc:odbc:Driver={Microsoft Access Driver
(*.accdb)};DBQ=" + database +
";DriverID=22;READONLY=true";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");
while(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
}
catch(Exception ee)
{
System.out.println(ee);
}
}
}
Nikita Education ( NET ) [ 9689925884 ] 115
Basics of Advance Java API
2. MySql Connection
import java.sql.*;
class MySqlCon
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql:
//localhost:3306
/mydemodb","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
while(rs.next())
{
System.out.print(rs.getString(1));
System.out.println(" , "+rs.getString(2));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
4. Oracle Connection
import java.sql.*;
class OracleCon
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println( rs.getInt(1)+" "+
rs.getString(2)+" "+
rs.getString(3));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
5. MySQL Connection
import java.sql.*;
class MySqlConTwo
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://
localhost:3306/MyDemoDB","root","root123");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from
StudBasic order by RollNo");
System.out.println("\nRollNo \t Name \t Branch
\t Mobile \t Avg \n");
while(rs.next())
6. PreparedStatement Example
import java.sql.*;
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
String sql = "UPDATE StudBasic set StudBranch=?
WHERE RollNo=?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, "Computer");
stmt.setInt(2, 126130);
while(rs.next())
{
int roll = rs.getInt("RollNo");
String sname = rs.getString("StudName");
String branch= rs.getString("StudBranch");
long mobile=rs.getLong(4);
float avg=rs.getFloat(5);
//Display values
System.out.print("RollNo: " + roll);
System.out.print(", Name: " + sname);
System.out.print(", Branch: " + branch);
System.out.print(", Mobile: " + mobile);
System.out.println(", Avg: " + avg);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e)
{
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{
}
try
{
if(conn!=null)
conn.close();
Example 2:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
preparedStatement.setInt(1, 126162);
preparedStatement.setString(2, "Sapana");
preparedStatement.setString(3, "Mechanical");
preparedStatement.setLong(4, 94234745);
preparedStatement.setFloat(5,92.57f);
while(rs.next())
{
int roll = rs.getInt("RollNo");
String sname = rs.getString("StudName");
String branch= rs.getString("StudBranch");
long mobile=rs.getLong(4);
float avg=rs.getFloat(5);
//Display values
System.out.print("RollNo: " + roll);
System.out.print(", Name: " + sname);
System.out.print(", Branch: " + branch);
System.out.print(", Mobile: " + mobile);
System.out.println(", Avg: " + avg);
}
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
return dbConnection;
}
}
7. ResultSet Metadata
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
8. Database Metadata
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
Unit-V
Servlet & JSP
A. Basic Concepts
World Wide Web: The Web is a network of computers all over the world. All the computers in the
Web can communicate with each other. All the computers use a communication protocol called HTTP.
Web information is stored in documents called web pages. Web pages are files stored on computers
called web servers. Computers reading the web pages are called web clients. Web clients view the
pages with a program called a web browser. Popular browsers are Google Chrome, Firefox, and
Internet Explorer.
Browser: A browser fetches a page from a web server by a request. A request is a standard HTTP
request containing a page address. An address may look like this: http://www.example.com/a.html.
All web pages contain instructions for display. The browser displays the page by reading these
instructions. The most common display instructions are called HTML tags HTML tags look like
this <p>This is a paragraph.</p>
Website: Website is a collection of related web pages that may contain text, images, audio and
video. The first page of a website is called home page. Each website has specific internet address
(URL) that you need to enter in your browser to access a website. Website is hosted on one or more
servers and can be accessed by visiting its homepage using a computer network.
Static Web Page: "Static" means unchanged or constant, static web pages contain the same
prebuilt content each time the page is loaded. Standard HTML pages are static web pages. They
contain HTML code, which defines the structure and content of the Web page. Each time an HTML
page is loaded, it looks the same. The only way the content of an HTML page will change is if the
Web developer updates and publishes the file.
Dynamic Web Page: "dynamic" means changing or lively, the content of dynamic Web pages can
be generated on-the-fly. PHP, ASP, Servlets and JSP pages are dynamic Web pages. These pages
contain "server-side" code, which allows the server to generate unique content each time the page is
loaded. Technologies used to create dynamic web pages are PHP, ASP, JSP, Servlets, CGI etc.
Web Application: A web application is an application accessible from the web used to generate
dynamic responses. A web application is composed of web components like Servlet, JSP, Filter etc.
and other components such as HTML. The web components typically execute in Web Server and
respond to HTTP request.
B. HTTP
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative,
hypermedia information systems. This is the foundation for data communication for the World Wide Web
(i.e. internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes
as well using extensions of its request methods, error codes, and headers. Basically, HTTP is a TCP/IP
based communication protocol, that is used to deliver data (HTML files, image files, query results, etc.) on
the World Wide Web. The default port is TCP 80, but other ports can be used as well. It provides a
standardized way for computers to communicate with each other. HTTP specification specifies how
clients' request data will be constructed and sent to the server, and how the servers respond to these
requests.
HTTP Features:
There are three basic features that make HTTP a simple but powerful protocol:
HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request and after a
request is made, the client disconnects from the server and waits for a response. The server
processes the request and re-establishes the connection with the client to send a response back.
HTTP is media independent: It means, any type of data can be sent by HTTP as long as both
the client and the server know how to handle the data content. It is required for the client as well
as the server to specify the content type using appropriate MIME-type.
HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct result of HTTP
being a stateless protocol. The server and client are aware of each other only during a current
request. Afterwards, both of them forget about each other. Due to this nature of the protocol,
neither the client nor the browser can retain information between different requests across the
web pages.
HTTP Request
An HTTP client sends an HTTP request to a server in the form of a request message which includes
following format:
Request Methods:
GET: The GET method is used to retrieve information from the given server using a given URI.
Requests using GET should only retrieve data and should have no other effect on the data.
HEAD: Same as GET, but it transfers the status line and the header section only.
POST: A POST request is used to send data to the server, for example, customer information, file
upload, etc. using HTML forms.
PUT: Replaces all the current representations of the target resource with the uploaded content.
DELETE: Removes all the current representations of the target resource given by URI.
CONNECT: Establishes a tunnel to the server identified by a given URI.
OPTIONS: Describe the communication options for the target resource.
TRACE: Performs a message loop back test along with the path to the target resource.
GET POST
In case of Get request, only limited amount of In case of post request, large amount of data can
data can be sent because data is sent in header. be sent because data is sent in body.
Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.
Get request can be bookmarked Post request cannot be bookmarked
HTTP Response
After receiving and interpreting a request message, a server responds with an HTTP response message
which includes following format:
Status codes used in response: The Status-Code element is a 3-digit integer where first digit of the
Status-Code defines the class of response and the last two digits do not have any categorization role.
There are 5 values for the first digit.
1xx: Informational It means the request was received and the process is continuing.
2xx: Success It means the action was successfully received, understood, and accepted.
3xx: Redirection It means further action must be taken in order to complete the request.
4xx: Client Error It means the request contains incorrect syntax or cannot be fulfilled.
5xx: Server Error It means the server failed to fulfill an apparently valid request.
Content Type: Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is
a HTTP header that provides the description about what are you sending to the browser. There are
many content types:
text/html application/pdf
text/plain application/octet-stream
application/msword application/x-zip
application/vnd.ms-excel images/jpeg
application/jar video/quicktime etc.
C. Server Software’s
Web Server:
A Web server is a program that, using the client/server model and the World Wide Web's Hypertext
Transfer Protocol ( HTTP ), serves the files that form Web pages to Web users. Two leading Web servers
are Apache , the most widely-installed Web server, and Microsoft's Internet Information Server ( IIS ).
Any computer can be turned into a Web server by installing server software and connecting the machine
to the Internet. A Web server can be either a computer program or a computer running a program that is
responsible for accepting HTTP requests from clients, serving back HTTP responses along with optional
data contents, which usually are web pages such as HTML documents and linked objects on it.
Application Server:
An application server is a program that handles all application operations between users and an
organization's backend business applications or databases. An application server is typically used for
complex transaction-based applications. To support high-end needs, an application server has to have
built-in redundancy, monitor for high-availability, high-performance distributed application services and
support for complex database access. An application server is the kind of software engine that will deliver
various applications to another device.
It's a server used to communicate with Web Browsers as its clients and the communication protocol used
in this case is HTTP (Hyper Text Transfer Protocol). This is why a Web Server is also called an HTTP
Server. The client (i.e., the Web Browser) and the server (i.e., HTTP/Web Server) should be able to
communicate with each other in a defined way. These pre-defined sets of rules which form the basis of
the communication are normally termed as a protocol and in this case the underlying protocol will be
HTTP. Irrespective of how the client or the server has been implemented, there will always be a way to
form a valid HTTP Request for the client to work and similarly the server needs to be capable of
understanding the HTTP Requests sent to it and form valid HTTP Responses to all the arrived HTTP
Requests. Both the client and the server machines should also be equipped with the capability of
establishing the connection to each other (in this case it'll be a TCP reliable connection) to be able to
transfer the HTTP Requests (client -> server) and HTTP Responses (server -> client).
A Web Container is a J2EE compliant implementation which provides an environment for the Servlets
and JSPs to run. Putting it differently we can say that a Web Container is combination of a Servlet Engine
and a JSP Engine. If an HTTP Request refers to a Web Component (typically a Servlet or a JSP) then the
request is forwarded to the Web Container and the result of the request is sent back to Web Server,
which uses that result to prepare the HTTP Response for the particular HTTP Request.
E. Servlet
Servlet technology is used to create web application (resides at server side and generates dynamic web
page). Servet technology is robust and scalable as it uses the java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was used as a server-side programming language. But
there were many disadvantages of this technology. Java 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, you can collect input from
users through web page forms, present records from a database or another source, and create web
pages dynamically. 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.
There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse etc.
Servlet is a technology i.e. used to create web application.
Servlet is an API that provides many interfaces and classes including documentations.
Servlet is an interface that must be implemented for creating any servlet.
Servlet is a class that extends the capabilities of the servers and responds to the incoming
request. It can respond to any type of requests.
Servlet is a web component that is deployed on the server to create dynamic web page.
Servlets 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 (i.e., the document) to the clients (browsers). This document can be sent in a
variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
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.
It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a
static WebPages from the server. If the user wants to read the web pages as per input then the servlet
container is used in java. The servlet container is used in java for dynamically generate the web pages on
the server side. Therefore the servlet container is the part of a web server that interacts with the servlet
for handling the dynamic web pages from the client.
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. It is a older
technology used to generate dynamic responses for client requests.
Disadvantages of CGI
1. If number of client‟s increases, it takes more time for sending response.
2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet:
1. Better performance: because it creates a thread for each request not process.
2. Portability: Servlets are platform-independent because they are written in Java.
3. Robust: Servlets are managed by JVM so no need to worry about memory leak, garbage collection
etc.
4. Secure: because it uses java language...
5. Servlets execute within the address space of a Web server. It is not necessary to create a separate
process to handle each client request.
6. Java security manager on the server enforces a set of restrictions to protect the resources on a server
machine. So servlets are trusted.
7. The full functionality of the Java class libraries is available to a servlet. It can communicate with
applets, databases, or other software via the sockets and RMI mechanisms that you have seen
already.
A development environment is where you would develop your Servlet, test them and finally run them.
Like any other Java program, you need to compile a servlet by using the Java compiler javac and after
compilation the servlet application, it would be deployed in a configured environment to test and run. This
development environment setup involves following steps:
%CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat
After startup, the default web applications included with Tomcat will be available by visiting
http://localhost:8080/. If everything is fine then it should display following result:
Further information about configuring and running Tomcat can be found on the Tomcat web site:
http://tomcat.apache.org. Tomcat can be stopped by executing the following commands on windows
machine: C:\apache-tomcat-5.5.29\bin\shutdown
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to
the compiler. If you are running Windows, you need to set Environment Variables, right-click on My
Computer, select Properties, then Advanced, then Environment Variables.
CLASSPATH: C:\apache-tomcat-5.5.29\common\lib\servlet-api.jar;%CLASSPATH%
Or
Paste the servlet-api.jar file in JRE/lib/ext folder
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following
are the paths followed by a servlet
The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.
The init method is designed to be called only once. It is called when the servlet is first created, and not
called again for each user request. So, it is used for one-time initializations, just as with the init method of
applets. The servlet is normally created when a user first invokes a URL corresponding to the servlet, but
you can also specify that the servlet be loaded when the server is first started. When a user invokes a
servlet, a single instance of each servlet gets created, with each user request resulting in a new thread.
The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write the
formatted response back to the client. Each time the server receives a request for a servlet, the server
spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. Here is the
signature of this method:
The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. The doGet() and doPost() are most frequently used methods
within each service request.
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your
servlet a chance to close database connections, halt background threads, write cookie lists or hit counts
to disk, and perform other such cleanup activities. After the destroy() method is called, the servlet object
is marked for garbage collection. The destroy method definition looks like this:
I. Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol. The javax.servlet.http package contains interfaces and
classes that are responsible for hyper text transfer protocol only.
Interfaces:
Servlet ServletContext ServletRequestListener
ServletRequest SingleThreadModel ServletRequestAttributeListener
ServletResponse Filter ServletContextListener
RequestDispatcher FilterConfig ServletContextAttributeListener
ServletConfig FilterChain
Classes:
GenericServlet ServletResponseWrapper ServletContextAttributeEvent
ServletInputStream ServletRequestEvent ServletException
ServletOutputStream ServletContextEvent UnavailableException
ServletRequestWrapper ServletRequestAttributeEvent
I.1. Interfaces
1. Servlet
Servlet interface provides common behaviour to all the servlets. Servlet interface needs to be
implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that
are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle
methods.
Method Description
public void init(ServletConfig initializes the servlet. It is the life cycle method of servlet and
config) invoked by the web container only once.
public void provides response for the incoming request. It is invoked at each
service(ServletRequest request, request by the web container.
ServletResponse response)
public void destroy() is invoked only once and indicates that servlet is being destroyed.
public ServletConfig returns the object of ServletConfig.
getServletConfig()
public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
2. ServletConfig
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.
Methods:
public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
public Enumeration getInitParameterNames():Returns an enumeration of all the initialization
parameter names.
public String getServletName():Returns the name of the servlet.
3. ServletContext
An object of ServletContext is created by the web container at time of deploying the project. This object
can be used to get configuration information from web.xml file. There is only one ServletContext object
per web application. If any information is shared to many servlet, it is better to provide it from the
web.xml file using the <context-param> element.
Methods:
public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
public void setAttribute(String name,Object object):sets the given object in the application scope.
public Object getAttribute(String name):Returns the attribute for the specified name.
public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
public void removeAttribute(String name):Removes the attribute with the given name from the
servlet context.
4. ServletRequest
An object of ServletRequest is used to provide the client request information to a servlet such as content
type, content length, parameter names and values, header informations, attributes etc.
Method Description
public String is used to obtain the value of a parameter by name.
getParameter(String name)
public String[] returns an array of String containing all values of given
getParameterValues(String parameter name. It is mainly used to obtain values of a Multi
name) select list box.
java.util.Enumeration returns an enumeration of all of the request parameter names.
getParameterNames()
public int getContentLength() Returns the size of the request entity data, or -1 if not known.
public String Returns the character set encoding for the input of this request.
getCharacterEncoding()
public String getContentType() Returns the Internet Media Type of the request entity data, or
null if not known.
public ServletInputStream Returns an input stream for reading binary data in the request
getInputStream() throws body.
IOException
public abstract String Returns the host name of the server that received the request.
getServerName()
public int getServerPort() Returns the port number on which this request was received.
5. ServletResponse
The ServletResponse interface contains various methods that enable a servlet to respond to the client
requests. A servlet can send the response either as character or binary data. The PrintWriter stream can
be used to send character data as servlet response, and ServletOutputStream stream to send binary data
as servlet response.
Methods Description
PrintWriter getWriter() returns a PrintWriter object that can send character text to the client.
void setBufferSize(int size) Sets the preferred buffer size for the body of the response
void setContentLength(int Sets the length of the content body in the response In HTTP servlets,
len) this method sets the HTTP Content-Length header
void setContentType(String sets the content type of the response being sent to the client before
type) sending the respond.
void setBufferSize(int size) sets the preferred buffer size for the body of the response.
boolean isCommitted() returns a boolean indicating if the response has been committed
void setLocale(Locale loc) sets the locale of the response, if the response has not been committed
yet.
I.2. Classes
1. GenericServlet
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the
implementaion of all the methods of these interfaces except the service method. GenericServlet class can
handle any type of request so it is protocol-independent. You may create a generic servlet by inheriting
the GenericServlet class and providing the implementation of the service method.
Methods
public void init(ServletConfig config) is used to initialize the servlet.
public void init() it is a convenient method for the servlet programmers, now there is no need to call
super.init(config)
public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml
file.
public String getServletName() returns the name of the servlet object.
public void log(String msg) writes the given message in the servlet log file.
public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a
stack trace.
2. ServletInputStream
ServletInputStream class provides stream to read binary data such as image etc. from the request
object. It is an abstract class. The getInputStream() method of ServletRequest interface returns the
instance of ServletInputStream class. So can be get as:
ServletInputStream sin=request.getInputStream();
Method: int readLine(byte[] b, int off, int len) : it reads the input stream.
3. ServletOutputStream
ServletOutputStream class provides a stream to write binary data into the response. It is an abstract
class. The getOutputStream() method of ServletResponse interface returns the instance of
ServletOutputStream class. It may be get as:
ServletOutputStream out=response.getOutputStream();
Methods:
void print(boolean b){} void print(double d){} void println(int i){}
void print(char c){} void print(String s){} void println(long l){}
void print(int i){} void println{} void println(float f){}
void print(long l){} void println(boolean b){} void println(double d){}
void print(float f){} void println(char c){} void println(String s){}
4. ServletException
javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet
problem has occurred. The second is UnavailableException, which extends ServletException. It
indicates that a servlet is unavailable.
Interfaces:
HttpServletRequest HttpSessionAttributeListener
HttpServletResponse HttpSessionBindingListener
HttpSession HttpSessionActivationListener
HttpSessionListener HttpSessionContext (deprecated now)
Classes:
HttpServlet HttpSessionEvent
Cookie HttpSessionBindingEvent
HttpServletRequestWrapper HttpUtils (deprecated now)
HttpServletResponseWrapper
I.3. Interfaces
1. HttpServletRequest
Method Summary
String getContextPath() Returns the portion of the request URI that indicates
the context of the request.
Cookie[] getCookies() Returns an array containing all of the Cookie objects the
client sent with this request.
String getHeader(java.lang.String name) Returns the value of the specified
request header as a String.
String getMethod() Returns the name of the HTTP method with which this
request was made, for example, GET, POST, or PUT.
String getPathInfo() Returns any extra path information associated with the
URL the client sent when it made this request.
StringBuffer getRequestURL() Reconstructs the URL the client used to make the
request.
String getServletPath() Returns the part of this request's URL that calls the
servlet.
HttpSession getSession() Returns the current session associated with this request, or
if the request does not have a session, creates one.
void login(java.lang.String username, java.lang.String password) Validate the
provided username and password in the password validation realm used by
the web container login mechanism configured for the ServletContext.
void logout() Establish null as the value returned when getUserPrincipal,
getRemoteUser, and getAuthType is called on the request.
2. HttpServletResponse
The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Several
constants are defined. These correspond to the different status codes that can be assigned to an HTTP
response. For example, SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND
indicates that the requested resource is not available.
Method Summary
void addCookie(Cookie cookie) Adds the specified cookie to the response.
void addHeader(java.lang.String name, java.lang.String value) Adds a response header with the
given name and value.
String encodeRedirectURL(java.lang.String url) Encodes the specified URL for use in the
sendRedirect method or, if encoding is not needed, returns the URL unchanged.
String encodeURL(java.lang.String url) Encodes the specified URL by including the session ID in it,
or, if encoding is not needed, returns the URL unchanged.
void sendError(int sc, java.lang.String msg) Sends an error response to the client using the
specified status and clears the buffer.
void sendRedirect(java.lang.String location) Sends a temporary redirect response to the client
using the specified redirect location URL and clears the buffer.
void setHeader(java.lang.String name, java.lang.String value) Sets a response header with the
given name and value.
void setStatus(int sc) Sets the status code for this response.
3. HttpSession
The HttpSession interface enables a servlet to read and write the state information that is associated with
an HTTP session. HttpSession object is used to store entire session with a specific client. We can store,
retrieve and remove attribute from HttpSession object. Any servlet can have access
to HttpSession object throughout the getSession() method of the HttpServletRequest object.
Methods Description
long getCreationTime() returns the time when the session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
String getId() returns a string containing the unique identifier assigned to the
session.
long getLastAccessedTime() returns the last time the client sent a request associated with the
session
int getMaxInactiveInterval() returns the maximum time interval, in seconds.
void invalidate() destroy the session
boolean isNew() returns true if the session is new else false
void setMaxInactiveInterval(int Specifies the time, in seconds,after servlet container will invalidate
interval) the session.
I.4. Classes
1. HttpServlet
The HttpServlet class extends the GenericServlet class and implements Serializable interface. HttpServlet
is also an abstract class. This class gives implementation of various service() methods
of Servlet interface. To create a servlet, we should create a class that extends HttpServlet abstract
class. The Servlet class that we will create, must not override service() method. Our servlet class will
override only the doGet() and/or doPost() methods. The service() method of HttpServlet class listens to
the Http methods (GET, POST etc) from request stream and invokes doGet() or doPost() methods based
on Http Method type.
Methods
public void service(ServletRequest req,ServletResponse res) dispatches the request to the
protected service method by converting the request and response object into http type.
protected void service(HttpServletRequest req, HttpServletResponse res) receives the request
from the service method, and dispatches the request to the doXXX() method depending on the incoming
2. Cookies
Cookies are small pieces of information that are sent in response from the web server to the
client. Cookies are the simplest technique used for storing client state. Cookies are stored on client's
computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan. It is
information for future use that is stored by the server on the client side of a client/server communication.
Cookies are usually small text files, given ID tags that are stored on your computer's browser directory or
program data subfolders. Cookies are created using Cookie class present in Servlet API. Cookies are
added to response object using the addCookie() method. This method sends cookie information over the
HTTP response stream. getCookies() method is used to access the cookies that are added to response
object.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be changed
after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
J. Servlet Development
The directory structure is a hierarchy of folders that defines where to put the different types of files so
that web container may get the information and respond to the client. The Sun Microsystem defines a
unique standard to be followed by all the server vendors. Let's see the directory structure that must be
followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The web.xml file must
be under the WEB-INF folder.
The HttpServlet class is widely used to create the servlet because it provides methods to handle http
requests such as doGet(), doPost, doHead() etc.
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache Tomcat
server servlet-api.jar file is required to compile a servlet class.
NOTE: After compiling your Servlet class you will have to paste the class file into WEB-
INF/classes/ directory.
The deployment descriptor is an xml file, from which Web Container gets the information about the
servlet to be invoked. The web container uses the Parser to get the information from the web.xml file.
There are many xml parsers such as SAX, DOM and Pull. There are many elements in the web.xml file.
Here is given some necessary elements to run the simple servlet program.
web.xml file
<web-app>
<servlet>
<servlet-name>MyFirstHttpServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> MyFirstHttpServlet </servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
There are too many elements in the web.xml file. Here is the illustration of some elements that is used in
the above web.xml file. The elements are as follows:
To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.
Copy the project and paste it in the webapps folder under apache tomcat.
It is important to learn how servlet works for understanding the servlet well. Here, we are going to get
the internal detail about the first servlet program. The server checks if the servlet is requested for the
first time.
If yes, web container does the following tasks:
loads the servlet class.
instantiates the servlet class.
calls the init method passing the ServletConfig object
else
calls the service method passing request and response objects
The web container calls the destroy method when it needs to remove the servlet such as at time of
stopping server or undeploying the project.
L. RequestDispatcher
The RequestDispacher 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.
Methods Description
void forward(ServletRequest request, forwards a request from a servlet to another resource
ServletResponse response) (servlet, JSP file, or HTML file) on the server
void include(ServletRequest request, includes the content of a resource (servlet, JSP page,
ServletResponse response) HTML file) in the response
Session: The session of activity that a user with a unique IP address spends on a Web site during a
specified period of time. The number of user sessions on a site is used in measuring the amount of traffic
a Web site gets. The site administrator determines what the time frame of a user session will be (e.g., 30
minutes). If the visitor comes back to the site within that time period, it is still considered one user
session because any number of visits within that 30 minutes will only count as one session. If the visitor
returns to the site after the allotted time period has expired, say an hour from the initial visit, then it is
counted as a separate user session. session: an abstract concept to represent a series of HTTP requests
and responses between a specific Web browser and server. HTTP doesn't support the notion of a session,
but Java does.
Session tracking is the capability of a server to maintain the current state of a single client‟s sequential
requests. The HTTP protocol used by Web servers is stateless. This means that every transaction is
autonomous. This type of stateless transaction is not a problem unless you need to know the sequence of
actions a client has performed while at your site. Session Management is a mechanism used by
the Web container to store session information for a particular user.
Session simply means a particular interval of time. Session Tracking is a way to maintain state (data)
of an 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 an 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:
The basic concept behind session is, whenever a user starts using our application, we can save a unique
identification information about him, in an object which is available throughout the application, until its
destroyed. So wherever the user goes, we will always have his information and we can always manage
which user is doing what. Whenever a user wants to exit from your application, destroy the object with
his information.
Cookies: You can use HTTP cookies to store information. Cookies will be stored at browser side.
URL rewriting: With this method, the information is carried through url as request parameters. In
general added parameter will be sessionid, userid.
HttpSession: Using HttpSession, we can store information at server side. Http Session provides
methods to handle session related information.
Hidden form fields: By using hidden form fields we can insert information in the webpages and
these information will be sent to the server. These fields are not visible directly to the user, but can
be viewed using view source option from the browsers. The hidden form fields are as given below:
<input type='hidden' name='siteName' value='nspl'/>
1. Cookies
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.
Types of Cookie
1. Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
2. Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.
2. URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We
can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from
another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to
obtain a parameter value.
3. HttpSession
In such case, container creates a session id for each user. The container uses this id to identify the
particular user. An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time, and
last accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. public HttpSession getSession():Returns the current session associated with this request, or if
the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.
In such case, we store the information in the hidden field and get it from another servlet. This approach
is better if we have to submit form in all the pages and we don't want to depend on the browser. Let's
see the code to store value in hidden field.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
O. Examples
MyGenericServlet.java
import java.io.*;
import javax.servlet.*;
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<description>
Generic Servlet Example.
</description>
<servlet>
<servlet-name>nsplservlet</servlet-name>
<servlet-class>MyGenericServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>nsplservlet</servlet-name>
<url-pattern>/nspl</url-pattern>
</servlet-mapping>
</web-app>
welcome.html
<html>
<head>
<title> Nikita Education [NET] </title>
</head>
<body>
<h1>Hello, you have successfully
executed the GenericServlet</h1>
</body>
</html>
Nikita Education ( NET ) [ 9689925884 ] 151
Basics of Advance Java API
2. HttpServlet Example
login.html
<html>
<head>
<title>NSPL HttpServletDemo - Login Page </title>
</head>
<body>
<h1> Welcome to Nikita Education [NET] </h1>
<hr><br>
<form name=form1 method=get action="/nspl/nsplhttpservlet">
<b> Enter User Name : </b>
<input type=text name=text1 size=35 value=""/><br>
<b> Enter User Pass : </b>
<input type=text name=text2 size=35 value=""/>
<br><br><br>
<input type=submit name=submit1 value="Login"/>
<input type=submit name=submit2 value="Cancel"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<description>
NSPL - Http Servlet Examples.
</description>
<servlet>
<servlet-name>nsplhttpserv</servlet-name>
<servlet-class>nsplhttpservlet.MyHttpServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>nsplhttpserv</servlet-name>
<url-pattern>/nsplhttpservlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
MyHttpServletDemo.java
package nsplhttpservlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
3. RequestDispatcher Example
login.html
<form action="go" method="get" action=”/go”>
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Simple</servlet-name>
<servlet-class>Simple</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Simple</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
Nikita Education ( NET ) [ 9689925884 ] 153
Basics of Advance Java API
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Simple.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
String p=request.getParameter("userPass");
if(p.equals("servlet")){
RequestDispatcher rd=request.getRequestDispatcher("welcome");
rd.forward(request, response);
}
else{
out.print("Sorry username or password error!");
RequestDispatcher rd=request.getRequestDispatcher("login.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
4. sendRedirect() Example
index.html
<html>
<head>
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>GoogleSearcher</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MySearcher</servlet-name>
<servlet-class>MySearcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MySearcher</servlet-name>
<url-pattern>/MySearcher</url-pattern>
</servlet-mapping>
</web-app>
MySearcher.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
1. Cookies
cookies.html
<html>
<head>
<title> NSPL - Cookies Demo </title>
</head>
<body>
<h1> Welcome to Nikita Education [NET] </h1>
<hr><br>
<form name=form1 method=post action="/myCookieApps/addcookieserv">
<b> Enter a value for cookie : </b>
<input type=text name=text1 size=25 value=""/>
<br><br>
<input type=submit name=submit1 value="AddCookie"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>addcookieserv</servlet-name>
<servlet-class>mycookies.AddCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addcookieserv</servlet-name>
<url-pattern>/addcookieserv</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>getcookieserv</servlet-name>
<servlet-class>mycookies.GetCookiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getcookieserv</servlet-name>
<url-pattern>/getcookieserv</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>cookies.html</welcome-file>
</welcome-file-list>
</web-app>
AddCookieServlet.java
package mycookies;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.addCookie(cook);
response.setContentType("text/html");
Nikita Education ( NET ) [ 9689925884 ] 156
Basics of Advance Java API
PrintWriter out=response.getWriter();
out.println("<h2> my cookie has been set to : "+data+"</h2>");
out.close();
}
}
GetCookiesServlet.java
package mycookies;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<b>");
for (int i=0;i<cookies.length ; i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
out.println("name : "+name+"<br> value : "+value+"<br>");
}
out.println("</b>");
out.close();
}
}
2. URL Rewriting
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
Nikita Education ( NET ) [ 9689925884 ] 157
Basics of Advance Java API
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.close();
}catch(Exception e){System.out.println(e);}
}
}
3. HttpSession
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
index.html
<form action="go" method="get">
Name:<input type="text" name="uname"/><br/>
<input type="submit" value="go"/>
</form>
web.xml
<web-app>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
Nikita Education ( NET ) [ 9689925884 ] 160
Basics of Advance Java API
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Unit-V
Servlet & JSP
A. Introduction to JSP
JSP technology is used to create web application just like Servlet technology. It can be thought of as an
extension to servlet because it provides more functionality than servlet such as expression language, jstl
etc. A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than servlet
because we can separate designing and development. It provides some additional features such as
Expression Language, Custom Tag etc. Java Server 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 Java Server 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.
Importance of JSP
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages
itself instead of having a separate CGI files.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server
to load an interpreter and the target script each time the page is requested.
Java Server Pages are built on top of the Java Servlets API, so like Servlets; JSP also has access to all
the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Advantages of JSP
vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is
written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to
use. Second, it is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty
of println statements that generate the HTML.
vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real"
programs that use form data, make database connections, and the like.
vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing etc.
vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
Extension to Servlet: JSP technology is the extension to 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.
Easy to maintain: JSP can be easily managed because we can easily separate our business logic
with presentation logic. In servlet technology, we mix our business logic with the presentation logic.
Fast Development (No need to recompile and redeploy): If JSP page is modified, we don't
need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if
we have to change the look and feel of the application.
Less code than Servlet: In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc.
that reduces the code. Moreover, we can use EL, implicit objects etc.
B. JSP Architecture
The web server needs a JSP engine i.e. container to process JSP pages. The JSP container is responsible
for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP
container to support JSP pages development. A JSP container works with the Web server to provide the
runtime environment and other services a JSP needs. It knows how to understand the special elements
that are part of JSPs. Following diagram shows the position of JSP container and JSP files in a Web
Application.
JSP Processing:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.
This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into servlet content. This conversion is
very simple in which all template text is converted to println( ) statements and all JSP elements are
converted to Java code that implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request to a
servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format, which the servlet engine passes to the web
server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly
as if it were a static page.
Typically the JSP engine checks to see whether a servlet for a JSP file already exists and modification date
on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP container
assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's contents. This
makes the process more efficient than with other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet.
The key to understanding the low-level functionality of JSP is to understand the simple life cycle they
follow. 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. The
following are the paths followed by a JSP
Compilation
Initialization
Execution
Cleanup
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. The compilation process involves three steps:
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
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:
Typically initialization is performed only once and as with the servlet init method, you generally initialize
database connections, open files, and create lookup tables in the jspInit method.
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
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:
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of the
HTTP methods ie. GET, POST, DELETE etc.
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or closing
open files. The jspDestroy() method has the following form:
Web flow starts from a request being made by user's browser, the request is made as http request so
that server can understand it. Based on request the server searches for an appropriate resource and
sends it back to client in form of http response.
1. Http Request: A http request basically have three major components.
1. HTTP method, there are 7 methods defined in java servlets but most of the time you will see
either a get or post method. We will get to know about these methods and their usage in later
part of this blog.
2. The requested page URL, the page to access like www.google.com.
3. Parameters, parameters(as id, name, email.. etc.) are being send as part of request on which the
response is being generated.
2. Http Response: A http request basically have three major components.
1. A status code, this code tells the browser whether the request is successful or not.
2. Content type, it tells the browser about the type of content that response web page contains in it
(text, picture, html...etc).
3. The content, the important and last information that is the served resource that the user was
requested.
To create the first jsp page, write some html code as given below, and save it by .jsp extension. We have
save this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in apache
tomcat to run the jsp page.
index.jsp
<html> How to run a simple JSP Page?
<body> Start the apache tomcat server
<% out.print(2*5); %> put the jsp file in a folder and deploy on the
</body> server
</html> visit the browser by the url :
Output: 10 http://localhost:portno/contextRoot/jspfile
[it will print on web page inside web browser] e.g. http://localhost:8080/myapplication/index.jsp
F. JSP API
Interfaces Classes
1. JspPage JspWriter JspEngineInfo
2. HttpJspPage PageContext JspException
JspFactory JspError
1. JspPage
According to the JSP specification, all the generated servlet classes must implement the JspPage
interface. It extends the Servlet interface. It provides two life cycle methods.
Methods of JspPage interface
1. public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP page is
requested firstly. It is used to perform initialization. It is same as the init() method of Servlet
interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP before the JSP
page is destroyed. It can be used to perform some clean up operation.
2. HttpJspPage
The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage interface.
Method of HttpJspPage interface:
1. public void _jspService(): It is invoked each time when request for the JSP page comes to the
container. It is used to process the request. The underscore _ signifies that you cannot override
this method.
In JSP, java code can be written inside the jsp page using different JSP elements called as scripting
elements. Following are the three different scripting elements of jsp:
scriptlet tag
expression tag
declaration tag
Example
In this example, we have created two files index.html and welcome.jsp. The index.html file gets the
username from the user and the welcome.jsp file prints the username with the welcome message.
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>
Example
To display the current time, we have used the getTime() method of Calendar class. The getTime() is an
instance method of Calendar class, so we have called it after getting the instance of Calendar class by the
getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
In this example, we are printing the username using the expression tag. The index.html file gets the
username and sends the request to the welcome.jsp file, which displays the username.
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
Example
In this example of JSP declaration tag, we are declaring the field and printing the value of the declared
field using the jsp expression tag.
index.jsp
<html>
<body>
</body>
</html>
Example
In this example of JSP declaration tag, we are defining the method which returns the cube of given
number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call
the declared method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
There are 9 jsp implicit objects. These objects are created by the web containers that are available to
all the jsp pages.
Object Class
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
H.1. out
For writing any data to the buffer, JSP provides an implicit object named out. It is the object of JspWriter.
In case of servlet you need to write:
1. PrintWriter out=response.getWriter();
But in JSP, you don't need to write this code.
Example:
index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
H.2. request
The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by the
web container. It can be used to get request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc. It can also be used to set, get
and remove attributes from the jsp request scope. Let's see the simple example of request implicit object
where we are printing the name of the user with welcome message.
Example
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
Output
H.3. response
Example
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
Output
H.4. config
In JSP, config is an implicit object of type ServletConfig. This object can be used to get initialization
parameter for a particular JSP page. The config object is created by the web container for each jsp page.
Generally, it is used to get initialization parameter from the web.xml file.
Example
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
Output
H.5. application
In JSP, application is an implicit object of type ServletContext. The instance of ServletContext is created
only once by the web container when application or project is deployed on the server. This object can be
used to get initialization parameter from configuration file (web.xml). It can also be used to get, set or
remove attribute from the application scope. This initialization parameter can be used by all jsp pages.
Example
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
Output
H.6. session
In JSP, session is an implicit object of type HttpSession. The Java developer can use this object to set, get
or remove attribute or to get session information.
Example
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Output
H.7. pageContext
In JSP, pageContext is an implicit object of type PageContext class. The pageContext object can be used
to set, get or remove attribute from one of the following scopes:
page (default scope of jsp)
request
session
application
Example
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
Output
H.8. page
In JSP, page is an implicit object of type Object class. This object is assigned to the reference of auto
generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type. For example:
Since, it is of type Object it is less used because you can use this object directly in jsp.For example:
H.9. exception
In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to print
the exception. But it can only be used in error pages. It is better to learn it after page directive.
Example
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
I. JSP Directives
The jsp directives are messages that tell 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
I.1. page
The page directive defines attributes that apply to an entire JSP page.
Attributes:
import info isELIgnored
contentType buffer isThreadSafe
extends language autoFlush
session pageEncoding errorPage
isErrorPage
import
The import attribute is used to import class,interface or all the members of a package.It is similar to
import keyword in java class or interface.
Example
<html>
<body>
</body>
</html>
contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response.The default value is "text/html;charset=ISO-8859-1".
Example
<html>
<body>
</body>
</html>
extends
The extends attribute defines the parent class that will be inherited by the generated servlet. It is rarely
used.
info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
Example
<html>
<body>
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The
default size of the buffer is 8Kb.
Example
<html>
<body>
</body>
</html>
language
The language attribute specifies the scripting language used in the JSP page. The default value is "java".
isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is
false i.e. Expression Language is enabled by default. We see Expression Language later.
1. <%@ page isELIgnored="true" %>//Now EL will be ignored
isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false, the
web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a
request before passing another request to it.If you make the value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
1. public class SimplePage_jsp extends HttpJspBase
2. implements SingleThreadModel{
3. .......
4. }
errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be
redirected to the error page.
Example: index.jsp
<body>
</body>
</html>
isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page. Note: The
exception object can only be used in the error page.
Example: myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
I.2. include
The include directive is used to include the contents of any resource it may be jsp file, html file or text
file. The include directive includes the original content of the included resource at page translation time
(the jsp page is translated only once so it will be better to include static resource). Advantage is Code
Reusability.
Example
In this example, we are including the content of the header.html file. To run this example you must
create an header.html file.
<html>
<body>
</body>
</html>
I.3. taglib
The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag
Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be better
to learn it in custom tag.
Example
In this example, we are using our tag named currentDate. To use this tag we must specify the taglib
directive so the container may get information about the tag.
<html>
<body>
<mytag:currentDate/>
</body>
</html>
The exception is normally an object that is thrown at runtime. Exception Handling is the process to
handle the runtime errors. There may occur exception any time in your web application. So handling
exceptions is a safer side for the web developer. In JSP, there are two ways to perform exception
handling:
1. By errorPage and isErrorPage attributes of page directive
2. By <error-page> element in web.xml file
process.jsp for dividing the two numbers and displaying the result
error.jsp for handling the exception
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
This approach is better if you want to handle any exception. If you know any specific error code and you
want to handle that exception, specify the error-code element instead of exception-type as given below:
<web-app>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
K. Action Tags
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.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development.
K.1. jsp:forward
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or
another resource.
</body>
</html>
printdate.jsp
<html>
<body>
</body>
</html>
K.2. jsp:include
The jsp:include action tag is used to include the content of another resource it may be jsp, html or
servlet. The jsp include action tag includes the resource at request time so it is better for dynamic
pages because there might be changes in future. The jsp:include tag can be used to include static as
well as dynamic pages. Code reusability : We can use a page many times such as including header and
footer pages in all pages. So it saves a lot of time.
L. javaBean
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
System.out.println(e.getName());
}
}
Note: There are two ways to provide values to the object, one way is by constructor and
second is by setter method.
jsp:useBean
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. But if object of bean is not created,
it instantiates the bean.
Example
}
index.jsp
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Output
The setProperty and getProperty action tags are used for developing web application with Java Bean. In
web devlopment, bean class is mostly used because it is a reusable software component that represents
data. The jsp:setProperty action tag sets a property value or values in a bean using the setter
method.
Example of jsp:setProperty action tag if you have to set all the values of incoming request in
the bean
Example of jsp:setProperty action tag if you have to set value of the incoming specific
property
Example of jsp:setProperty action tag if you have to set a specific value in the property
jsp:getProperty
Example
index.html for input of values
welocme.jsp file that sets the incoming values to the bean object and prints the one value
User.java bean class that have setter and getter methods
index.html
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>
process.jsp
<jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
User.java
package org.sssit;
Let's see the simple example, that prints the data of bean object in two jsp pages.
index.jsp
Same as above.
User.java
Same as above.
process.jsp
second.jsp
In some case, you may get some value from the database, that is to be set in the bean object, in such
case, you need to use expression tag. For example:
process.jsp
The jsp:plugin action tag is used to embed applet in the jsp file. The jsp:plugin action tag downloads
plugin at client side to execute an applet or bean.
In this example, we are simply displaying applet in jsp using the jsp:plugin tag. You must have
MouseDrag.class file (an applet class file) in the current folder where jsp file resides. You may simply
download this program that contains index.jsp, MouseDrag.java and MouseDrag.class files to run this
application.
index.jsp
1. <html>
2. <head>
3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
4. <title>Mouse Drag</title>
5. </head>
6. <body bgcolor="khaki">
7. <h1>Mouse Drag Example</h1>
8.
9. <jsp:plugin align="middle" height="500" width="500"
10. type="applet" code="MouseDrag.class" name="clock" codebase="."/>
11.
12. </body>
13. </html>
The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component,
and other objects like request, session, application etc. There are many implicit objects, operators and
reserve words in EL. It is the newly added feature in JSP technology version 2.0.
Example:
<jsp:include page="${location}">
Where location variable is separately defines in the jsp page. Expressions can also be used
in jsp:setProperty to set a properties value, using other bean properties like : If we have a bean
named Square with properties length, breadth and area.
<h1>Welcome ${name}</h1>
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive
as below:
Example of EL
index.jsp
<form method="POST" action="welcome.jsp">
Name <input type="text" name="user" >
<input type="submit" value="Submit">
</form>
welcome.jsp
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome ${param.name}</h1>
</body>
</html>
Reserve words in EL
lt le gt ge
eq ne true false
and or not instanceof
div mod empty null
O. JSTL
JSP Standard Tag Library (JSTL) is a standard library of readymade tags. The JSTL contains several tags
that can remove scriptlet code from a JSP page by providing some ready to use, already implemented
common functionalities.
Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
1. JSTL Core: JSTL Core provides several core tags such as if, forEach, import, out etc to support
some basic scripting task. Url to include JSTL Core Tag inside JSP page is
2. JSTL Formatting: JSTL Formatting library provides tags to format text, date, number for
Internationalised web sites. Url to include JSTL Formatting Tags inside JSP page is
3. JSTL sql: JSTL SQL library provides support for Relational Database Connection and tags to
perform operations like insert, delete, update, select etc on SQL databases. Url to include JSTL
SQL Tag inside JSP page is
4. JSTL XML: JSTL XML library provides support for XML processing. It provides flow control,
transformation features etc. Url to include JSTL XML Tag inside JSP page is
5. JSTL functions: JSTL functions library provides support for string manipulation. Url to include
JSTL Function Tag inside JSP page is
The JSTL core library contains several tags that can be used to eliminate the basic scripting overhead
such as for loop, if...else conditions etc from a JSP Page. Let's study some important tags of JSTL Core
library.
JSTL if tag: The if tag is a conditional tag used to evaluate conditional expressions. When a body is
supplied with if tag, the body is evaluated only when the expression is true. For Example :
JSTL out tag: The out tag is used to evaluate an expression and write the result to JspWriter. For
Example :
JSTL forEach tag: This tag provides a mechanism for iteration within a JSP page. JSTL forEachtag
works similarly to enhanced for loop of Java Technology. You can use this tag to iterate over an
existing collection of items. For Example :
JSTL choose, when, otherwise tag: These are conditional tags used to implement conditional
operations. If the test condition of the when tag evaluates to true, then the content within when tag
is evaluated, otherwise the content within the otherwise tag is evaluated.
We can also implement if-else-if construct by using multiple when tag. The when tags are mutually
exclusive, that means the first when tag which evaluates to true is evaluated and then, the control
exits the choose block. If none of the when condition evaluates to true, then otherwise condition is
evaluated. For Example
<c:otherwise>
<p> Neither divisible by 2 nor 5 : ${tutorial.key} </p><br/>
</c:otherwise>
</c:choose>
</c:forEach>
</body>
</html>
JSTL import tag: < c:import> tag is used to dynamically add the contents from the provided URL to
the current page, at request time. The URL resource used in the < c:import> url attribute can be from
outside the web Container. For Example :
JSTL url tag: The JSTL url tag is used to store a url in a variable and also perform url rewriting when
necessary. For Example
JSTL set tag: The JSTL set tag is used to store a variable in specified scope or update the property
of JavaBean instance. Following is the example of setting the name property of a Student bean :
JSTL catch tag: The JSTL catch tag is used to handle exception and doesn't forward the page to the
error page. For Example :
When EL and Standard Action elements aren't enough to remove scriptlet code from your JSP Page, you
can use Custom Tags. Custom tags are nothing but user-defined tags. Custom tags are an excellent way
to abstract the complexity of business logic from the presentation of Web pages in a way that is easy for
the Web author to use and control. It also allows for reusability as custom tags can be used again and
again.
Syntax
The format of a custom tag can either be empty, called an Empty tag, or can contain a body, called
a Body tag. The number of attributes that a tag will accept depends on the implementation of the Tag
Handler class.
The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom tag API. The JspTag
is the root interface in the Custom Tag hierarchy.
CountMatches.java
package com.studytonight.taghandler;
import java.io.IOException;
import javax.servlet.jsp.*;
import org.apache.commons.lang.StringUtils;
@Override
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
out.println(StringUtils.countMatches(inputstring, lookupstring));
}
catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
}
In the above code, we have an implementation of the doStartTag() method which is must if we are
extending TagSupport class. We have declared two variables inputstring and lookupstring. These
variables represents the attributes of the custom tag. We must provide getter and setter for these
variables in order to set the values into these variables that will be provided at the time of using this
custom tag. We can also specify whether these attributes are required or not.
CountMatchesDescriptor.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>cntmtchs</shortname>
<info>Sample taglib for Substr operation</info>
<uri>http://studytonight.com/jsp/taglib/countmatches</uri>
<tag>
<name>countmatches</name>
<tagclass>com.studytonight.taghandler.CountMatches</tagclass>
<info>String Utility</info>
<attribute>
<name>inputstring</name>
<required>true</required>
</attribute>
<attribute>
<name>lookupstring</name>
<required>true</required>
</attribute>
</tag>
</taglib>
The taglib element specifies the schema, required JSP version and the tags within this tag library.
Each tag element within the TLD represents an individual custom tag that exist in the library. Each of
these tag should have a tag handler class associated with them.
The uri element represents a Uniform Resource Identifier that uniquely identifies the tag library. The
two attribute elements within the tag element represents that the tag has two attributes and
the true value provided to the required element represents that both of these attributes are required for
the tag to function properly.
test.jsp
<%@taglib prefix="mytag" uri="/WEB-INF/CountMatchesDescriptor.tld"%>
<html>
<mytag:countmatches inputstring="Studytonight" lookupstring="t">
</mytag:countmatches>
</html>
If this tag works fine it should print a value 3 in the browser as there 't' occurs 3 times in the word
'Studytonight'.
Q. Introduction to RMI
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another JVM.
The RMI provides remote communication between the applications using two objects stub and skeleton.
RMI (Remote Method Invocation) is a way that a programmer, using the Java programming language and
development environment, can write object-oriented programming in which objects on different
computers can interact in a distributed network. RMI is the Java version of what is generally known as a
remote procedure call (RPC), but with the ability to pass one or more objects along with the request. The
object can include information that will change the service that is performed in the remote computer.
Remote Method Invocation (RMI) facilitates object function calls between Java Virtual Machines (JVMs).
RMI Architecture
Application Layer
This layer is nothing but the actual systems (client and server) involved in communication. A client Java
program communicates with the other Java program on the server side. RMI is nothing but a
communication between two JVMs placed on different systems.
The proxy layer consists of proxies (named as stub and skeleton) for client and server. Stub is client
side proxy and Skeleton is server side proxy. The stub/skeleton layer is the interface between the
application layer and the rest of the RMI system. This layer does not deal with specifics of any transport,
but transmits data to the remote reference layer via the abstraction of marshal streams. Marshaling is
nothing but converting data into a special format suitable to pass through the distributed environment
without losing object persistence. Un-marshaling is the process of extracting marshaled data into its
original format. Stub performs the marshaling, whereas Skeleton performs the un-marshaling.
o Stub
The stub is a client-side object that represents (or acts as a proxy for) the remote object.
Sequence of events performed by the stub:
Initiates a connection with the remote VM containing the remote object
Marshals (writes and transmits) the parameters to the remote VM.
Waits for the result of the method invocation.
Unmarshals (reads) the return value or exception returned.
Return the value to the caller
o Skeleton
On the server side, the skeleton object takes care of all the details of “remoteness” so that the
actual remote object does not need to worry about them. Sequence of events performed by the
skeleton:
Unmarshals (reads) the parameters for the remote method (remember that these were
marshaled by the stub on the client side)
Invokes the method on the actual remote object implementation.
Marshals (writes and transmits) the result (return value or exception) to the caller (which is
then unmarshalled by the stub)
Proxies are implicitly connected to RMI mechanism through Remote reference layer, the layer responsible
for object communication and transfer of objects between client and server. It is responsible for dealing
with semantics of remote invocations and implementation – specific tasks with remote objects. In this
layer, actual implementation of communication protocols is handled.
Unicast point-to-point invocation.
Invocation to replicated object groups.
Support for a specific replication strategy.
Support for a persistent reference to the remote object (enabling activation of the remote object).
Reconnection strategies (if remote object becomes inaccessible).
Transport layer does not exist separately but is a part of Remote reference layer. Transport layer is
responsible for actually setting up connections and handling the transport of data from one machine to
another. It can be modified to handle encrypted streams, compression algorithms and a number of other
security/performance related enhancements. In general, the transport layer of the RMI system is
responsible for:
Setting up connections to remote address spaces.
Managing connections.
Monitoring connection "liveness."
Listening for incoming calls.
Maintaining a table of remote objects that reside in the address space.
Setting up a connection for an incoming call.
Locating the dispatcher for the target of the remote call and passing the connection to this
dispatcher.
Goals of RMI
A primary goal for the RMI designers was to allow programmers to develop distributed Java programs
with the same syntax and semantics used for non-distributed programs.
Minimize difference between working with local and remote objects
Minimize complexity
Preserve type safety
Distributed garbage collection
Invocation of object methods in another java virtual machines
Distribution transference (java semantics)
Easy to use
1) RMI Registry:
A remote object registry is a bootstrap naming service that is used by RMI servers on the same host to
bind remote objects to names. Clients on local and remote hosts can then look up remote objects and
make remote method invocations. Default port for RMI Registry is: 1099
2) rmic compiler:
The rmic compiler generates stub and skeleton class files (JRMP protocol) and stub and tie class
files (IIOP protocol) for remote objects. These classes files are generated from compiled Java
programming language classes that are remote object implementation classes.
R. Introduction to EJB
EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems to
develop secured, robust and scalable distributed applications. Enterprise Java Beans ('EJB') is a managed,
server-side component architecture for modular construction of enterprise applications. EJB is a server-
side model that encapsulates the business logic of an application. The EJB specification intends to provide
a standard way to implement the back-end 'business' code typically found in enterprise applications.
Features of EJB
The EJB specification details how an application server provides the following responsibilities:
Transaction processing
Integration with the persistence services offered by the Java Persistence API (JPA)
Concurrency control
Event-driven programming using Java Message Service and Java EE Connector Architecture
Asynchronous method invocation
Job scheduling
Naming and directory services (JNDI)
Inter-process Communication using RMI-IIOP and Web services
Benefits of EJB
Types of EJB
Session Bean Session bean stores data of a particular user for a single session. It can be
stateful or stateless. It is less resource intensive as compared to entity beans.
Session bean gets destroyed as soon as user session terminates.
Entity Bean Entity bean represents persistent data storage. User data can be saved to
database via entity beans and later on can be retrieved from the database in
the entity bean.
Message Driven Message driven beans are used in context of JMS (Java Messaging Service).
Bean Message Driven Beans can consumes JMS messages from external entities and
act accordingly.
Both RMI and EJB, provides services to access an object running in another JVM (known as remote
object) from another JVM. The differences between RMI and EJB are given below:
Limitations of EJB
Appendices
---------------------------------------
Appendix - A
[Practice Set]
What is GUI?
1 Graphical User Interface (GUI) offers user interaction via some graphical components.
Nikita Education [NET]
What is AWT?
2 Abstract Window Toolkit (AWT) is a set of application program interfaces (API - collection of classes and
interfaces) used by Java programmers to create graphical user interface ( GUI ).
Nikita Education [NET]
Events: Event is an object that describes a state of change in a source. Event may be generated as a
17 consequence of a person interacting with the GUI elements
Nikita Education [NET]
Event Sources: "Source" is an object that generates an event. listeners must register with the source in
18 order to receive event notification.
Nikita Education [NET]
20
Enlist any five event classes and interfaces. Nikita Education [NET]
ActionEvent ActionListener
21 MouseEvent MouseListener
KeyEvent KeyListener
ItemEvent ItemListener
WindowEvent WindowListener
What is adapter class? Enlist any three. Nikita Education [NET]
22 An adapter class provides an empty implementation of all methods in an event listener interface.
Classes: WindowAdapter, KeyAdapter, MouseAdapter
Event Hirarchy
23
What is the method used to get the data entered by the user in the text field?
32
getText() method of TextField class.
What is the difference between text field and text area?
TextField and TextArea are used to get or display messages from user. The difference is text field displays
33 the message in one line of text only but of any length where as text area is used to display multiple lines of
text.
Nikita Education [NET]
What is the method used to change the characters entered by the user in the text field (used for
34 password)?
setEchoChar(char ch) of TextField class.
How to make the text field non-editable by the user (user cannot enter anything)?
35 setEditable(boolean state) of TextField class. This type of text field is used only to display text to the user.
Nikita Education [NET]
What is the method used to know the label of the button clicked by the user?
36 getActionCommand() method of ActionEvent class.
Nikita Education [NET]
What is HeadlessExceptin?
It is an unchecked exception. This runtime exception is thrown when the code that is dependent on the
39 hardware like keyboard, display or mouse is called in an environment that does not support a keyboard,
display or mouse.
Nikita Education [NET]
44
48
Dialog boxes may be modal or modeless. When a modal dialog box is active, all input is directed to it
until it is closed. This means that you cannot access other parts of your program until you have closed the
50
dialog box. When a modeless dialog box is active, input focus can be directed to another window in your
program. Thus, other parts of your program remain active and accessible.
02 - SWING Nikita Education [NET]
What is Swing?
1
Set of classes and interfaces used to design flexible and attractive GUI.
Heavyweight Lightweight
Java.awt package Javax.swing package
2 Platform dependant Platform independent
OS dependant look & feel Pluggable look & feel
Uses peer objects of OS for each components Entirely written in java
Uses simple architecture Uses MVC architecture
Simple and less portable Portable and flexible
What is JFC?
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries
3 provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface
(GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft
Windows, Linux, and Mac OSX.
Nikita Education [NET]
Swing features: Plugable look & feel, Uses MVC architecture , Lightweight components, Platform
4
Independant, Advance features such as JTable, JTabbedPane, JScrollPane etc.
5 Swing is built on AWT Nikita Education [NET]
MVC Architecture: Model - View - Controller ( model corresponds to the state information, view
6
determines how the component is displayed on the screen, controller determines how the component reacts)
A Swing GUI consists of two key items: components and containers.
7 A component is an independent visual control, such as a push button
A container holds a group of components. Nikita Education [NET]
JRootPane contains:
1. Glass Pane: This enables you to manage mouse events that affect the entire container
8 2. Layered Pane: This allows components to be given a depth value. This value determines which
component overlays another. It contains Content Pane and Menu Bar.
3. Content Pane: This pane holds the visual components such as buttons, labels, textfields
Important constants of Swing frame: static int EXIT_ON_CLOSE, static int DISPOSE_ON_CLOSE,
9 static int DO_NOTHING_ON_CLOSE, static int HIDE_ON_CLOSE
Nikita Education [NET]
What are the type of Buttons in Swing: JButton, JToggleButton, JCheckBox, JRadioButton. All are
subclasses of AbstractButton.
Important methods of AbstractButton:
getSelectedIcon()
17
setDisabledIcon(Icon disabledIcon)
setIcon(Icon defaultIcon)
setPressedIcon(Icon pressedIcon)
setSelectedIcon(Icon selectedIcon)
What is Toggle button?
18 Toggle button provides only two states i.e. on or off. When it is pressed it switches only between to states.
Two important subclasses of JToggleButton are JCheckBox and JRadioButton.
Nikita Education [NET]
Computer Network: A computer network is a group of computer systems and other computing hardware
1 devices that are linked together through communication channels to facilitate communication and resource-
sharing among a wide range of users
IP Address: IP address is short for Internet Protocol (IP) address. An IP address is an identifier for a
2 computer or device on a TCP/IP network.
Nikita Education [NET]
Subnet Mask: An IP address has two components, the network address and the host address. A subnet
3
mask separates the IP address into the network and host addresses (<network><host>).
IP Classes: The IPv4 address space can be subdivided into 5 classes - Class A (1 - 126), B (128 - 191), C
4 (192 - 223), D (224 - 239) and E (240 - 254).
Nikita Education [NET]
Proxy Server: A server that sits between a client application and a real server. It intercepts all requests to
5
the real server to see if it can fulfill the requests itself. If not, it forwards the request to the real server.
TCP vs. UDP
1. TCP stands for “Transmission Control Protocol” while UDP stands for “User datagram Protocol”.
2. TCP is connection oriented protocol while UDP is connectionless protocol.
3. TCP is more reliable , UDP is not reliable.
4. UDP is more faster for data sending than TCP.
5. UDP makes error checking but no reporting but TCP makes checks for errors and reporting.
6 6. TCP gives guarantee that the order of data at receiving end is same as on sending end while UDP has
no such guarantee.
7. Header size of TCP is 20 bytes while that of UDP is 8 bytes.
8. TCP is heavy weight as it needs three packets to setup a connection while UDP is light weight.
9. TCP has acknowledgement segments but UDP has no acknowledgement.
10. TCP is used for application that require high reliability but less time critical whereas UDP is used
for application that are time sensitive but require less reliability.
Nikita Education [NET]
9 Socket primitives: Socket, Bind, Listen, Accept, Connect, Send, Receive, Close.
Nikita Education [NET]
What is port?
It is a sixteen bit unique number used to uniquely identify processes over a network. It is also called as a
10
numbered socket. A port number is the logical address of each application or process.
Maximum possible port numbers: 216 = 65536 i.e. 0 to 65535
Well known ports: 0 to 1023 i.e. 1024
11 Registered ports: 1024 to 49151 i.e. 48128
Dynamic or private ports: 49152 to 65535 i.e. 16383
Nikita Education [NET]
What is ServerSocket?
12 As the name indicates, the ServerSocket works on server-side and its job is to bind the connection on the
specific port number requested by the client.
What is URL class?
13 An URL represents the host name or address along with the protocol.
Nikita Education [NET]
Enlist different protocols: IP, TCP, UDP, SMTP, POP, Telnet, ARP, RARP, RSTP, FTP, TFTP, HTTP,
17
HTTPS, SNMP, DHCP, BGP, LDAP etc.
Enlist some common well known ports:
20 - FTP Data
21 - FTP Control
80 - HTTP
23 - Telnet
18
25 - SMTP
161 - SNMP
53 - Domain Name System (DNS)
443 - HTTPS
546, 547 - DHCP Client, DHCP Server Nikita Education [NET]
20
What is JDBC?
1 JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers
to connects to the database.
What is JDBC Driver?
JDBC Driver is a software component that enables java application to interact with the database. There are
4 types of JDBC drivers:
2 1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver) Nikita Education [NET]
JDBC Features
23 Get a connection, Connection Pooling, Rowsets, New data type supports, Batch Updating, Result set
enhancement, Scrollable Result set, Updateable Result set, Savepoints.
Simple JDBC program
class SimpleJdbcDemo{
public static void main(String ar[]){
try{
24
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement(); Nikita Education [NET]
What is RMI?
1 The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another JVM.
RPC (Remote Procedure Call) vs. RMI
RMI is object oriented while RPC isn’t
2 RPC is C bases while RMI is Java only
RMI invokes methods while RPC invokes functions
RPC is antiquated while RMI is the future Nikita Education [NET]
Architecture of RMI
Goals of RMI
Minimize difference between working with local and remote objects
Minimize complexity
Preserve type safety
7 Distributed garbage collection
Invocation of object methods in another java virtual machines
Distribution transference (java semantics)
Easy to use
Nikita Education [NET]
The security manager is the most important component in the sandbox; the role of the security manager is
to perform run-time checks on potentially dangerous operations:
File I/O
15 Network access
Creation on new class loaders etc.
The manager reserves the right to verify any such operations.
System.setSecurityManager(new RMISecurityManager());
Security file
16 The java.security is master security file which enforces specified security parameters, properties, and policies
for each java program running on JVM.
Nikita Education [NET]
The java.policy file is a global default policy file shared by all of the Java programs running in the Java
17
Virtual Machine (JVM) on the node.
Specific Permission Policy File
grant {
18 permission java.net.SocketPermission "*:1024-65535", "connect,accept,resolve";
permission java.net.SocketPermission "*:80", "connect";
Nikita Education [NET]
Static Web Page: "Static" means unchanged or constant, static web pages contain the same prebuilt
1
content each time the page is loaded.
Dynamic Web Page: "dynamic" means changing or lively, the content of dynamic Web pages can be
2
generated on-the-fly. PHP, ASP, Servlets and JSP pages are dynamic Web pages.
Web Application: A web application is an application accessible from the web used to generate dynamic
3 responses. A web application is composed of web components like Servlet, JSP, Filter etc. and other
components such as HTML.
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative,
4 hypermedia information systems.
Nikita Education [NET]
HTTP Methods:
GET: The GET method is used to retrieve information from the given server using a given URI. Requests
using GET should only retrieve data and should have no other effect on the data.
HEAD: Same as GET, but it transfers the status line and the header section only.
POST: A POST request is used to send data to the server, for example, customer information, file upload,
5 etc. using HTML forms.
PUT: Replaces all the current representations of the target resource with the uploaded content.
DELETE: Removes all the current representations of the target resource given by URI.
CONNECT: Establishes a tunnel to the server identified by a given URI.
OPTIONS: Describe the communication options for the target resource.
TRACE: Performs a message loop back test along with the path to the target resource.
Nikita Education [NET]
What is cookie?
Cookies are small pieces of information that are sent in response from the web server to the
21
client. Cookies are the simplest technique used for storing client state. Cookies are stored on client's
computer.
Constructors of Cookie class
22 Cookie()
Cookie(String name, String value)
Nikita Education [NET]
25
Which jar file is required for compiling servlet class in apache tomcat?
27
servlet-api.jar
What is deployment descriptor?
28 The deployment descriptor is an xml file, from which Web Container gets the information about the servlet
to be invoked.
web.xml Nikita Education [NET]
<web-app>
<servlet>
<servlet-name> logical name for servlet as it is given below</servlet-name>
<servlet-class>name of servlet class file</servlet-class>
29 </servlet>
<servlet-mapping>
<servlet-name> any logical name for servlet </servlet-name>
<url-pattern>url pattern of request in browsers address bar</url-pattern>
</servlet-mapping>
</web-app>
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another
32
resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL.
What is Session?
33 The session of activity that a user with a unique IP address spends on a Web site during a specified period of
time.
Nikita Education [NET]
Types of Cookie
1. Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
36
2. Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is removed
only if user logout or signout.
sessions vs. cookies:
37 a cookie is data stored on the client
a session's data is stored on the server (only 1 session per client) Nikita Education [NET]
What is difference between Get and Post method? Nikita Education [NET]
Get Post
1) Limited amount of data can be sent because data is Large amount of data can be sent because data is
sent in header. sent in body.
41
2) Not Secured because data is exposed in URL bar. Secured because data is not exposed in URL bar.
3) Can be bookmarked Cannot be bookmarked
4) Idempotent Non-Idempotent
5) It is more efficient and used than Post It is less efficient and used
What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class where as ServletOutputStream is a byte-stream class. The
42 PrintWriter class can be used to write only character-based information whereas ServletOutputStream class
can be used to write primitive values as well as character-based information.
Nikita Education [NET]
What is JSP?
1 Java Server Pages technology (JSP) is used to create dynamic web page. It is an extension to the servlet
technology. A JSP page is internally converted into servlet.
What are the life-cycle methods for a jsp?
public void jspInit()
2
public void _jspService(ServletRequest request,ServletResponse)throws ServletException,IOException
public void jspDestroy() Nikita Education [NET]
How can we forward the request from jsp page to the servlet ?
7
Yes of course! With the help of forward action tag, but we need to give the url-pattern of the servlet.
Can we use the exception implicit object in any jsp page ?
8 No. The exception implicit object can only be used in the error page which defines it with the isErrorPage
attribute of page directive.
What are the different scope values for the <jsp:useBean> tag?
1. page
9 2. request
3. session
4. application Nikita Education [NET]
What is EL in JSP?
The Expression Language(EL) is used in JSP to simplify the accessibility of objects. It provides many
10
objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session
etc.
What is JSTL?
11 JSP Standard Tag Library is library of predefined tags that ease the development of JSP.
Nikita Education [NET]
Importance of JSP
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages
14
itself instead of having a separate CGI files.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to
load an interpreter and the target script each time the page is requested.
Java Server Pages are built on top of the Java Servlets API, so like Servlets; JSP also has access to all the
powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle the business logic, the model supported
by Java servlet template engines.
Nikita Education [NET]
Advantages of JSP
vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in
Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs
that use form data, make database connections, and the like.
vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing etc.
15 vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
Extension to Servlet: JSP technology is the extension to 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.
Easy to maintain: JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the presentation logic.
Fast Development: No need to recompile and redeploy: If JSP page is modified, we don't need to
recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to
change the look and feel of the application.
Less code than Servlet: In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that
reduces the code. Moreover, we can use EL, implicit objects etc.
Nikita Education [NET]
What is EJB?
1 EJB stands for Enterprise Java Bean. It is a server-side component to develop scalable, robust and secured
enterprise applications in java.
What are the types of Enterprise Bean?
There are 3 types of enterprise bean in java.
2 1. Session Bean
2. Message Driven Bean
3. Entity Bean Nikita Education [NET]
What is JMS?
7
Java Message Service is a messaging service to create, send and receive messages asynchronously.
What are the advantages of JMS?
8 o Asynchronous
o Reliable Nikita Education [NET]
What is MDB?
9 Message Driven Bean (MDB) encapsulates business logic. It is invoked by passing message. It is like JMS
receiver.
What is Entity Bean?
10 Entity Bean is a server side component that represents the persistent data. Since EJB 3.x, it is replaced by
JPA.
Nikita Education [NET]
Features of EJB
Transaction processing
Integration with the persistence services offered by the Java Persistence API (JPA)
Concurrency control
Event-driven programming using Java Message Service and Java EE Connector Architecture
11 Asynchronous method invocation
Job scheduling
Naming and directory services (JNDI)
14
15
17
Best of Luck
-----------------------------
Nikita Education [NET]