You are on page 1of 90

SYCS-SEMESTER IV-ADVANCED JAVA

Topic Teaching Number


date of
lectures

Unit Swing:
1
Need for swing components,

Difference between AWTand swing,

Components hierarchy,

Panes,

Swing components: Jlabel, JTextField and


JPasswordField, JTextAres, JButton, JCheckBox,
JRadioButton, JComboBox and JList

JDBC:

Introduction,

JDBC Architecture,

Types of Drivers,

Statement,

ResultSet,

Read Only ResultSet, Updatable ResultSet,

Forward Only ResultSet, Scrollable ResultSet,


PreparedStatement, Connection Modes,

SavePoint,

Batch Updations, CallableStatement,

BLOB & CLOB

Unit Servlets: Introduction,


2
Web application Architecture, Http Protocol & Http
Methods, Web Server & Web Container, Servlet
Interface, GenericServlet, HttpServlet, Servlet Life
Cycle, ServletConfig,

Jyoti Samel Page 1


SYCS-SEMESTER IV-ADVANCED JAVA

ServletContext,

Servlet Communication, Session Tracking


Mechanisms

JSP: Introduction,

JSP LifeCycle,

JSP Implicit Objects & Scopes, JSP Directives,

JSP Scripting Elements,

JSP Actions: Standard actions and customized actions,

Unit Java Beans: Introduction, JavaBeans Properties,


3 Examples

Struts 2: Basic MVC Architecture,

Struts 2 framework features, Struts 2 MVC pattern,

Request life cycle,

Examples,

Configuration Files,

Actions,

Interceptors,

Results & Result Types,

Value Stack/OGNL

JSON: Overview,

Syntax,

DataTypes,

Objects,

Schema,

Comparison with XML,

Jyoti Samel Page 2


SYCS-SEMESTER IV-ADVANCED JAVA

JSON with Java

What does Java Swing mean?

Java Swing is a lightweight Java graphical user interface (GUI) widget toolkit that includes a rich set of widgets.
It is part of the Java Foundation Classes (JFC) and includes several packages for developing rich desktop
applications in Java. Swing includes built-in controls such as trees, image buttons, tabbed panes, sliders,
toolbars, color choosers, tables, and text areas to display HTTP or rich text format (RTF). Swing components
are written entirely in Java and thus are platform-independent.

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

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

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

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

N
Java AWT Java Swing
o.

1) AWT components are platform-dependent. Java swing components are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

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

Swing provides more powerful components such as


4) AWT provides less components than Swing. tables, lists, scrollpanes, colorchooser, tabbedpane
etc.

AWT doesn't follows MVC(Model View


Controller) where model represents data, view
5) Swing follows MVC.
represents presentation and controller acts as
an interface between model and view.

Jyoti Samel Page 3


SYCS-SEMESTER IV-ADVANCED JAVA

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


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

Method Description

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

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager


sets the layout manager for the component.
m)

sets the visibility of the component. It is by default


public void setVisible(boolean b)
false.

Simple Java Swing Example


import javax.swing.*;  
public class FirstSwingExample {  
public static void main(String[] args) {  
JFrame  f=new JFrame();//creating instance of JFrame  
          
JButton b=new JButton("click");//creating instance of JButton  
b.setBounds(130,100,100, 40);//x axis, y axis, width, height  
          
f.add(b);//adding button in JFrame  
          
f.setSize(400,500);//400 width and 500 height  
f.setLayout(null);//using no layout managers  
f.setVisible(true);//making the frame visible  

Jyoti Samel Page 4


SYCS-SEMESTER IV-ADVANCED JAVA

}  
}  

Swing Features

● Light Weight − Swing components are independent of native Operating System's API as Swing API
controls are rendered mostly using pure JAVA code instead of underlying operating system calls.

● Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane, slider,
colorpicker, and table controls.

● Highly Customizable − Swing controls can be customized in a very easy way as visual appearance is
independent of internal representation.

● Pluggable look-and-feel − SWING based GUI Application look and feel can be changed at run-time,
based on available values.

Java Swing Components and Containers


A component is an independent visual control. Swing Framework contains a large set of components which
provide rich functionalities and allow high level of customization. They all are derived from JComponent class.
All these components are lightweight components. This class provides some common functionality like
pluggable look and feel, support for accessibility, drag and drop, layout, etc.

A container holds a group of components. It provides a space where a component can be managed and
displayed. Containers are of two types:

1. Top level Containers


o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel

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

JLabel class declaration

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

1. public class JLabel extends JComponent implements SwingConstants, Accessible  

Jyoti Samel Page 5


SYCS-SEMESTER IV-ADVANCED JAVA
Commonly used Constructors:

Constructor Description

Creates a JLabel instance with no image and with an empty string


JLabel()
for the title.

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

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

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

Commonly used Methods:


Methods Description

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

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

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

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

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

Java JLabel Example

import javax.swing.*;  
class LabelExample  
{  
public static void main(String args[])  
    {  
    JFrame f= new JFrame("Label Example");  
    JLabel l1,l2;  
    l1=new JLabel("First Label.");  
    l1.setBounds(50,50, 100,30);  
    l2=new JLabel("Second Label.");  
    l2.setBounds(50,100, 100,30);  
    f.add(l1); f.add(l2);  
    f.setSize(300,300);  
    f.setLayout(null);  
    f.setVisible(true);  
    }  
}  

Jyoti Samel Page 6


SYCS-SEMESTER IV-ADVANCED JAVA

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

JTextField class declaration

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

1. public class JTextField extends JTextComponent implements SwingConstants  

Commonly used Constructors:


Constructor Description

JTextField() Creates a new TextField

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

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

Creates a new empty TextField with the specified number of


JTextField(int columns)
columns.

Commonly used Methods:


Methods Description

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

It returns the currently set Action for this ActionEvent source, or


Action getAction()
null if no Action is set.

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

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


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

Java JTextField Example

import javax.swing.*;  
class TextFieldExample  
{  
public static void main(String args[])  
    {  
    JFrame f= new JFrame("TextField Example");  
    JTextField t1,t2;  
    t1=new JTextField("Welcome to Javatpoint.");  
    t1.setBounds(50,100, 200,30);  
    t2=new JTextField("AWT Tutorial");  
    t2.setBounds(50,150, 200,30);

Jyoti Samel Page 7


SYCS-SEMESTER IV-ADVANCED JAVA

    f.add(t1); f.add(t2);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);  
    }  
    }  

Java 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

JTextArea class declaration

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

1. public class JTextArea extends JTextComponent  

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.

Creates a text area with the specified number of rows and columns that
JTextArea(int row, int column)
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.

Commonly used Methods:


Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

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

void insert(String s, int


It is used to insert the specified text on the specified position.
position)

It is used to append the given text to the end of the


void append(String s)
document.

Java JTextArea Example

import javax.swing.*;  

Jyoti Samel Page 8


SYCS-SEMESTER IV-ADVANCED JAVA

public class TextAreaExample  
{  
     TextAreaExample(){  
        JFrame f= new JFrame();  
        JTextArea area=new JTextArea("Welcome to javatpoint");  
        area.setBounds(10,30, 200,200);  
        f.add(area);  
        f.setSize(300,300);  
        f.setLayout(null);  
        f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
   new TextAreaExample();  
    }} 

Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It allows the editing
of a single line of text. It inherits JTextField class.

JPasswordField class declaration

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

1. public class JPasswordField extends JTextField  

Commonly used Constructors:


Constructor Description

Constructs a new JPasswordField, with a default document, null starting


JPasswordField()
text string, and 0 column width.

Constructs a new empty JPasswordField with the specified number of


JPasswordField(int columns)
columns.

JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text.

JPasswordField(String text, int Construct a new JPasswordField initialized with the specified text and
columns) columns.

Java JPasswordField Example

import javax.swing.*;    
public class PasswordFieldExample {  
    public static void main(String[] args) {    
    JFrame f=new JFrame("Password Field Example");    
     JPasswordField value = new JPasswordField();   
     JLabel l1=new JLabel("Password:");    
        l1.setBounds(20,100, 80,30);    
Jyoti Samel Page 9
SYCS-SEMESTER IV-ADVANCED JAVA

         value.setBounds(100,100,100,30);    
            f.add(value);  f.add(l1);  
            f.setSize(300,300);    
            f.setLayout(null);    
            f.setVisible(true);     
}  
}  

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

JButton class declaration

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

1. public class JButton extends AbstractButton implements Accessible  

Commonly used Constructors:


Constructor Description

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

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

It creates a button with the specified icon


JButton(Icon i)
object.

Commonly used Methods of AbstractButton class:


Methods Description

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

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

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

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

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

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

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

Java JButton Example

import javax.swing.*;    

Jyoti Samel Page 10


SYCS-SEMESTER IV-ADVANCED JAVA

public class ButtonExample {  
public static void main(String[] args) {  
    JFrame f=new JFrame("Button Example");  
    JButton b=new JButton("Click Here");  
    b.setBounds(50,100,95,30);  
    f.add(b);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  }

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

JCheckBox class declaration

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

1. public class JCheckBox extends JToggleButton implements Accessible  

Commonly used Constructors:


Constructor Description

JCheckBox() Creates an initially unselected check box button with no text, no icon.

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

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

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

Java JCheckBox Example

import javax.swing.*;  
public class CheckBoxExample  
{  
     CheckBoxExample(){  
        JFrame f= new JFrame("CheckBox Example");  
        JCheckBox checkBox1 = new JCheckBox("C++");  
        checkBox1.setBounds(100,100, 50,50);  
        JCheckBox checkBox2 = new JCheckBox("Java", true);  
        checkBox2.setBounds(100,150, 50,50);  
        f.add(checkBox1);  
        f.add(checkBox2);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);  

Jyoti Samel Page 11


SYCS-SEMESTER IV-ADVANCED JAVA

     }  
public static void main(String args[])  
    {  
    new CheckBoxExample();  
    }}  

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

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

JRadioButton class declaration

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

1. public class JRadioButton extends JToggleButton implements Accessible  

Commonly used Constructors:


Constructor Description

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

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

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

Commonly used Methods:


Methods Description

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

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

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

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

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

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

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

Java JRadioButton Example


import javax.swing.*;    
public class RadioButtonExample {    
JFrame f;    
RadioButtonExample(){    
f=new JFrame();     
Jyoti Samel Page 12
SYCS-SEMESTER IV-ADVANCED JAVA
JRadioButton r1=new JRadioButton("A) Male");    
JRadioButton r2=new JRadioButton("B) Female");    
r1.setBounds(75,50,100,30);    
r2.setBounds(75,100,100,30);    
ButtonGroup bg=new ButtonGroup();    
bg.add(r1);bg.add(r2);    
f.add(r1);f.add(r2);      
f.setSize(300,300);    
f.setLayout(null);    
f.setVisible(true);    
}    
public static void main(String[] args) {    
    new RadioButtonExample();    
}    
}    

Java JComboBox
JComboBox components combines a button or editable field and a drop –down list. User can select a value
from the drop down list.

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

JComboBox class declaration

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

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListe
ner, Accessible  

Commonly used Constructors:


Constructor Description

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

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

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


items) Vector.

Commonly used Methods:


Methods Description

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

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

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

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

Jyoti Samel Page 13


SYCS-SEMESTER IV-ADVANCED JAVA

editable.

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

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

Java JComboBox Example

import javax.swing.*;    
public class ComboBoxExample {    
JFrame f;    
ComboBoxExample(){    
    f=new JFrame("ComboBox Example");    
    String country[]={"India","Aus","U.S.A","England","Newzealand"};        
    JComboBox cb=new JComboBox(country);    
    cb.setBounds(50, 50,90,20);  
cb.addItem(“Germany”);  
    f.add(cb);        
cn.removeItem(“U.S.A”);
    f.setLayout(null);    
    f.setSize(400,500);    
    f.setVisible(true);         
}    
public static void main(String[] args) {    
    new ComboBoxExample();         

}    
}   

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

JList class declaration

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

1. public class JList extends JComponent implements Scrollable, Accessible  

Commonly used Constructors:


Constructor Description

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

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

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

Jyoti Samel Page 14


SYCS-SEMESTER IV-ADVANCED JAVA
Commonly used Methods:
Methods Description

Void addListSelectionListener It is used to add a listener to the list, to be notified each time a
(ListSelectionListener listener) change to the selection occurs.

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

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

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

Java JList Example

import javax.swing.*;  
public class ListExample  
{       ListExample(){  
        JFrame f= new JFrame();  
        DefaultListModel<String> l1 = new DefaultListModel<>();  
          l1.addElement("Item1");  
          l1.addElement("Item2");  
          l1.addElement("Item3");  
          l1.addElement("Item4");  
          JList<String> list = new JList<>(l1);  
          list.setBounds(100,100, 75,75);  
          f.add(list);  
          f.setSize(400,400);  
          f.setLayout(null);  
          f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
   new ListExample();  
}} 

JTabel

JTable that contains rows and columns of data.

Constructor:

JTable(object data[] [] , object c[])

Example :

Jyoti Samel Page 15


SYCS-SEMESTER IV-ADVANCED JAVA
import javax.swing.*;
class JTableExample
{
public static void main(String args[])
{
JFrame f = new JFrame("JTable Example");
JPanel p=new JPanel();
final Object[][] info={ {"1","jeet"} ,{"2","hari"},
{"1","jeet"} ,{"2","hari"},
{"1","jeet"} ,{"2","hari"},
{"1","jeet"} ,{"2","hari"},
{"1","jeet"} ,{"2","hari"},
{"1","jeet"} ,{"2","hari"},
};
final String[] cHead={"Roll no", "Name"};
JTable jT=new JTable(info, cHead);
jT.setBounds(50,50,200,200);
JScrollPane sp=new JScrollPane(jT);

f.add(sp);
f.setSize(150,150);
f.setVisible(true);
}

final Object[][] info={ {"1","jeet"} , {"2","hari"}};


final String[] cHead={"Roll no", "Name"}
JTable jT=new JTable(info, cHead);

JTabbedPane

Are the space savers used to display child component. The child component can be displayed one at a time.

JTabbedPane()

void addTab(String s, component c)

import javax.swing.*;
class JTabbedPaneExample
{
public static void main(String args[])
{
JFrame f = new JFrame("JTabbed Example");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTabbedPane jTab=new JTabbedPane();
JLabel jL1=new JLabel("This is tab one");
JLabel jL2=new JLabel("This is tab two");
JTextField jT1=new JTextField("welcome");
Jyoti Samel Page 16
SYCS-SEMESTER IV-ADVANCED JAVA
p1.add(jL1); p1.add(jT1);
final Object[][] info={ {"1","jeet"} , {"2","hari"}, {"3","kavi"}};
final String[] cHead={"Roll no", "Name"};
JTable jT=new JTable(info, cHead);
p2.add(jT);
p2.add(jL2);
jTab.addTab("Tab1", p1);
jTab.addTab("Tab2", p2);
f.add(jTab);
f.setSize(500,400);
f.setVisible(true);

}
}
_________________________________________________________
import javax.swing.*;
class JTabbedPaneExample
{ public static void main(String args[])
{ JFrame f = new JFrame("JTabbed Example");
JTabbedPane jTab=new JTabbedPane(JTabbedPane.LEFT,JTabbedPane.WRAP_TAB_LAYOUT);
//JTabbedPane jTab=new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT);
//JTabbedPane jTab=new JTabbedPane();
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();
JPanel p5=new JPanel();
JPanel p6=new JPanel();
JPanel p7=new JPanel();
JPanel p8=new JPanel();
JPanel p9=new JPanel();
JPanel p10=new JPanel();
JLabel jL1=new JLabel("Enter your full name : ");
JTextField jt1=new JTextField(20);

JLabel jL2=new JLabel("Enter your Roll No : ");


JTextField jt2=new JTextField(20);

p1.add(jL1); p1.add(jt1); p1.add(jL2); p1.add(jt2);

jTab.addTab("Tab1", p1);jTab.addTab("Tab2",p2);jTab.addTab("Tab3",p3);
jTab.addTab("Tab4",p4);jTab.addTab("Tab5",p5);
jTab.addTab("Tab6",p6); jTab.addTab("Tab7",p7); jTab.addTab("Tab8",p8);
jTab.addTab("Tab9",p9); jTab.addTab("Tab10",p10);
f.add(jTab);
f.setSize(500,400);
f.setVisible(true);

}
}

Jyoti Samel Page 17


SYCS-SEMESTER IV-ADVANCED JAVA

JMenuItem:

It is a menu. A menu item is essentially a button that represent list.

JMenuBar()

JMenu(String label)

JMenu(String label , Boolean status)

JMenuItem(String s)

The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.

The object of JMenu class is a pull down menu component which is displayed from the
menu bar. It inherits the JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.

import javax.swing.*;

class MenuExample

JMenu menu, submenu;

JMenuItem i1, i2, i3, i4, i5;

MenuExample(){

JFrame f= new JFrame("Menu and MenuItem Example");

JMenuBar mb=new JMenuBar();

menu=new JMenu("File");

submenu=new JMenu("Edit");

i1=new JMenuItem("Item 1");

i2=new JMenuItem("Item 2");

i3=new JMenuItem("Item 3");

i4=new JMenuItem("Item 4");

i5=new JMenuItem("Item 5");

menu.add(i1); menu.add(i2); menu.add(i3);

Jyoti Samel Page 18


SYCS-SEMESTER IV-ADVANCED JAVA
submenu.add(i4); submenu.add(i5);

menu.add(submenu);

mb.add(menu);

f.setJMenuBar(mb);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[])

new MenuExample();

}}

___________________________________________________________

import javax.swing.*;

class MenuExample

JMenu filemenu, editmenu;

JMenuItem new1, open, save, cut, copy ,paste;

MenuExample(){

JFrame f= new JFrame("Menu and MenuItem Example");

JMenuBar mb=new JMenuBar();

filemenu=new JMenu("File");

editmenu=new JMenu("Edit");

new1=new JMenuItem("Open New Doc");

open=new JMenuItem("Open existing file");

save=new JMenuItem("Save the file");

cut=new JMenuItem("cut option is selected");

copy=new JMenuItem("copy option is selected");


Jyoti Samel Page 19
SYCS-SEMESTER IV-ADVANCED JAVA
paste=new JMenuItem("Paste option is selected");

filemenu.add(new1); filemenu.add(open); filemenu.add(save);

editmenu.add(cut); editmenu.add(copy); editmenu.add(paste);

mb.add(filemenu);

mb.add(editmenu);

f.setJMenuBar(mb);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String args[])

new MenuExample();

}}

________________________________________________________________

Jyoti Samel Page 20


SYCS-SEMESTER IV-ADVANCED JAVA

Chapter 2

JDBC

Introduction :
JDBC is a Java standard that provides the interface for connecting from Java to relational databases. The JDBC
standard is defined by Sun Microsystems and implemented through the standard java.sql interfaces. This
allows individual providers to implement and extend the standard with their own JDBC drivers. JDBC stands
for Java Database Connectivity, which is a standard Java API for database-independent connectivity between
the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the
tasks commonly associated with database usage:
● Making a connection to a database
● Creating SQL or MySQL statements
● Executing that SQL or MySQL queries in the database
● Viewing & Modifying the resulting records

JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

Design of JDBC:

Just as Java was designed to provide platform independence from hardware/software platforms, so too JDBC
has been designed to provide some degree of database independence for developers. JDBC is designed to
provide a database-neutral API for accessing relational databases from different vendors. Just as a Java
application does not need to be aware of the operating system platform on which it is running, so too JDBC
has been designed so that the database application can use the same methods to access data regardless of the
underlying database product.
● JDBC was developed to work with the most common type of database: the relational database. This is
not to say that JDBC cannot be used with another type of database. In fact, there are JDBC drivers that
allow the API to be used to connect to both high-end, mainframe databases, which are not relational,
and to access flat files and spreadsheets as databases (which are definitely not relational). But the
reality is that JDBC is most commonly used with relational databases.
● The technical definition of a relational database is a database that stores data as a collection of related
entities. These entities are composed of attributes that describe the entity, and each entity has a
collection of rows. Another way to think about a relational database is that it stores information on
real-world objects (the entities). The information about the objects is contained in the attributes for
the object.
● Since real world objects have some type of relation to each other, we must have a facility for
expressing relations between the objects in the database. The relationships between the database
objects is described using a query language, the most popular of which is the Structured Query
Language (SQL).

● JavaSoft's JDBC consists of two layers: the JDBC API and the JDBC Driver Manager API.

● The JDBC API is the top layer and is the programming interface in Java to structured query language
(SQL) which is the standard for accessing relational databases.

Jyoti Samel Page 21


SYCS-SEMESTER IV-ADVANCED JAVA
● The JDBC API communicates with the JDBC Driver Manager API, sending it various SQL statements.
The manager communicates (transparent to the programmer) with the various third party drivers
(provided by Database vendors like Oracle) that actually connect to the database and return the
information from the query.

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.

● Following is the architectural diagram, which shows the location of the driver manager with respect to
the JDBC drivers and the Java application:

● The JDBC 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.

Common JDBC Components:


The JDBC API provides the following interfaces and classes:
● DriverManager: This class manages a list of database drivers. Matches connection requests from the
java application with the proper database driver using communication sub protocol. The first driver that
recognizes a certain sub protocol under JDBC will be used to establish a database Connection.
● Driver: This interface handles the communications with the database server. You will interact directly
with Driver objects very rarely. Instead, you use DriverManager objects, which manage objects of this
type. It also abstracts the details associated with working with Driver objects
● Connection : This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection object
only.
● Statement : You use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
● ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
● SQLException: This class handles any errors that occur in a database application. JDBC drivers
implement the defined interfaces in the JDBC API for interacting with your database server.

Jyoti Samel Page 22


SYCS-SEMESTER IV-ADVANCED JAVA
For example, using JDBC drivers enable you to open database connections and to interact with it by
sending SQL or database commands then receiving results with Java.
● The Java.sql package that ships with JDK contains various classes with their behaviors defined and
their actual implementations are done in third-party drivers. Third party vendors implement the
java.sql.Driver interface in their database driver.

JDBC Drivers Types:


JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in
which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4,
which is explained below:

Type 1: JDBC-ODBC Bridge Driver:


● In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using
ODBC requires configuring on your system a Data Source Name (DSN) that represents the target
database.
● When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.

The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.

Advantages:
• Easy to use.
• Can be easily connected to any database.

Disadvantages:
• Performance degraded because JDBC
method call is converted into the ODBC
function calls.
• The ODBC driver needs to be installed on
the client machine.

Type 2: JDBC-Native API:


● In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the
database. These drivers typically provided by the database vendors and used in the same manner as
the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.
● If we change the Database we have to change the native API as it is specific to a database and they are
mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it
eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Advantage:

• Performance upgraded than JDBC-ODBC bridge


driver.
Disadvantage:
• The Native driver needs to be installed on the each
client machine.

Jyoti Samel Page 23


SYCS-SEMESTER IV-ADVANCED JAVA
• The Vendor client library needs to be installed on client machine.

Jyoti Samel Page 24


SYCS-SEMESTER IV-ADVANCED JAVA

Type 3: JDBC-Net pure Java:

In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network
sockets to communicate with an middleware application server. The socket information is then translated by
the middleware application server into the call format required by the DBMS, and forwarded to the database
server.
● This kind of driver is extremely flexible, since it requires no code installed on the client and a single
driver can actually provide access to multiple databases.
● You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client
application. As a result, you need some knowledge of the application server's configuration in order to
effectively use this driver type.
● Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
Advantage:
• No client side library is required because of
application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the
middle tier.
• Maintenance of Network Protocol driver becomes
costly because it requires database- specific coding to be done in the middle tier.

Type 4: 100% pure Java (Thin Driver):

In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket
connection. This is the highest performance driver available for the database and is usually provided by the
vendor itself.
● This kind of driver is extremely
flexible, you don't need to install
special software on the client or
server. Further, these drivers can be
downloaded dynamically.
● MySQL's Connector/J driver is a Type
4 driver. Because of the proprietary
nature of their network protocols,
database vendors usually supply
type 4 drivers.
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantage:
• Drivers depends on the Database.

Jyoti Samel Page 25


SYCS-SEMESTER IV-ADVANCED JAVA

Step by step JDBC Program:

Steps to develop JDBC Program :

To implement the JDBC code in Java program, typically we have 7 different steps, are listed below.

● Import java.sql package


● Load a JDBC Driver class
● Establish a Connection
● Create a Statement
● Execute Sql queries
● Process the ResultSet
● Close Connection

To write a simple JDBC program, we should follow these 7 different steps. Lets understand in detail for each
step.

JDBC Program Step 1 :

Import java.sql package:

The JDBC API is a set of classes and interface, to work with JDBC we must import java.sql package.

import java.sql.*;

JDBC Program Step 2:

Load a JDBC Driver : To load a class at runtime into JVM, we need to call a static method called forName() of
java.lang.Class. By calling the forName() method we can load the JDBC Driver class into the JVM.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver);

JDBC Program Step 3 :

Establish a Connection : By using the DriverManager class, we can establish the connection to the database.
By calling the getConnection(String url, String user,String password) static factory method in DriverManager
class, we can obtain a Connection object. To get the connection object we need to proved the connection url
as a first parameter and database username and password as second and third parameters. Like below.

Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/onlinetutorialspoint","root","123456");

JDBC Program Step 4 :

Create a Statement : In order to send the SQL commands to database from our java program, we need
Statement object. We can get the Statement object by calling the createStatement() method on connection.

Statement stmt = con.createStatement();

 JDBC Program Step 5 :

Jyoti Samel Page 26


SYCS-SEMESTER IV-ADVANCED JAVA
Execute Sql queries : Inorder to execute the SQL commands on database, Statement interface provides
provides three different methods:

● executeUpdate() insert,update, delete ,alter


● executeQuery() select operations
● execute() -select, update, delete,drop,insert, calling procedure , …etc

When we want to run the non-select operations then we  can choose executeUpdate()

int count = stmt.executeUpdate("non-select command");


When we want to execute select operations then we  can choose executeQuery()

ResultSet rs = stmt.executeQuery("select command");


When we want to run both select and non-select operations, then we can use execute()

boolean isTrue = stmt.executeQuery("select / non-select command");

JDBC Program Step 6:

Process the ResultSet :  For the select operations, we use executeQuery() method. The executed query
returns the data in the form of ResultSet object. To process the data we need to go through the ResultSet.

ResultSet rs = stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1));
}

JDBC Program Step 7 :

Close Connection : Last but not least, finally we need to close the connection object. It is very important step
to close the connection. Else we may get JDBCConnectionException exception.

con.close();

 Complete JDBC Program Example :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Jdbc_Select_Example {

public static void main(String[] args) throws Exception {


// Step - I
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Step - II
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/jdbc", "root", "123456");
// Step -III

Jyoti Samel Page 27


SYCS-SEMESTER IV-ADVANCED JAVA
Statement stmt = con.createStatement();
// Step - IV
ResultSet rs = stmt.executeQuery("select * from student");
// Step - V
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " "
+ rs.getString(3));
}
// Step - VI
rs.close();
stmt.close();
con.close();
}

JDBC - Statements, PreparedStatement and CallableStatement

Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement,
and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL
commands and receive data from your database.

They also define methods that help bridge data type differences between Java and SQL data types used in a
database.

The following table provides a summary of each interface's purpose to decide on the interface to use.

Interfaces Recommended Use


Use this for general-purpose access to your database. Useful when you are
Statement using static SQL statements at runtime. The Statement interface cannot
accept parameters.
Use this when you plan to use the SQL statements many times. The
PreparedStatement
PreparedStatement interface accepts input parameters at runtime.
Use this when you want to access the database stored procedures. The
CallableStatement
CallableStatement interface can also accept runtime input parameters.

The Statement Objects

Creating Statement Object


Before you can use a Statement object to execute a SQL statement, you need to create one using the
Connection object's createStatement( ) method, as in the following example −

Statement stmt;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}

Jyoti Samel Page 28


SYCS-SEMESTER IV-ADVANCED JAVA
finally {
...
}
Once you've created a Statement object, you can then use it to execute an SQL statement with one of its three
execute methods.

● boolean execute (String SQL): Returns a boolean value of true if a ResultSet object can be retrieved;
otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use
truly dynamic SQL.

● int executeUpdate (String SQL): Returns the number of rows affected by the execution of the SQL
statement. Use this method to execute SQL statements for which you expect to get a number of rows
affected - for example, an INSERT, UPDATE, or DELETE statement.

● ResultSet executeQuery (String SQL): Returns a ResultSet object. Use this method when you expect to
get a result set, as you would with a SELECT statement.

Closing Statement Object

Just as you close a Connection object to save database resources, for the same reason you should also close
the Statement object.

A simple call to the close() method will do the job. If you close the Connection object first, it will close the
Statement object as well. However, you should always explicitly close the Statement object to ensure proper
cleanup.

Statement stmt = null;


try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
stmt.close();
}

The PreparedStatement Objects

The PreparedStatement interface extends the Statement interface, which gives you added functionality with a
couple of advantages over a generic Statement object.

This statement gives you the flexibility of supplying arguments dynamically.

Creating PreparedStatement Object

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
Jyoti Samel Page 29
SYCS-SEMESTER IV-ADVANCED JAVA
catch (SQLException e) {
...
}
finally {
...
}

All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must
supply values for every parameter before executing the SQL statement.

The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value
you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException.

Each parameter marker is referred by its ordinal position. The first marker represents position 1, the next
position 2, and so forth. This method differs from that of Java array indices, which starts at 0.

All of the Statement object's methods for interacting with the database (a) execute(), (b) executeQuery(), and
(c) executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use
SQL statements that can input the parameters.

Closing PreparedStatement Object

Just as you close a Statement object, for the same reason you should also close the PreparedStatement object.

A simple call to the close() method will do the job. If you close the Connection object first, it will close the
PreparedStatement object as well. However, you should always explicitly close the PreparedStatement object
to ensure proper cleanup.

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Jdbc_PreparedStatement_Example {

public static void main(String[] args) throws Exception {

Jyoti Samel Page 30


SYCS-SEMESTER IV-ADVANCED JAVA
Connection connection = null;
PreparedStatement pstatement = null;
Scanner scanner = null;

try {

scanner = new Scanner(System.in);


int n = 0;
System.out.println("Enter no. of Students to insert");
n = scanner.nextInt();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlinetutorialspoint", "root",
"123456");
if (connection != null)
pstatement = connection.prepareStatement("insert into student values(?,?,?,?)");
if (pstatement != null) {
for (int i = 1; i <= n; i++) {
System.out.println("Enter " + i + " Student Details");
System.out.println("Enter Student No : ");
int studentNo = scanner.nextInt();
System.out.println("Enter Student Name : ");
String studentName = scanner.next();
System.out.println("Enter Student Address : ");
String studentAddress = scanner.next();
System.out.println("Enter Student Age : ");
int studentAge = scanner.nextInt();
pstatement.setInt(1, studentNo);
pstatement.setString(2, studentName);
pstatement.setString(3, studentAddress);
pstatement.setInt(4, studentAge);
int result = pstatement.executeUpdate();
if (result == 0) {
System.out.println("Student details: are not inserted");
} else {
System.out.println(result + " records(s) are inserted");
}
}
}
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (pstatement != null) {
pstatement.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
Jyoti Samel Page 31
SYCS-SEMESTER IV-ADVANCED JAVA
try {
if (connection != null) {
connection.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}

The CallableStatement Objects

Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object, which would be used to execute a call to a database stored procedure.

Creating CallableStatement Object

Suppose, you need to execute the following Oracle stored procedure −

CREATE OR REPLACE PROCEDURE getEmpName


(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;

NOTE: Above stored procedure has been written for Oracle, but we are working with MySQL database so, let
us write same stored procedure for MySQL as follows to create it in EMP database −

DELIMITER $$

DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$


CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$

DELIMITER ;

Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN
parameter. The CallableStatement object can use all the three.

Here are the definitions of each −

Jyoti Samel Page 32


SYCS-SEMESTER IV-ADVANCED JAVA

Parameter Description
A parameter whose value is unknown when the SQL statement is created.
IN
You bind values to IN parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns. You
OUT
retrieve values from theOUT parameters with the getXXX() methods.
A parameter that provides both input and output values. You bind variables
INOUT
with the setXXX() methods and retrieve values with the getXXX() methods.

The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a
CallableStatement object based on the preceding stored procedure −

CallableStatement cstmt = null;


try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}

The String variable SQL, represents the stored procedure, with parameter placeholders.

Using the CallableStatement objects is much like using the PreparedStatement objects. You must bind values
to all the parameters before executing the statement, or you will receive an SQLException.

If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement
object; use the setXXX() method that corresponds to the Java data type you are binding.

When you use OUT and INOUT parameters you must employ an additional CallableStatement method,
registerOutParameter(). The registerOutParameter() method binds the JDBC data type, to the data type that
the stored procedure is expected to return.

Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate
getXXX() method. This method casts the retrieved value of SQL type to a Java data type.

Closing CallableStatement Object

Just as you close other Statement object, for the same reason you should also close the CallableStatement
object.

A simple call to the close() method will do the job. If you close the Connection object first, it will close the
CallableStatement object as well. However, you should always explicitly close the CallableStatement object to
ensure proper cleanup.

CallableStatement cstmt = null;


try {
String SQL = "{call getEmpName (?, ?)}";

Jyoti Samel Page 33


SYCS-SEMESTER IV-ADVANCED JAVA
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();
}

JDBC - Result Sets


The SQL statements that read data from a database query, return the data in a result set. The SELECT
statement is the standard way to select rows from a database and view them in a result set. The
java.sql.ResultSet interface represents the result set of a database query.

A ResultSet object maintains a cursor that points to the current row in the result set. The term "result set"
refers to the row and column data contained in a ResultSet object.

The methods of the ResultSet interface can be broken down into three categories −

● Navigational methods: Used to move the cursor around.

● Get methods: Used to view the data in the columns of the current row being pointed by the cursor.

● Update methods: Used to update the data in the columns of the current row. The updates can then
be updated in the underlying database as well.

The cursor is movable based on the properties of the ResultSet. These properties are designated when the
corresponding Statement that generates the ResultSet is created.

JDBC provides the following connection methods to create statements with desired ResultSet −

● createStatement(int RSType, int RSConcurrency);

● prepareStatement(String SQL, int RSType, int RSConcurrency);

● prepareCall(String sql, int RSType, int RSConcurrency);

The first argument indicates the type of a ResultSet object and the second argument is one of two ResultSet
constants for specifying whether a result set is read-only or updatable.

Type of ResultSet

The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get one
that is TYPE_FORWARD_ONLY.

Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
The cursor can scroll forward and backward, and the result
ResultSet.TYPE_SCROLL_INSENSITIVE set is not sensitive to changes made by others to the
database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and the result
set is sensitive to changes made by others to the database

Jyoti Samel Page 34


SYCS-SEMESTER IV-ADVANCED JAVA

that occur after the result set was created.

JDBC Scrollable ResultSet Example

Whenever we create an object of ResultSet by default, it allows us to retrieve in the forward direction only
and we cannot perform any modifications on ResultSet object. Therefore, by default, the ResultSet object is
non-scrollable and non-updatable ResultSet.

JDBC Scrollable ResultSet :

A scrollable ResultSet is one which allows us to retrieve the data in forward direction as well as backward
direction but no updations are allowed. In order to make the non-scrollable ResultSet as scrollable ResultSet
we must use the following createStatement() method which is present in Connection interface.

public Statement createStatement(int Type, int Mode);


Here type represents the type of scrollability and mode represents either read only or updatable. The
value of Type and the Modes are present in ResultSet interface as constant data members and they are:

● TYPE_FORWARD_ONLY -> 1
● TYPE_SCROLL_INSENSITIVE -> 2
● CONCUR_READ_ONLY -> 3

We can pass the above constants to ResultSet as below:

Statement st=con.createStatement ( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );


ResultSet rs=st.executeQuery (“select * from empleyee”);
Whenever we create a ResultSet object, by default, constant-1 as a Type and constant-3 as mode will be
assigned.

ResultSet interface provides us several methods to make an ResultSet as Scrollable ResultSet below is the list
of methods available in ResultSet interface.

● public boolean next (); It returns true when rs contains next record otherwise false.
● public void beforeFirst ();  It is used for making the ResultSet object to point to just before the first
record (it is by default)
● public boolean isFirst ();  It returns true when rs is pointing to first record otherwise false.
● public void first ();  It is used to point the ResultSet object to first record.
● public boolean isBeforeFirst (); It returns true when rs pointing to before first record otherwise false.
● public boolean previous ();  It returns true when rs contains previous record otherwise false.
● public void afterLast ();  It is used for making the ResultSet object to point to just after the last record.
● public boolean isLast ();  It returns true when rs is pointing to last record otherwise false.
● public void last ();  It is used to point the ResultSet object to last record.
● public boolean isAfterLast ();  It returns true when rs is pointing after last record otherwise false.
● public void absolute (int);  It is used for moving the ResultSet object to a particular record either in
forward direction or in backward direction with respect to first record and last record respectively. If
int value is positive, rs move in forward direction to that with respect to first record. If int value is
negative, rs move in backward direction to that with respect to last record.
● public void relative (int);  It is used for moving rs to that record either in forward direction or in
backward direction with respect to current record.

JDBC Scrollable ResultSet Example :


ScrollResultSet.java
Jyoti Samel Page 35
SYCS-SEMESTER IV-ADVANCED JAVA
package com.onlinetutorialspoint.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ScrollResultSet {

public static void main(String[] args) throws Exception {


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/onlinetutorialspoint", "root",
"123456");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("select * from student");
System.out.println("RECORDS IN THE TABLE...");
while (rs.next()) {
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
}
rs.first();
System.out.println("FIRST RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
rs.absolute(3);
System.out.println("THIRD RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
rs.last();
System.out.println("LAST RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
rs.previous();
rs.relative(-1);
System.out.println("LAST TO FIRST RECORD...");
System.out.println(rs.getInt(1) + " -> " + rs.getString(2));
con.close();
}

JDBC Updatable ResultSet Example

Whenever we create a ResultSet object which never allows us to update the database through ResultSet
object and it allows retrieving the data only in forward direction. Such type of ResultSet is known as non-
updatable and non-scrollable ResultSet.

JDBC Updatable ResultSet:

In this tutorials, I am going to tell you how to make a ResultSet as Updatable. You can find How to make a
ResultSet as Updatable ResultSet and Scrollable here.

There are four steps for updating a record into a table using JDBC API.

Jyoti Samel Page 36


SYCS-SEMESTER IV-ADVANCED JAVA
● Open connection to the database.
● Create a statement object to perform an update query.
● Execute the executeUpdate()  method of statement object to submit a SQL query to database.
● Close connection to the database.

JDBC Statement + Update records example


Here is an example of using the Statement object to update the database records.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class UpdateRecordExample1 {

public static void main(String[] args) {


String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
String username = "root";
String password = "admin";
String sql = "update employee set name='Michael Sam' where emp_id=1";

try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);


Statement stmt = conn.createStatement();) {

stmt.executeUpdate(sql);
System.out.println("Database updated successfully ");
} catch (SQLException e) {
e.printStackTrace();
}
}
}

JDBC-Connection mode:

JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the
database upon its completion.

That may be fine for simple applications, but there are three reasons why you may want to turn off the auto-
commit and manage your own transactions −

● To increase performance.
● To maintain the integrity of business processes.
● To use distributed transactions.

Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction
fails.

To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default,
use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you
turn off auto-commit. You can pass a boolean true to turn it back on again.

Jyoti Samel Page 37


SYCS-SEMESTER IV-ADVANCED JAVA
For example, if you have a Connection object named conn, code the following to turn off auto-commit −

conn.setAutoCommit(false);

Commit & Rollback

Once you are done with your changes and you want to commit the changes then call commit() method on
connection object as follows −

conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the following
code −

conn.rollback( );
The following example illustrates the use of a commit and rollback object −

try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();

String SQL = "INSERT INTO Employees " +


"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
In this case, none of the above INSERT statement would success and everything would be rolled back.

import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver

Jyoti Samel Page 38


SYCS-SEMESTER IV-ADVANCED JAVA
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Set auto commit as false.


conn.setAutoCommit(false);

//STEP 5: Execute a query to create statment with


// required arguments for RS example.
System.out.println("Creating statement...");
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

//STEP 6: INSERT a row into Employees table


System.out.println("Inserting one row....");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);

//STEP 7: INSERT one more row into Employees table


SQL = "INSERT INTO Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);

//STEP 8: Commit data here.


System.out.println("Commiting data here....");
conn.commit();

//STEP 9: Now list all the available records.


String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("List result set for reference....");
printRs(rs);

//STEP 10: Clean-up environment


rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
// If there is an error then rollback the changes.
System.out.println("Rolling back data here....");
try{
if(conn!=null)
conn.rollback();
}catch(SQLException se2){
se2.printStackTrace();
}//end try
Jyoti Samel Page 39
SYCS-SEMESTER IV-ADVANCED JAVA

}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){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main

public static void printRs(ResultSet rs) throws SQLException{


//Ensure we start with first row
rs.beforeFirst();
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
System.out.println();
}//end printRs()
}//end JDBCExample

JDBC Savepoint
Sometimes a transaction can be group of multiple statements and we would like to rollback to a particular
point in the transaction. JDBC Savepoint helps us in creating checkpoints in a transaction and we can rollback
to that particular checkpoint. Any savepoint created for a transaction is automatically released and become
invalid when the transaction is committed, or when the entire transaction is rolled back. Rolling a transaction
back to a savepoint automatically releases and makes invalid any other savepoints that were created after the
savepoint in question.

Jyoti Samel Page 40


SYCS-SEMESTER IV-ADVANCED JAVA
Let’s say we have a Logs table where we want to log the messages that employee information is saved
successfully. But since it’s just for logging, if there are any exceptions while inserting into Logs table, we don’t
want to rollback the entire transaction. Let’s see how we can achieve this with JDBC savepoint.

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class JDBCSavepointExample {


private static final String INSERT_SQL = "INSERT INTO employee "
+ "(EMP_ID, NAME, DOB) VALUES (?,?,?)";

public static void main(String[] args) {


String jdbcUrl = "jdbc:mysql://localhost:3306/BORAJI";
String username = "root";
String password = "admin";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);) {

// Disable auto commit mode


conn.setAutoCommit(false);

try (PreparedStatement insertStmt = conn.prepareStatement(INSERT_SQL);) {

// Insert 1st record


insertStmt.setInt(1, 1);
insertStmt.setString(2, "Michael");
insertStmt.setDate(3, new Date(dateFormat.parse("1995-07-01").getTime()));
insertStmt.executeUpdate();

// Insert 2st record


insertStmt.setInt(1, 2);
insertStmt.setString(2, "Sunil");
insertStmt.setDate(3, new Date(dateFormat.parse("1988-03-22").getTime()));
insertStmt.executeUpdate();

// Insert 3st record


insertStmt.setInt(1, 3);
insertStmt.setString(2, "Mike");
insertStmt.setDate(3, new Date(dateFormat.parse("1980-05-12").getTime()));
insertStmt.executeUpdate();

// Create Savepoint
Savepoint savepoint = conn.setSavepoint();

// Insert 4st record

Jyoti Samel Page 41


SYCS-SEMESTER IV-ADVANCED JAVA
insertStmt.setInt(1, 4);
insertStmt.setString(2, "Manish");
insertStmt.setDate(3, new Date(dateFormat.parse("1992-01-21").getTime()));
insertStmt.executeUpdate();

// Insert 5st record


insertStmt.setInt(1, 5);
insertStmt.setString(2, "Albert");
insertStmt.setDate(3, new Date(dateFormat.parse("1972-07-05").getTime()));
insertStmt.executeUpdate();

// Rollback to savepoint
conn.rollback(savepoint);

// Commit statement
conn.commit();

System.out.println("Transaction is commited successfully.");


} catch (SQLException | ParseException e) {
e.printStackTrace();
if (conn != null) {
try {
// Roll back transaction
System.out.println("Transaction is being rolled back.");
conn.rollback();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output

Transaction is commited successfully.


Data in the EMPLOYEE table after running the above program. 

mysql> select EMP_ID,NAME,DOB from employee;


+--------+---------+------------+
| EMP_ID | NAME | DOB |
+--------+---------+------------+
| 1 | Michael | 1995-07-01 |
| 2 | Sunil | 1988-03-22 |
| 3 | Mike | 1980-05-12 |
+--------+---------+------------+

Jyoti Samel Page 42


SYCS-SEMESTER IV-ADVANCED JAVA

difference between BLOB and CLOB datatypes

Blob and Clob together are known as LOB(Large Object Type). Following are the major differences between
Blob and Clob data types.

JDBC 2.0 introduced two most important datatypes. The purpose of designing these data types to hold large
amount of data.

1) BLOB (Binary Large Object) – Binary data


2) CLOB (Character Large Object) -- text data

Blob Clob
The full form of Blob is Binary Large Object. The full form of Clob is Character Large Object.
This is used to store large binary data. This is used to store large textual data.
This stores values in the form of binary streams. This stores values in the form of character streams.
Using this you can store files like text files, PDF Using this you can stores files like videos, images, gifs,
documents, word documents etc. and audio files.
MySQL supports this with the following datatypes: MySQL supports this with the following datatypes:
● TINYBLOB ● TINYTEXT
● BLOB ● TEXT
● MEDIUMBLOB ● MEDIUMTEXT
● LONGBLOB ● LONGTEXT
In JDBC API it is represented by java.sql.Blob
In JDBC it is represented by java.sql.Clob Interface.
Interface.
The Blob object in JDBC points to the location of The Clob object in JDBC points to the location of CLOB
BLOB instead of holding its binary data. instead of holding its character data.
To store Blob JDBC (PreparedStatement) provides To store Clob JDBC (PreparedStatement) provides
methods like: methods like:
● setBlob() ● setClob()
● setBinaryStream() ● setCharacterStream()
And to retrieve (ResultSet) Blob it provides And to retrieve (ResultSet) Clob it provides methods
methods like: like:
● getBlob() ● getClob()
● getBinaryStream ● getCharacterStream()

Jyoti Samel Page 43


SYCS-SEMESTER IV-ADVANCED JAVA

JDBC - Batch Processing


Batch Processing allows you to group related SQL statements into a batch and submit them with one call to
the database. When you send several SQL statements to the database at once, you reduce the amount of
communication overhead, thereby improving performance.

● JDBC drivers are not required to support this feature. You should use the
DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports
batch update processing. The method returns true if your JDBC driver supports this feature.

● The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add


individual statements to the batch. The executeBatch() is used to start the execution of all the
statements grouped together.

● The executeBatch() returns an array of integers, and each element of the array represents the update
count for the respective update statement.

● Just as you can add statements to a batch for processing, you can remove them with the clearBatch()
method. This method removes all the statements you added with the addBatch() method. However,
you cannot selectively choose which statement to remove.

JDBC transactions
If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is
committed to the database upon its completion. That may be fine for simple applications, but there are three
reasons why you may want to turn off the auto-commit and manage your own transactions −

● To increase performance.

● To maintain the integrity of business processes.

● To use distributed transactions.

Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction
fails. To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by
default, use the Connection object's setAutoCommit() method. If you pass a boolean false to
setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.

For example, if you have a Connection object named conn, code the following to turn off auto-commit
conn.setAutoCommit(false);

Commit & Rollback

Once you are done with your changes and you want to commit the changes then call commit() method on
connection object as follows :

conn.commit( );

Otherwise, to roll back updates to the database made using the Connection named conn, use the following
code −

conn.rollback( );
Jyoti Samel Page 44
SYCS-SEMESTER IV-ADVANCED JAVA

Jyoti Samel Page 45


SYCS-SEMESTER IV-ADVANCED JAVA

Chapter 3
Servlet

Introduction
● How do the pages you're reading in your favorite Web browser show up there? When you log into your
favorite Web site, how does the Web site know that you're you? And how do Web retailers handle
taking your order online? Those capabilities are possible because of code running on servers behind the
scenes that interact with you in a Web session, access stored information throughout that process, and
oftentimes present dynamic information in one or more Web pages.
● The core of those capabilities is provided in the Java language world by servlets. The goal of this Unit
is to introduce you to servlets. It describes what servlets are, how they work, how you can use them to
create Web applications of any degree of sophistication you can imagine, and how you can use servlets
most effectively as a professional programmer.
● In the early days, web servers deliver static contents that are indifferent to users' requests. Java servlets
are server-side programs (running inside a web server) that handle clients' requests and return a
customized or dynamic response for each request. The dynamic response could be based on user's input
(e.g., search, online shopping, online transaction) with data retrieved from databases or other
applications, or time-sensitive data (such as news and stock prices).
● Java servlets typically run on the HTTP protocol. HTTP is an asymmetrical request-response protocol.
The client sends a request message to the server, and the server returns a response message as
illustrated.

In brief, HTTP is a request-response protocol.


The client sends a request message to the
server. The server, in turn, returns a
response message. The messages consists of
two parts: header (information about the
message) and body (contents). Header
provides information about the messages.
The data in header is organized in name-
value pairs.

Advantages of servlets

A servlet can be imagined to be as an applet running on the server side. Some of the other server side
technologies available are Common Gateway Interface (CGI), server side JavaScript and Active Server Pages
(ASP). Advantages of servlets over these server side technologies are as follows:

• Persistent: Servlets remain in memory until explicitly destroyed. This helps in serving several incoming
requests. Servlets establishes connection only once with the database and can handle several requests on the
same database. This reduces the time and resources required to establish connection again and again with the
same database. Whereas, CGI programs are removed from the memory once the request is processed and
each time a new process is initiated whenever new request arrives.

Jyoti Samel Page 46


SYCS-SEMESTER IV-ADVANCED JAVA
• Portable: Since servlets are written in Java, they are portable. That is, servlets are compatible with almost all
operating systems. The programs written on one operating system can be executed on other operating
system.

• Server-independent: Servlets are compatible with any web server available today. Most of the software
vendors today support servlets within their web server products. On the other hand, some of the server side
technologies like server side JavaSricpt and ASP can run on only selected web servers. The CGI is compatible
with the web server that has features to supports it.

• Protocol-independent: Servlets can be created to support any of the protocols like FTP commands, Telnet
sessions, NNTP newsgroups, etc. It also provides extended support for the functionality of HTTP protocol.

• Extensible: Servlets being written in Java, can be extended and polymorphed into the objects that suits the
user requirement.

• Secure: Since servlets are server side programs and can be invoked by web server only, they inherit all the
security measures taken by the web server. They are also safe from the problems related to memory
management as Java does not support the concept of pointers and perform garbage collection automatically.

• Fast: Since servlets are compiled into bytecodes, they can execute more quickly as compared to other
scripting languages. The bytecode compilation feature helps servlets to give much better performance. In
addition, it also provides advantage of strong error and type checking.

HTTP Requests

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

The HTTP client sends the request to the


server in the form of request message which
includes following information:

● The Request-line
● The analysis of source IP address,
proxy and port
● The analysis of destination IP address,
protocol, port and host
● The Requested URI (Uniform Resource
Identifier)
● The Request method and Content
● The User-Agent header
● The Connection control header
● The Cache control header

The HTTP request method indicates the method to be performed on the resource identified by the Requested
URI (Uniform Resource Identifier). This method is case-sensitive and should be used in uppercase.

The HTTP request methods are:

HTTP
Description
Request

Jyoti Samel Page 47


SYCS-SEMESTER IV-ADVANCED JAVA

GET Asks to get the resource at the requested URL.


Asks the server to accept the body info attached. It is like GET request with extra info sent with
POST
the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond

Get vs. Post

There are many differences between the Get and Post request. Let's see these differences:

GET POST
1) In case of Get request, only limited amount of data can In case of post request, large amount of data
be sent because data is sent in header. can be sent because data is sent in body.
2) Get request is not secured because data is exposed in Post request is secured because data is not
URL bar. exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent . It means second request will
Post request is non-idempotent.
be ignored until response of first request is delivered
Post request is less efficient and used less than
5) Get request is more efficient and used more than Post.
get.

Some other features of GET requests are:

● It remains in the browser history


● It can be bookmarked
● It can be cached
● It have length restrictions
● It should never be used when dealing with sensitive data
● It should only be used for retrieving the data

Some other features of POST requests are:

● This requests cannot be bookmarked


● This requests have no restrictions on length of data
● This requests are never cached
● This requests do not retain in the browser history

Servlets and Web Servers.
When user request for dynamic contents from web server, even though web server has access to database it
cannot produce web pages.
Here Servlets comes into middle and generate dynamic web pages upon user requests.

Servlet and Clients.


It’s not necessary that application from client side should written in java to get Servlets response.
Hence application written in any programming language can consumes Servlets outputs.

Servlet Container

Jyoti Samel Page 48


SYCS-SEMESTER IV-ADVANCED JAVA
Servlet container popularly known as Servlet Engine which provide execution environment for Servlets and
manage Servlets lifecycle from creation to destroy phase.

Servlet Interface
● This interface is for developing servlets. A servlet is a body of Java code that is loaded into and runs
inside a servlet engine, such as a web server. It receives and responds to requests from clients. For
example, a client may need information from a database; a servlet can be written that receives the
request, gets and processes the data as needed by the client, and then returns it to the client.
● All servlets implement this interface. Servlet writers typically do this by subclassing either
GenericServlet, which implements the Servlet interface, or by subclassingGenericServlet's descendent,
HttpServlet.
● The Servlet interface defines methods to initialize a servlet, to receive and respond to client requests,
and to destroy a servlet and its resources. These methods are called by the network service in the
following manner:

1. Servlet is created then initialized.


2. Zero or more service calls from clients are handled.
3. Servlet is destroyed then garbage collected and finalized.

The following are the methods available in this interface:


init() Initializes the servlet. The method is called once, automatically, by the servlet
engine when it loads the servlet. It is guaranteed to finish before any service
requests are accepted.
getServletConfig() Returns a servlet config object, which contains any initialization parameters
and startup configuration for this servlet. This is the ServletConfig object
passed to the init method; the init method should have stored this object so
that this method could return it.
Service() Carries out a single request from the client. The method implements a request
and response paradigm. The request object contains information about the
service request, including parameters provided by the client. The response
object is used to return information to the client. The request and response
objects rely on the underlying network transport for quality of service
guarantees, such as reordering, duplication, privacy, and authentication.
getServletInfo() Returns a string containing information about the servlet, such as its author,
version, and copyright. As this method may be called to display such
information in an administrative tool that is servlet engine specific, the string
that this method returns should be plain text and not contain markup.
destroy() Cleans up whatever resources are being held (e.g., memory, file handles,
threads) and makes sure that any persistent state is synchronized with the
servlet's current in-memory state. The method is called once, automatically, by
the network service when it unloads the servlet. After destroy is run, it cannot
be called again until the network service reloads the servlet.

ServletContext interface
● Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to
get the MIME type of a file, dispatch requests, or write to a log file.
● 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.

Jyoti Samel Page 49


SYCS-SEMESTER IV-ADVANCED JAVA
● If any information is shared to many servlet, it is better to provide it from the web.xml file using the
<context-param> element.
● The ServletContext object is contained within the ServletConfig object, which the Web server provides
the servlet when the servlet is initialized. There can be a lot of usage of ServletContext object. Some of
them are as follows:

1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.

The following are the methods available in this interface:


Methods Description
getContextPath() Returns the context path of the web application.
getContext() Returns a ServletContext object that corresponds to a specified URL on the server.
getMimeType() Returns the MIME type of the specified file, or null if the MIME type is not known.
getResource() Returns a URL to the resource that is mapped to the given path.
Log Writes the specified message to a servlet log file, usually an event log. The name and
type of the servlet log file is specific to the servlet container.
getRealPath Gets the real path corresponding to the given virtual path.
getServerInfo() Returns the name and version of the servlet container on which the servlet is running.
getInitParameter Returns a String containing the value of the named context-wide initialization
parameter, or null if the parameter does not exist.
getInitParameterNa Returns the names of the context's initialization parameters as an Enumeration of
mes() String objects, or an empty Enumeration if the context has no initialization
parameters.
setInitParameter Sets the context initialization parameter with the given name and value on this
ServletContext.
getAttribute Returns the servlet container attribute with the given name, or null if there is no
attribute by that name.
getAttributeNames() Returns an Enumeration containing the attribute names available within this
ServletContext.
Syntax of getServletContext() method
public ServletContext getServletContext()

Example of getServletContext() method


ServletContext application=getServletContext();

ServletConfig interface
● An object of ServletConfig is created by the web container for each servlet. This object can be used to
get configuration information from web.xml file.
● If the configuration information is modified from the web.xml file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from time to
time.
● The core advantage of ServletConfig is that you don't need to edit the servlet file if information is
modified from the web.xml file.
● The following are the methods available in this interface:
Methods Description
getServletName Returns the name of this servlet instance. The name may be provided via
server administration, assigned in the web application deployment

Jyoti Samel Page 50


SYCS-SEMESTER IV-ADVANCED JAVA

descriptor, or for an unregistered (and thus unnamed) servlet instance it


will be the servlet's class name.
getServletContext Returns a reference to the ServletContext in which the caller is executing.
getInitParameter Returns a String containing the value of the named initialization
parameter, or null if the parameter does not exist.
getInitParameterNames Returns the names of the servlet's initialization parameters as an
Enumeration of String objects, or an empty Enumeration if the servlet has
no initialization parameters.
How to get the object of ServletConfig
getServletConfig() method of Servlet interface returns the object of ServletConfig.

Syntax of getServletConfig() method


public ServletConfig getServletConfig();

Example of getServletConfig() method


ServletConfig config = getServletConfig();

GenericServlet Class
● GenericServlet class implements Servlet, ServletConfig interfaces. It provides the implementation of
all the methods of these interfaces except the service method.
● GenericServlet class can handle any type of request so it is protocol-independent.
● You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method. There are many methods in GenericServlet class. They are as
follows:
Methods Description
public abstract void service(ServletRequest provides service for the incoming request. It is invoked at
request, ServletResponse response) each time when user requests for a servlet.
public void destroy() is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
public void init() it is a convenient method for the servlet programmers,
now there is no need to call super.init(config)
public String getServletName() Returns the name of the servlet object.

HttpServlet Class
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http
specific methods such as doGet, doPost, doHead, doTrace etc.

public abstract class HttpServlet extends GenericServlet implements java.io.Serializable

Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of
HttpServlet must override at least one method, usually one of these:
● doGet, if the servlet supports HTTP GET requests
● doPost, for HTTP POST requests
● doPut, for HTTP PUT requests

doDelete, for HTTP DELETE requests


● init and destroy, to manage resources that are held for the life of the servlet
● getServletInfo(), which the servlet uses to provide information about itself

Jyoti Samel Page 51


SYCS-SEMESTER IV-ADVANCED JAVA
Servlets typically run on multithreaded servers, so be aware that a servlet must handle concurrent requests
and be careful to synchronize access to shared resources. Shared resources include in-memory data such as
instance or class variables and external objects such as files, database connections, and network connections.

Jyoti Samel Page 52


SYCS-SEMESTER IV-ADVANCED JAVA
There are many methods in HttpServlet class. They are as follows:

Methods Description
doGet handles the GET request. It is invoked by the web container.
[protected void doGet(HttpServletRequest req, Parameters:
HttpServletResponse resp)] req - an HttpServletRequest object that contains the request
the client has made of the servlet
resp - an HttpServletResponse object that contains the
response the servlet sends to the client
getLastModified returns the time when HttpServletRequest was last modified
[protected long since midnight May 18, 1991 GMT.
getLastModified(HttpServletRequest req)]
doHead It handles the HEAD request. It is invoked by the web
[protected void doHead(HttpServletRequest container. The client sends a HEAD request when it wants to
req, see only the headers of a response, such as Content-Type or
HttpServletResponse resp)] Content-Length. The HTTP HEAD method counts the output
bytes in the response to set the Content-Length header
accurately.
doPost It handles the POST request. It is invoked by the web
[protected void doPost(HttpServletRequest req, container. The HTTP POST method allows the client to send
HttpServletResponse resp)] data of unlimited length to the Web server a single time and
is useful when posting information such as credit card
numbers.
doDelete handles the DELETE request. It is invoked by the web
[protected void doDelete(HttpServletRequest container. The DELETE operation allows a client to remove a
req, document or Web page from the server.
HttpServletResponse resp)]

GenericServlet HttpServlet
Can be used with any protocol (means, can Should be used with HTTP protocol only (can handle HTTP
handle any protocol). Protocol independent. specific protocols) . Protocol dependent.
All methods are concrete except service() All methods are concrete (non-abstract). service() is non-
method. service() method is abstract method. abstract method.
service() should be overridden being abstract in
service() method need not be overridden.
super interface.
It is a must to use service() method as it is a Being service() is non-abstract, it can be replaced by
callback method. doGet() or doPost() methods.
Extends Object and implements interfaces Extends GenericServlet and implements interface
Servlet, ServletConfig and Serializable. Serializable
Direct subclass of Servet interface. Direct subclass of GenericServlet.
Defined javax.servlet package. Defined javax.servlet.http package.
All the classes and interfaces belonging to All the classes and interfaces present in javax.servlet.http
javax.servlet package are protocol independent. package are protocol dependent (specific to HTTP).
Not used now-a-days. Used always.

Servlet Lifecycle
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.

Jyoti Samel Page 53


SYCS-SEMESTER IV-ADVANCED JAVA
4. service method is invoked.
5. destroy method is invoked.

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

1) Servlet class is loaded


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

2) Servlet instance is created


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

3) init method is invoked


The web container calls the init method only once
after creating the servlet instance. The init method
is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init
method is given below:
public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service
method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response) throwsServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from the service. It gives the
servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy
method of the Servlet interface is given below:
public void destroy()

Simple Servlet Program


import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
Jyoti Samel Page 54
SYCS-SEMESTER IV-ADVANCED JAVA
pw.close();//closing the stream
}}

Session tracking mechanism:

● 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.
● All requests and responses are independent. But sometimes you need to keep track of client's activity
across multiple requests. For eg. When a User logs into your website, not matter on which web page
he visits after logging in, his credentials will be with the server, until he logs out. So this is managed by
creating a session.
● Session is used to store everything that we can get from the client from all the requests the client
makes.
1.1 Advantages of Stateless Nature
● Keeps the protocol simple and straightforward
● Consumes fewer resources on the Web Server.
● Can support simultaneous visitors.

1.2 Disadvantages of Stateless Nature


● Increased overhead required creating a new connection with each request.
● Inability to track a single visitor traverses a website.
● The web server cannot automatically accept browser request with a particular session.

Workarounds
● Web applications have used several techniques to get around the stateless operations of HTTP:
Client identifies itself each time it makes a request and the server stores and retrieves data related to
that client – Sessions

Server send data to the client and forces the client to send it back with each request it makes -
Cookies

How Session Works

● 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

Jyoti Samel Page 55


SYCS-SEMESTER IV-ADVANCED JAVA
can always manage which user is doing what. Whenever a user wants to exit from your application,
destroy the object with his information.
● On client's first request, the Web Container generates a unique session ID and gives it back to the
client with response. This is a temporary session created by web container.
● The client sends back the session ID with each request. Making it easier for the web container to
identify where the request is coming from.
● The Web Container uses this ID, finds the matching session with the ID and associates the session with
the request.

How to get the HttpSessionobject ?


● The HttpServletRequest interface provides two methods to get the object of HttpSession:
● publicHttpSessiongetSession():Returns the current session associated with this request, or if the
request does not have a session, creates one.
● publicHttpSessiongetSession(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.

Commonly used methods of HttpSession interface


• public String getId():Returns a string containing the unique identifier value.
• public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
• public long getLastAccessedTime():Returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT.
• public void invalidate():Invalidates this session then unbinds any objects bound to it.

Session ID : A session ID is a unique number that a Web site's server assigns a specific user for the duration of
that user's visit (session). The session ID can be stored as a cookie, form field, or URL (Uniform Resource
Locator). Some Web servers generate session IDs by simply incrementing static numbers. However, most
servers use algorithms that involve more complex methods, such as factoring in the date and time of the visit
along with other variables defined by the server administrator.

Methods of Session Tracking


• User Authentication – This is the very common way where we user can provide authentication
credentials from the login page and then we can pass the authentication information between server
and client to maintain the session. This is not very effective method because it wont work if the same
user is logged in from different browsers.
• HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts
navigating, we can set its value unique to the user and keep track of the session. This method can’t be
used with links because it needs the form to be submitted every time request is made from client to
server with the hidden field. Also it’s not secure because we can get the hidden field value from the
HTML source and use it to hack the session.
• URL Rewriting – We can append a session identifier parameter with every request and response to
keep track of the session. This is very tedious because we need to keep track of this parameter in
every response and make sure it’s not clashing with other parameters.
• Cookies – Cookies are small piece of information that is sent by web server in response header and
gets stored in the browser cookies. When client make further request, it adds the cookie to the
request header and we can utilize it to keep track of the session. We can maintain a session with
cookies but if the client disables the cookies, then it won’t work.

Methods in HttpServlet Interface

Jyoti Samel Page 56


SYCS-SEMESTER IV-ADVANCED JAVA

Method Description
Gets the HttpSession object. If the request doesn’t have a session
public HttpSession getSession()
associated with it, a new session is created
Gets the session associated with the request. If not already present, then a
public HttpSession
new one is created based on the value of the boolean argument passed
getSession(boolean create)
into it
public String getId() Returns the unique session id
It returns the time when this session was created, measured in
public long getCreationTime()
milliseconds since midnight January 1, 1970 GMT.
public long It returns the time when this session was last accessed, measured in
getLastAccessedTime() milliseconds since midnight January 1, 1970 GMT.
public void invalidate() Invalidates the session

Example of Session tracking using HttpServlet Interface: In the below example the setAttribute() and
getAttribute() methods of the HttpSession interface is used to create an attribute in the session scope of one
servlet and fetch that attribute from the session scope of another servlet.

index.html
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit"></form>
Validate.java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class ValidateextendsHttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
HttpSessionsession = request.getSession(); session.setAttribute("user", name);
response.sendRedirect("Welcome");
}}}
Welcome.java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class WelcomeextendsHttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriterout = response.getWriter();
HttpSessionsession = request.getSession();
String user = (String)session.getAttribute("user"); out.println("Hello "+user);

Jyoti Samel Page 57


SYCS-SEMESTER IV-ADVANCED JAVA
}}

Chapter : 4
JSP

Introduction:

• Instead of static contents that are indifferent, Java Servlet was introduced to generate dynamic web
contents that are customized according to users' requests (e.g. in response to queries and search
requests). However, it is a pain to use a Servlet to produce a presentable HTML page (via the
out.prinltn() programming statements). It is even worse to maintain or modify that HTML page
produced. Programmers, who wrote the servlet, may not be a good graphic designer, while a graphic
designer does not understand Java programming.
● Java Server Pages (JSP) is a complimentary technology to Java Servlet which facilitates the mixing of
dynamic and static web contents. JSP is Java's answer to the popular Microsoft's Active Server
Pages(ASP). JSP, like ASP, provides a elegant way to mix static and dynamic contents. The main page is
written in regular HTML, while special tags are provided to insert pieces of Java programming codes.
The business programming logic and the presentation are cleanly separated. This allows the
programmers to focus on the business logic, while the web designer to concentrate on the
presentation.
● Write Once Run Anywhere: JSP technology brings the "Write Once, Run Anywhere" paradigm to
interactive Web pages. JSP pages can be moved easily across platforms, and across web servers,
without any changes.

How Java Server Pages works?

● A page using Java Server Pages is executed during the query, by a JSP engine (generally running with a
Web server or an application server). The JSP model is derived from the one used for Java servlets (JSP
are indeed a way to write servlets). It is a Java class derived from HttpServlet class, making use of
using doGet() and doPost() to return an HTTP response.

● When a user calls a JSP page, the Web server calls the JSP engine which creates a Java source code
from the JSP script and compile the class to provide a compiled file (with the .class extension).

● Note that: the JSP engine checks if the date of the .jsp file corresponds to the .class file. The JSP engine
will convert and compile the class, only if the JSP script has been updated. Thus, the fact that the
compilation only takes place when the JSP script is updated, makes JSP, one of the as test technologies
to create dynamic pages.

Why Use JSP?


● Java Server Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
● 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.

Jyoti Samel Page 58


SYCS-SEMESTER IV-ADVANCED JAVA
● 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.
● Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This
means that JSP can play a part in the simplest applications to the most complex and demanding.

ADVANTAGES
● The main advantage of the JSP method is that the output is standard HTML and is therefore compact
and universally readable in any browser. HTML requires little from the client except a compatible
browser. There is no JVM running on the client, so there is no requirement for a set of Java runtime
files or Java application files on the local PC.
● The presentation look-and-feel of a page is embedded in HTML tags and cascading style sheets (an
HTML facility for changing the appearance and formatting of common tags in a standardized way).
Since the HTML tags are directly embedded in the JSP source file, you can split the development work.
A web graphics designer can create the template look-and-feel for a page, while the dynamic JSP-
specific sections would be developed by a Java programmer.
● Merging the work is just a matter of embedding one into the other.
● HTML friendly simple and easy language and tags.
● Supports Java Code.
● Supports standard Web site development tools.

DISADVANTAGES
● The main advantage of JSP pages—that they output lightweight HTML—is also the main disadvantage.
You do not use the feature-rich Swing (or AWT) controls to construct the user interface.
● The HTML language is not a programming language as such and has fewer features than the Swing
controls for creating a user interface. In addition, simple functions such as scrolling down in a list of
records, deleting a record, or changing the way information is sorted requires a refresh of the page.
● You can embed JavaScript in the HTML page to enhance functionality, but this solution requires that
the JavaScript that you use be supported by the ability of your users' browsers to interpret it correctly.
● As JSP pages are translated to servlets and compiled, it is difficult to trace errors occurred in JSP pages.
● JSP pages require double the disk space to hold the JSP page.
● JSP pages require more time when accessed for the first time as they are to be compiled on the server.

Lifecycle of JSP
When a web container or servlet container receives a request from client for a jsp page, it takes the jsp
through its various life cycle phases, and then returns the response to the client. What all things these
containers should support, is defined by the jsp and servlet specifications. The web containers can be a part of
web servers, e.g. tomcat, and application servers.
Following diagram shows the different stages of life cycle of jsp. Broadly, these stages can be classified into
three.
● Instantiation
● Request Processing
● Destruction

Jyoti Samel Page 59


SYCS-SEMESTER IV-ADVANCED JAVA

I. Instantiation:
When a web container receives a jsp request (may be first or subsequent), it checks for the jsp’s servlet
instance. If no servlet instance is available or if it is older than the jsp, then, the web container creates the
servlet instance using following stages.
a) Translation
b) Compilation
c) Loading
d) Instantiation
e) Initialization

a) Translation:
Web container translates (converts) the jsp code into a servlet code. This means that jsp is actually a
servlet. After this stage, there is no jsp, everything is a servlet. This task will create a complete jsp
page, by considering all included components. Here on, the static content and dynamic contents are
treated differently. The resultant is a java class instead of an html page (which we wrote). This is how
the structure of a jsp compiled into a java class will be. package org.apache.jsp.WEB_002dINF.jsp;
b) Compilation:
The generated servlet is compiled to validate the syntax. As it is a java class, the compilation is done
using javac command. This will generate the byte code to be run on JVM.
c) Loading:
The compiled byte code is loaded by the class loader used by web container. This is a standard process
of using any java class.
d) Instantiation:
In this step, instance of the servlet class is created so that it can serve the request.
e)Initialization:
Initialization is done by calling the jspInit() method. This is one time activity at the start of the
initialization process. Initialization will make the ServletContext and ServletConfig objects available.
One can access many attributes related to the web container and the servlet itself. After initialization
the servlet is ready to process requests.

II. Request Processing:


Entire initialization process is done to make the servlet available in order to process the incoming request.
jspService() is the method that actually processes the request. It prints the response in html (any other)
format, using ‘out’ object.

III. Destroy:

Jyoti Samel Page 60


SYCS-SEMESTER IV-ADVANCED JAVA
Whenever the server is shutting down or when the server needs memory, the server removes the instance of
the servlet. The destroy method jspDestroy() can be called by the server after initialization and before or after
request processing. Once destroyed the jsp needs to be initialized again.

JSP - Implicit Objects and scope

These Objects are the Java objects that the JSP Container makes available to the developers in each page and
the developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-
defined variables.

Following table lists out the nine Implicit Objects that JSP supports −

S.No. Object & Description


request
1
This is the HttpServletRequest object associated with the request.

response
2
This is the HttpServletResponse object associated with the response to the client.

out
3
This is the PrintWriter object used to send output to the client.

session
4
This is the HttpSession object associated with the request.

application
5
This is the ServletContext object associated with the application context.

config
6
This is the ServletConfig object associated with the page.

pageContext
7
This encapsulates use of server-specific features like higher performance JspWriters.

page

8 This is simply a synonym for this, and is used to call the methods defined by the translated
servlet class.

Exception
9
The Exception object allows the exception data to be accessed by designated JSP.

Jyoti Samel Page 61


SYCS-SEMESTER IV-ADVANCED JAVA
The request Object

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client


requests a page the JSP engine creates a new object to represent that request.

The request object provides methods to get the HTTP header information including form data, cookies, HTTP
methods etc.

The response Object

The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server


creates the request object, it also creates an object to represent the response to the client.

The response object also defines the interfaces that deal with creating new HTTP headers. Through this object
the JSP programmer can add new cookies or date stamps, HTTP status codes, etc.

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Implicit Guru JSP4</title>
8. </head>
9. <body>
10. <%response.setContentType("text/html"); %>
11. </body>
12. </html>

The out Object

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a
response.

The initial JspWriter object is instantiated differently depending on whether the page is buffered or not.
Buffering can be easily turned off by using the buffered = 'false' attribute of the page directive.

The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter
has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws
IOExceptions.

Jyoti Samel Page 62


SYCS-SEMESTER IV-ADVANCED JAVA
Following table lists out the important methods that we will use to write boolean char, int, double, object,
String, etc.

S.No. Method & Description

out.print(dataType dt)
1
Print a data type value

out.println(dataType dt)
2
Print a data type value then terminate the line with new line character.

out.flush()
3
Flush the stream.

<body>
<% int num1=10;int num2=20;
out.println("num1 is " +num1);
out.println("num2 is "+num2);
%>

The session Object

The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that
session objects behave under Java Servlets.

The session object is used to track client session between client requests.

The application Object

The application object is direct wrapper around the ServletContext object for the generated Servlet and in
reality an instance of a javax.servlet.ServletContext object.

This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP
page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.

By adding an attribute to application, you can ensure that all JSP files that make up your web application have
access to it.

<body>
<% application.getContextPath(); %>
</body>

The config Object

The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the
ServletConfig object for the generated servlet.

This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the
paths or file locations etc.

The following config method is the only one you might ever use, and its usage is trivial −

Jyoti Samel Page 63


SYCS-SEMESTER IV-ADVANCED JAVA
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the
WEB-INF\web.xml file.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru JSP5</title>
</head>
<body>
<% String servletName = config.getServletName();
out.println("Servlet Name is " +servletName);%>
</body>
</html>

The pageContext Object

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is


used to represent the entire JSP page.

This object is intended as a means to access information about the page while avoiding most of the
implementation details.

This object stores references to the request and response objects for each request. The application, config,
session, and out objects are derived by accessing attributes of this object.

The pageContext object also contains information about the directives issued to the JSP page, including the
buffering information, the errorPageURL, and page scope.

The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and
APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of
which are inherited from the javax.servlet.jsp.JspContext class.

One of the important methods is removeAttribute. This method accepts either one or two arguments. For
example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the
following code only removes it from the page scope −

pageContext.removeAttribute("attrName", PAGE_SCOPE);

The page Object

This object is an actual reference to the instance of the page. It can be thought of as an object that represents
the entire JSP page.

The page object is really a direct synonym for the this object.

The exception Object

The exception object is a wrapper containing the exception thrown from the previous page. It is typically used
to generate an appropriate response to the error condition.

JSP Directives

Jyoti Samel Page 64


SYCS-SEMESTER IV-ADVANCED JAVA
● JSP directives are the messages to JSP container. They provide global information about an entire JSP
page.
● JSP directives are used to give special instruction to a container for translation of JSP to servlet code.
● In JSP life cycle phase, JSP has to be converted to a servlet which is the translation phase.
● They give instructions to the container on how to handle certain aspects of JSP processing
● Directives can have many attributes by comma separated as key-value pairs.
● In JSP, directive is described in <%@ %> tags.

Syntax of Directive:

<%@ directive attribute="" %>


There are three types of directives:

1. Page directive
2. Include directive
3. Taglib directive

Each one of them is described in detail below with examples:

In this tutorial, you will learn -

● JSP Page directive


● JSP Include directive
● JSP Taglib Directive

JSP Page directive

Syntax of Page directive:

<%@ page…%>

● It provides attributes that get applied to entire JSP page.


● It defines page dependent attributes, such as scripting language, error page, and buffering
requirements.
● It is used to provide instructions to a container that pertains to current JSP page.

Following are its list of attributes associated with page directive:

1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. autoflush
9. buffer
10. IsErrorPage
11. pageEncoding
12. errorPage
13. isELIgonored

Jyoti Samel Page 65


SYCS-SEMESTER IV-ADVANCED JAVA
More details about each attribute

1. language: It defines the programming language (underlying language) being used in the page.

Syntax of language:

<%@ page language="value" %>


Here value is the programming language (underlying language)

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
Explanation of code: In the above example, attribute language value is Java which is the underlying language
in this case. Hence, the code in expression tags would be compiled using java compiler.

2. Extends: This attribute is used to extend (inherit) the class like JAVA does

Syntax of extends:

<%@ page extends="value" %>


Here the value represents class from which it has to be inherited.

Example:

<%@ page extends="demotest.DemoClass" %>


Explanation of the code: In the above code JSP is extending DemoClass which is within demotest package, and
it will extend all class features.

3. Import: This attribute is most used attribute in page directive attributes.It is used to tell the container
to import other java classes, interfaces, enums, etc. while generating servlet code.It is similar to
import statements in java classes, interfaces.

Syntax of import:

<%@ page import="value" %>


Here value indicates the classes which have to be imported.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


import="java.util.Date" pageEncoding="ISO-8859-1"%>
Explanation of the code:

In the above code, we are importing Date class from java.util package (all utility classes), and it can use all
methods of the following class.

4. contentType:

● It defines the character encoding scheme i.e. it is used to set the content type and the character set of
the response
● The default type of contentType is "text/html; charset=ISO-8859-1".

Syntax of the contentType:

Jyoti Samel Page 66


SYCS-SEMESTER IV-ADVANCED JAVA
<%@ page contentType="value" %>
Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
Explanation of the code:

In the above code, the content type is set as text/html, it sets character encoding for JSP and for generated
response page.

5. info

● It defines a string which can be accessed by getServletInfo() method.


● This attribute is used to set the servlet description.

Syntax of info:

<%@ page info="value" %>


Here, the value represents the servlet information.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


info="Guru Directive JSP" pageEncoding="ISO-8859-1"%>
Explanation of the code:

In the above code, string "Guru Directive JSP" can be retrieved by the servlet interface using getServletInfo()

6. Session

● JSP page creates session by default.


● Sometimes we don't need a session to be created in JSP, and hence, we can set this attribute to false
in that case.The default value of the session attribute is true, and the session is created.

When it is set to false, then we can indicate the compiler to not create the session by default.

Syntax of session:

<%@ page session="true/false"%>


Here in this case session attribute can be set to true or false

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


session="false"%>
Explanation of code:

In the above example, session attribute is set to "false" hence we are indicating that we don't want to create
any session in this JSP

7. isThreadSafe:

● It defines the threading model for the generated servlet.


● It indicates the level of thread safety implemented in the page.

Jyoti Samel Page 67


SYCS-SEMESTER IV-ADVANCED JAVA
● Its default value is true so simultaneous
● We can use this attribute to implement SingleThreadModel interface in generated servlet.
● If we set it to false, then it will implement SingleThreadModel and can access any shared objects and
can yield inconsistency.

Syntax of isThreadSafe:

<% @ page isThreadSafe="true/false" %>


Here true or false represents if synchronization is there then set as true and set it as false.

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


isThreadSafe="true"%>
Explanation of the code:

In the above code, isThreadSafe is set to "true" hence synchronization will be done, and multiple threads can
be used.

8. AutoFlush:

This attribute specifies that the buffered output should be flushed automatically or not and default value of
that attribute is true.

If the value is set to false the buffer will not be flushed automatically and if its full, we will get an exception.

When the buffer is none then the false is illegitimate, and there is no buffering, so it will be flushed
automatically.

Syntax of autoFlush:

<% @ page autoFlush="true/false" %>


Here true/false represents whether buffering has to be done or not

Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


autoFlush="false"%>
Explanation of the code:

In the above code, the autoflush is set to false and hence buffering won't be done and it has manually flush
the output.

9.Buffer:

● Using this attribute the output response object may be buffered.


● We can define the size of buffering to be done using this attribute and default size is 8KB.
● It directs the servlet to write the buffer before writing to the response object.

Syntax of buffer:

<%@ page buffer="value" %>


Here the value represents the size of the buffer which has to be defined. If there is no buffer, then we can
write as none, and if we don't mention any value then the default is 8KB

Jyoti Samel Page 68


SYCS-SEMESTER IV-ADVANCED JAVA
Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


buffer="16KB"%>
Explanation of the code:

In the above code, buffer size is mentioned as 16KB wherein the buffer would be of that size

10. isErrorPage:

● It indicates that JSP Page that has an errorPage will be checked in another JSP page
● Any JSP file declared with "isErrorPage" attribute is then capable to receive exceptions from other JSP
pages which have error pages.
● Exceptions are available to these pages only.
● The default value is false.

Syntax of isErrorPage:

<%@ page isErrorPage="true/false"%>


Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


isErrorPage="true"%>
Explanation of the code:

In the above code, isErrorPage is set as true. Hence, it will check any other JSPs has errorPage (described in
the next attribute) attribute set and it can handle exceptions.

11. PageEncoding:

The "pageEncoding" attribute defines the character encoding for JSP page.
The default is specified as "ISO-8859-1" if any other is not specified.

Syntax of pageEncoding:

<%@ page pageEncoding="vaue" %>


Here value specifies the charset value for JSP

Example:

<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"


isErrorPage="true"%>
Explanation of the code:

In the above code "pageEncoding" has been set to default charset ISO-8859-1

12. errorPage:

This attribute is used to set the error page for the JSP page if JSP throws an exception and then it redirects to
the exception page.
Syntax of errorPage:

<%@ page errorPage="value" %>


Here value represents the error JSP page value

Jyoti Samel Page 69


SYCS-SEMESTER IV-ADVANCED JAVA
Example:

<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"


errorPage="errorHandler.jsp"%>
Explanation of the code:

In the above code, to handle exceptions we have errroHandler.jsp

13. isELIgnored:

● IsELIgnored is a flag attribute where we have to decide whether to ignore EL tags or not.
● Its datatype is java enum, and the default value is false hence EL is enabled by default.

Syntax of isELIgnored:

<%@ page isELIgnored="true/false" %>


Here, true/false represents the value of EL whether it should be ignored or not.

Example:

<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"


isELIgnored="true"%>
Explanation of the code:

In the above code, isELIgnored is true and hence Expression Language (EL) is ignored here.

In the below example we are using four attributes(code line 1-2)

Example with four attributes

<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"


isELIgnored="false"%>
<%@page import="java.util.Date" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Directive Guru JSP1</title>
</head>
<body>
<a>Date is:</a>
<%= new java.util.Date() %>
</body>
</html>
Explanation of the code:

Code Line 1-2: Here we have defined four attributes i.e.

● Language: It is set as Java as programming language


● contentType: set as text/html to tell the compiler that html has to be format
● pageEncoding: default charset is set in this attribute
● isELIgnored: Expression Tag is false hence it is not ignored

Jyoti Samel Page 70


SYCS-SEMESTER IV-ADVANCED JAVA
Code Line 3: Here we have used import attribute, and it is importing "Date class" which is from Java util
package, and we are trying to display current date in the code.

When you execute the above code, you will get the following output

Output:

● Date is: Current date using the date method of the date class

JSP Include directive

● JSP "include directive"( codeline 8 ) is used to include one file to the another file
● This included file can be HTML, JSP, text files, etc.
● It is also useful in creating templates with the user views and break the pages into header&footer and
sidebar actions.
● It includes file during translation phase

Syntax of include directive:

<%@ include….%>
Example:

Directive_jsp2.jsp (Main file)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ include file="directive_header_jsp3.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Directive JSP2</title>
</head>
<body>
<a>This is the main file</a>
</body>
</html>
Directive_header_jsp3.jsp (which is included in the main file)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
Jyoti Samel Page 71
SYCS-SEMESTER IV-ADVANCED JAVA
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 
</head>
<body>
<a>Header file : </a>
<%int count =1; count++;
out.println(count);%> :
</body>
</html>
Explanation of the code:

Directive_jsp2.jsp:

Code Line 3: In this code, we use include tags where we are including the file directive_header_jsp3.jsp into
the main file(_jsp2.jsp)and gets the output of both main file and included file.

Directive_header_jsp3.jsp:

Code Line 11-12: We have taken a variable count initialized to 1 and then incremented it. This will give the
output in the main file as shown below.

When you execute the above code you get the following output:

Output:

● The output is Header file: 2 : This is the main file


● The output is executed from the directive_jsp2.jsp file while the directive_header_jsp3.jsp included
file will be compiled first.
● After the included file is done, the main file is executed, and the output will be from the main file "This
is the main file". So you will get the output as "Header file: 2" from _jsp3.jsp and "This is main file"
from _jsp2.jsp.

JSP Taglib Directive

● JSP taglib directive is used to define the tag library with "taglib" as the prefix, which we can use in JSP.
● More detail will be covered in JSP Custom Tags section
● JSP taglib directive is used in the JSP pages using the JSP standard tag libraries
● It uses a set of custom tags, identifies the location of the library and provides means of identifying
custom tags in JSP page.

Syntax of taglib directive:

<%@ taglib uri="uri" prefix="value"%>

Jyoti Samel Page 72


SYCS-SEMESTER IV-ADVANCED JAVA
Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a tag name.

Example:

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


2. pageEncoding="ISO-8859-1"%>
3. <%@ taglib prefix="gurutag" uri="http://java.sun.com/jsp/jstl/core" %>
4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
5. <html>
6. <head>
7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8. <title>Guru Directive JSP</title>
9. <gurutag:hello/>
10. </head>
11. <body>
12. </body>
13. </html>

Explanation of the code:

Code Line 3: Here "taglib" is defined with attributes uri and prefix.

JSP Scripting Element


JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are processed by the JSP
engine during translation of the JSP page. Any other text in the JSP page is considered as HTML code or plain
text.

Example:

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
Just to experiment, try removing the <% %> scriplet tag from the above code and run it as JSP. You will see
that everything is printed as it is on the browser, because without the scriplet tag, everything is considered
plain HTML code.

Jyoti Samel Page 73


SYCS-SEMESTER IV-ADVANCED JAVA
There are five different types of scripting elements
Scripting
Example
Element

<%-- comment --
Comment
%>

Directive <%@ directive %>

<%! declarations
Declaration
%>

Scriptlet <% scriplets %>

<%= expression
Expression
%>

JSP Comment

JSP comment is to document the code. In addition, JSP comment is used to note some parts of JSP page to
make it clearer and easier to maintain. The following illustrates JSP comment inside a JSP page:

<%-- This is a JSP comment --


%>
 
<%--
   This is a JSP comment can
span
   in multiple lines
--%>

JSP comment is stripped off from the page in the response to the web browser.

Expression

The expression is one of the most basic scripting element in JSP. The expression is used to insert value directly
to the output. The syntax of an expression is as follows:

<?=
1
expression ?>

It is noticed that there is no space between <% and =. For example, if you want to display the current date and
time, you can use an expression as follows:

<%= new java.util.Date()


%>

You can also use XML syntax of the JSP expression to achieve the same effect as the following example:

1 <jsp:expression
Jyoti Samel Page 74
SYCS-SEMESTER IV-ADVANCED JAVA

>
  Java
2 Expression
3
</jsp:expressio
n>

Scriptlet

Scriptlet is similar to expression except for the equal sign “=”. You can insert any plain Java code inside a
scriptlet. Because of mixing between Java code and HTML make JSP page difficult to maintain so scriptlet is
not recommended for future development.
The following illustrates the syntax of scriptlet:

<% // any java source code here


1
%>

In this example, we display a greeting message based on the current time of the day using the scriptlet.

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
    <head>
        <title>JSP syntax</title>
    </head>
    <body>
        <%
                // using scriptlet
                java.util.Calendar now = new java.util.GregorianCalendar();
                String tod = "";
 
                if (now.get(now.HOUR_OF_DAY) < 12) {
                    tod = "Morning!";
                } else if (now.get(now.HOUR_OF_DAY) < 18) {
                    tod = "Afternoon!";
                } else {
                    tod = "Evening!";
                }
        %>
 
        Good <%=tod%>
 
    </body>
</html>

The XML syntax of JSP scriptlet is as follows:

<jsp:scriptlet>
   // Java code of

Jyoti Samel Page 75


SYCS-SEMESTER IV-ADVANCED JAVA

scriptlet
</jsp:scriptlet>

Declaration

1. Variable declaration
2. Method declaration
3. Class declaration

If you want to define methods or fields, you can use JSP declaration. The JSP declaration is surrounded by the
sign <%! and %>. For example, if you want to declare a variable x, you can use JSP declaration as follows:

<%! int x = 10;


1
%>

The final semicolon is required.

The difference between a variable using declaration and a variable is declared using scriptlet is that a variable
declared using declaration tag is accessible by all methods, while a variable declared using scriptlet is only
accessible to the _jspservice() method of the generated servlet from the JSP page.

We can also declare a method using declaration tag as the following example:

<%! public boolean isInRange(int x,int min,int max){return x >= min && x <= max;}
%>

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

JSP Action
Description
Tags
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setPropert
sets the value of property in bean object.
y
jsp:getProper
prints the value of property of the bean.
ty
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
can be used to print the message if plugin is working. It is used in
jsp:fallback
jsp:plugin.

jsp:include action tag

Jyoti Samel Page 76


SYCS-SEMESTER IV-ADVANCED JAVA
● 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.

Advantage of jsp:include action tag


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.
Difference between jsp include directive and include action JSP include directive
include directive in Page JSP include action
includes resource at translation time. includes resource at request time.
better for static pages. better for dynamic pages.
includes the original content in the generated calls the include method.
servlet.
Syntax of jsp:include action tag without parameter
<jsp:include page="relativeURL | <%= expression %>" />

Syntax of jsp:include action tag with parameter


<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:include>

Example of jsp:include action tag without parameter


File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>

File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>

Forwarding JSP Page to Another Page


jsp:forward action tag
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or another
resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>

Example of jsp:forward action tag without parameter


index.jsp

<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>

Jyoti Samel Page 77


SYCS-SEMESTER IV-ADVANCED JAVA

</html>

printdate.jsp

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

Example of jsp:forward action tag with parameter


In this example, we are forwarding the request to the printdate.jsp file with parameter and printdate.jsp file
prints the parameter value with date and time.

index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="sname" value="Sandhya" />
<jsp:param name="sclass" value="SYCS" />
<jsp:param name="srollno" value="9" />
</jsp:forward>
</body>
</html>

printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("sname") %>
<%= request.getParameter("sname") %>
<%= request.getParameter("sname") %>
</body> </html>

Loading a JavaBean
A Java Bean is a java class that should follow following conventions:
● It should have a no-arg constructor.
● It should be Serializable.
● It should provide methods to set and get the values of the properties, known as getter and setter
methods.

Why use Java Bean?


According to Java white paper, it is a reusable software component. A bean encapsulates many objects into
one object, so we can access this object from multiple places. Moreover, it provides the easy maintenance.

Simple example of java bean class


//Employee.java
package mypack;

Jyoti Samel Page 78


SYCS-SEMESTER IV-ADVANCED JAVA
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;
} public int getId(){return id;
} public void setName(String name){this.name=name;
} public String getName(){return name;
}
}

jsp:useBean action tag


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.
Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>

Attributes and Usage of jsp:useBean action tag


● id: is used to identify the bean in the specified scope.
● scope: represents the scope of the bean. It may be page, request, session or application. The default
scope is page.
● page: specifies that you can use this bean within the JSP page. The default scope is page.
● request: specifies that you can use this bean from any JSP page that processes the same request. It
has wider scope than page.
● session: specifies that you can use this bean from any JSP page in the same session whether processes
the same request or not. It has wider scope than request.
● application: specifies that you can use this bean from any JSP page in the same application. It has
wider scope than session.
● class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have
no-arg or no constructor and must not be abstract.
● type: provides the bean a data type if the bean already exists in the scope. It is mainly used with class
or beanName attribute. If you use it without class or beanName, no bean is instantiated.
● beanName:instantiates the bean using the java.beans.Beans.instantiate() method.

Simple example of jsp:useBean action tag


Calculator.java (a simple Bean class)
public class Calculator{
public int cube(int n){return n*n*n;}
}

index.jsp file
<jsp:useBean id="obj" class="ABC"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);

Jyoti Samel Page 79


SYCS-SEMESTER IV-ADVANCED JAVA
%>

Passing parameters for other actions


jsp:setProperty action tag
● 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 mthod.

Syntax of jsp:setProperty action tag


<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>

Example of jsp:setProperty action tag if you have to set all the values of incoming request in the bean
<jsp:setProperty name="bean" property="*" />

jsp:getProperty action tag


The jsp:getProperty action tag returns the value of the property.
Syntax of jsp:getProperty action tag
<jsp:getProperty name="instanceOfBean" property="propertyName" />
Simple example of jsp:getProperty action tag
<jsp:getProperty name="obj" property="name" />

Displaying applet in JSP (jsp:plugin action tag)


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

Syntax of jsp:plugin action tag


<jsp:plugin type= "applet | bean" code= "nameOfClassFile"
codebase= "directoryNameOfClassFile"
</jsp:plugin>

Jyoti Samel Page 80


SYCS-SEMESTER IV-ADVANCED JAVA

Chapter : 5
Java Bean

What is JavaBeans?

JavaBeans is a portable, platform-independent model written in Java Programming Language. Its components
are referred to as beans. 

In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It helps in
accessing these object from multiple places. JavaBeans contains several elements like Constructors,
Getter/Setter Methods and much more.

JavaBeans has several conventions that should be followed:

● Beans should have a default constructor (no arguments)


● Beans should provide getter and setter methods
o A getter method is used to read the value of a readable property
o To update the value, a setter method should be called
● Beans should implement java.io.serializable, as it allows to save, store and restore the state of a
JavaBean you are working on

Now that you are familiar with basics, let’s learn in detail about the properties of JavaBeans.

Components of JavaBeans

The classes that contained definition of beans is known as components of JavaBeans. These classes follows
certain design conventions. It includes properties, events, methods and persistence. There are two types of
components, GUI based and non GUI based. For instance JButton is example of a component not a class.

Properties (date members): Property is a named attribute of a bean, it includes color, label, font, font size,
display size. It determines appearance, behavior and state of a bean.

Methods: Methods in JavaBeans are same as normal Java methods in a class. It doesn’t follow any specific
naming conventions. All properties should have accessor and getter methods.

Events: Events in JavaBeans are same as SWING/AWT event handling.

Persistence: Serializable interface enables JavaBean to store its state.

JavaBean has no argument constructor.

Jyoti Samel Page 81


SYCS-SEMESTER IV-ADVANCED JAVA
//Employee.java  

package mypack;  
public class Employee implements java.io.Serializable{  
private int id;  
private String name;  
public Employee(){}  
public void setId(int id){this.id=id;}  
public int getId(){return id;}  
public void setName(String name){this.name=name;}  
public String getName(){return name;}  
}  

How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

package mypack;  
public class Test{  
public static void main(String args[]){  
Employee e=new Employee();//object is created  
e.setName("Arjun");//setting value to the object  
System.out.println(e.getName());  
}}  

JavaBean Properties

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

A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through two
methods in the JavaBean's implementation class:

1. getPropertyName ()

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

2. setPropertyName ()

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

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

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


● It provides an easiness to reuse the software components.

Jyoti Samel Page 82


SYCS-SEMESTER IV-ADVANCED JAVA
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:

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


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

Jyoti Samel Page 83


SYCS-SEMESTER IV-ADVANCED JAVA

What is JSON?
JSON stands for JavaScript Object Notation

JSON is a lightweight format for storing and transporting data

JSON is often used when data is sent from a server to a web page

JSON is "self-describing" and easy to understand

JSON Example

This example defines an employees object: an array of 3 employee records (objects):

{
"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
}

JSON Syntax Rules


● Data is in name/value pairs
● Data is separated by commas
● Curly braces hold objects
● Square brackets hold arrays

JavaScript Object Notation


The JSON format is syntactically identical to the code for creating JavaScript objects.

Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and
generating JSON data can be written in any programming language.

JSON Data - A Name and a Value


JSON data is written as name/value pairs, just like JavaScript object properties.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

"firstName":"John"

JSON names require double quotes. JavaScript names do not.

JSON Objects
JSON objects are written inside curly braces.

Jyoti Samel Page 84


SYCS-SEMESTER IV-ADVANCED JAVA
Just like in JavaScript, objects can contain multiple name/value pairs:

{"firstName":"John", "lastName":"Doe"}

JSON Arrays
JSON arrays are written inside square brackets.

Just like in JavaScript, an array can contain objects:

"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]

In the example above, the object "employees" is an array. It contains three objects.

Each object is a record of a person (with a first name and a last name).

Converting a JSON Text to a JavaScript Object


A common use of JSON is to read data from a web server, and display the data in a web page.

For simplicity, this can be demonstrated using a string as input.

First, create a JavaScript string containing JSON syntax:

var text = '{ "employees" : [' +


'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:

var obj = JSON.parse(text);

Finally, use the new JavaScript object in your page:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

Jyoti Samel Page 85


SYCS-SEMESTER IV-ADVANCED JAVA

<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

</body>
</html>

Output:

Create Object from JSON String


Anna Smith

Jyoti Samel Page 86


SYCS-SEMESTER IV-ADVANCED JAVA

JSON Data types


JSON format supports the following data types −

Sr.No Type & Description


.

1
Number

double- precision floating-point format in JavaScript

2
String

double-quoted Unicode with backslash escaping

3
Boolean

true or false

4
Array

an ordered sequence of values

5
Value

it can be a string, a number, true or false, null etc

6
Object

an unordered collection of key:value pairs

7
Whitespace

can be used between any pair of tokens

8
null

empty

Number

● It is a double precision floating-point format in JavaScript and it depends on implementation.

● Octal and hexadecimal formats are not used.

● No NaN or Infinity is used in Number.

The following table shows the number types −

Sr.No Type & Description


.

1
Integer

Digits 1-9, 0 and positive or negative

Jyoti Samel Page 87


SYCS-SEMESTER IV-ADVANCED JAVA

2
Fraction

Fractions like .3, .9

3
Exponent

Exponent like e, e+, e-, E, E+, E-

Syntax
var json-object-name = { string : number_value, .......}

Example
Example showing Number Datatype, value should not be quoted −

var obj = {marks: 97}

String

● It is a sequence of zero or more double quoted Unicode characters with backslash escaping.

● Character is a single character string i.e. a string with length 1.

The table shows various special characters that you can use in strings of a JSON document −

Sr.No Type & Description


.

1
"

double quotation

2
\

backslash

3
/

forward slash

4
b

backspace

5
f

form feed

6
n

new line

7
r

carriage return

8
t

horizontal tab

Jyoti Samel Page 88


SYCS-SEMESTER IV-ADVANCED JAVA

9
u

four hexadecimal digits

Syntax
var json-object-name = { string : "string value", .......}

Example
Example showing String Datatype −

var obj = {name: 'Amit'}

Boolean

It includes true or false values.

Syntax
var json-object-name = { string : true/false, .......}

Example
var obj = {name: 'Amit', marks: 97, distinction: true}

Array

● It is an ordered collection of values.

● These are enclosed in square brackets which means that array begins with .[. and ends with .]..

● The values are separated by , (comma).

● Array indexing can be started at 0 or 1.

● Arrays should be used when the key names are sequential integers.

Syntax
[ value, .......]

Example
Example showing array containing multiple objects −

{
"books": [
{ "language":"Java" , "edition":"second" },
{ "language":"C++" , "lastName":"fifth" },
{ "language":"C" , "lastName":"third" }
]
}

Object

● It is an unordered set of name/value pairs.

● Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.

● Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma).

● The keys must be strings and should be different from each other.

● Objects should be used when the key names are arbitrary strings.

Syntax
{ string : value, .......}

Example
Example showing Object −

Jyoti Samel Page 89


SYCS-SEMESTER IV-ADVANCED JAVA
{
"id": "011A",
"language": "JAVA",
"price": 500,
}

Whitespace

It can be inserted between any pair of tokens. It can be added to make a code more readable. Example shows declaration with and without whitespace −

Syntax
{string:" ",....}

Example
var obj1 = {"name": "Sachin Tendulkar"}
var obj2 = {"name": "SauravGanguly"}

null

It means empty type.

Syntax
null

Example
var i = null;

if(i == 1) {
document.write("<h1>value is 1</h1>");
} else {
document.write("<h1>value is null</h1>");
}

JSON Value

It includes −

● number (integer or floating point)


● string
● boolean
● array
● object
● null

Syntax
String | Number | Object | Array | TRUE | FALSE | NULL

Example
var i = 1;
var j = "sachin";
var k = null;

Jyoti Samel Page 90

You might also like