SYCS - Sem 4 - Advanced Java Notes
SYCS - Sem 4 - Advanced Java Notes
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
JSP: Introduction,
JSP LifeCycle,
JSP Implicit Objects & Scopes, JSP Directives,
JSP Scripting Elements,
JSP Actions: Standard actions and customized actions,
JSON: Overview,
Syntax,
DataTypes,
Objects,
Schema,
Comparison with XML,
JSON with Java
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.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
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.
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:
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(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
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.
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);
}
}
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(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int columns) Creates a new TextField initialized with the specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified number of columns.
It returns the currently set Action for this ActionEvent source, or null
Action getAction()
if no Action is set.
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);
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
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.
void insert(String s, int position) It is used to insert the specified text on the specified position.
void append(String s) It is used to append the given text to the end of the document.
import javax.swing.*;
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(int columns) Constructs a new empty JPasswordField with the specified number of
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.
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);
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.
import javax.swing.*;
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() Creates an initially unselected check box button with no text, no icon.
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.
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);
}
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.
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.
void addActionListener
It is used to add the action listener to this object.
(ActionListener a)
Java JComboBox
JComboBox components combines a button or editable filed 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(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.
void removeAllItems() It is used to remove all the items from the list.
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);
f.add(cb);
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(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the specified, non-null, model.
Void addListSelectionListener It is used to add a listener to the list, to be notified each time a change
(ListSelectionListener listener) to the selection occurs.
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.
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
Constructor:
Example :
import javax.swing.*;
class JTableExample
{
public static void main(String args[])
{
JFrame f = new JFrame("JList Example");
JPanel p=new JPanel();
final Object[][] info={ {"1","jeet"} , {"2","hari"}, {"3","kavi"}};
final String[] cHead={"Roll no", "Name"};
JTable jT=new JTable(info, cHead);
p.add(jT);
f.add(p);
f.setSize(400,400);
f.setVisible(true);
}
}
final Object[][] info={ {"1","jeet"} , {"2","hari"}, {"3","kavi"}};
JTabbedPane
Are the space savers used to display child component. The child component can be displayed one at a time.
JTabbedPane()
import javax.swing.*;
class JTabbedPaneExample
{
public static void main(String args[])
{
JFrame f = new JFrame("JList Example");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTabbedPane jTab=new JTabbedPane();
JLabel jL1=new JLabel("This is tab onq");
JLabel jL2=new JLabel("This is tab two");
JTextField jT1=new JTextField("welcome");
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);
}
}
JMenuItem:
JMenu()
JMenu(String label)
JMenuItem(String s)
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.
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:
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.
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.
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.
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.
Advantage:
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.
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.
To implement the JDBC code in Java program, typically we have 7 different steps, are listed below.
To write a simple JDBC program, we should follow these 7 different steps. Lets understand in detail for each
step.
The JDBC API is a set of classes and interface, to work with JDBC we must import java.sql package.
import java.sql.*;
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);
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");
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.
Execute Sql queries : Inorder to execute the SQL commands on database, Statement interface provides
provides three different methods:
When we want to run the non-select operations then we can choose executeUpdate()
When we want to run both select and non-select operations, then we can use execute()
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.
while(rs.next()){
System.out.println(rs.getInt(1));
}
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();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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.
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 −
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
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.
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.
The PreparedStatement interface extends the Statement interface, which gives you added functionality with a
couple of advantages over a generic Statement object.
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.
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.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
try {
if (pstatement != null) {
pstatement.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
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.
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 $$
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.
Parameter Description
A parameter whose value is unknown when the SQL statement is created. You
IN
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 −
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.
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.
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 −
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 −
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.
The cursor can scroll forward and backward, and the result
ResultSet.TYPE_SCROLL_SENSITIVE. set is sensitive to changes made by others to the database
that occur after the result set was created.
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.
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.
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
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.
package com.onlinetutorialspoint.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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.
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.
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;
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.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
conn.setAutoCommit(false);
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();
In this case, none of the above INSERT statement would success and everything would be rolled back.
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
}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
//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.
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;
// Create Savepoint
Savepoint savepoint = conn.setSavepoint();
// Rollback to savepoint
conn.rollback(savepoint);
// Commit statement
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output
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.
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 methods And to retrieve (ResultSet) Clob it provides methods
like: like:
getBlob() getClob()
getBinaryStream getCharacterStream()
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);
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( );
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.
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.
• 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 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.
HTTP
Description
Request
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
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 URL Post request is secured because data is not
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.
Servlet Container
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:
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.
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.
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
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.
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.
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
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.
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.
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.
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}
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
The basic concept behind session is, whenever a user starts using our application, we can save a
unique identification information about him, in an object which is available throughout the
application, until its destroyed. So wherever the user goes, we will always have his information and we
can always manage which user is doing what. Whenever a user wants to exit from your application,
destroy the object with his information.
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.
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.
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.
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 into
getSession(boolean create)
it
public String getId() Returns the unique session id
It returns the time when this session was created, measured in milliseconds
public long getCreationTime()
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"))
{
Jyoti Samel Page 54
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.
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.
Jyoti Samel Page 55
SYCS-SEMESTER IV-ADVANCED JAVA
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.
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.
Jyoti Samel Page 56
SYCS-SEMESTER IV-ADVANCED JAVA
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
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.
III. Destroy:
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.
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 −
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.
The request object provides methods to get the HTTP header information including form data, cookies, HTTP
methods etc.
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.
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.
Following table lists out the important methods that we will use to write boolean char, int, double, object,
String, etc.
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 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 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 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 −
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>
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);
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 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
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:
1. Page directive
2. Include directive
3. Taglib directive
<%@ page…%>
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
1. language: It defines the programming language (underlying language) being used in the page.
Syntax of language:
Example:
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:
Example:
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:
Example:
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".
Example:
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
Syntax of info:
Example:
In the above code, string "Guru Directive JSP" can be retrieved by the servlet interface using getServletInfo()
6. Session
When it is set to false, then we can indicate the compiler to not create the session by default.
Syntax of session:
Example:
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:
Syntax of isThreadSafe:
Here true or false represents if synchronization is there then set as true and set it as false.
Example:
isThreadSafe="true"%>
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:
Example:
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:
Syntax of buffer:
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
Example:
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:
Example:
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.
Syntax of pageEncoding:
Example:
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:
Example:
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:
Example:
In the above code, isELIgnored is true and hence Expression Language (EL) is ignored here.
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"( 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
<%@ include….%>
Example:
</head>
<body>
<a>Header file : </a>
<%int count =1; count++;
out.println(count);%> :
</body>
</html>
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:
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.
Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a tag name.
Example:
Code Line 3: Here "taglib" is defined with attributes uri and prefix.
Jyoti Samel Page 71
SYCS-SEMESTER IV-ADVANCED JAVA
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.
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 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:
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:
You can also use XML syntax of the JSP expression to achieve the same effect as the following example:
1 <jsp:expression>
2 Java Expression
3 </jsp:expression>
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:
In this example, we display a greeting message based on the current time of the day using the scriptlet.
<html>
<head>
<title>JSP syntax</title>
</head>
<body>
<%
// using scriptlet
Good <%=tod%>
</body>
</html>
<jsp:scriptlet>
// Java code of 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:
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;} %>
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.
File: printdate.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
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>
Jyoti Samel Page 76
SYCS-SEMESTER IV-ADVANCED JAVA
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.
</jsp:useBean>
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.
index.jsp file
<jsp:useBean id="obj" class="ABC"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
/>
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:plugin>
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.
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.
//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;}
}
To access the JavaBean class, we should use getter and setter methods.
package mypack;
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
Disadvantages of JavaBean
What is JSON?
JSON stands for JavaScript Object Notation
JSON is often used when data is sent from a server to a web page
JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
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.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
"firstName":"John"
JSON Objects
{"firstName":"John", "lastName":"Doe"}
JSON Arrays
JSON arrays are written inside square brackets.
"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).
Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<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:
1
Number
2
String
3
Boolean
true or false
4
Array
5
Value
6
Object
7
Whitespace
8
null
empty
Number
1
Integer
2
Fraction
3
Exponent
Syntax
var json-object-name = { string : number_value, .......}
Example
Example showing Number Datatype, value should not be quoted −
String
It is a sequence of zero or more double quoted Unicode characters with backslash escaping.
The table shows various special characters that you can use in strings of a JSON document −
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
9
u
Syntax
var json-object-name = { string : "string value", .......}
Example
Example showing String Datatype −
Boolean
Syntax
var json-object-name = { string : true/false, .......}
Example
var obj = {name: 'Amit', marks: 97, distinction: true}
Array
These are enclosed in square brackets which means that array begins with .[. and ends with .]..
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
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, .......}
{
"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
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 −
Syntax
String | Number | Object | Array | TRUE | FALSE | NULL
Example
var i = 1;
var j = "sachin";
var k = null;