CMP514 Advance Java R
CMP514 Advance Java R
Chavan Advance
Maharashtra Java
Open University
Advance JAVA
Production
INDEX
30 80
Unit 1 – JDBC
1.1 Learning Objectives
After completing this topic you will be able to create database connected Java
applications.
1.2 JDBC Introduction
UNIT 1 - JDBC
A database is an organized collection of related data. There are many different ways for organizing
data to make it easy to access and manipulate. A database management system(DBMS)
provides mechanisms for storing, organizing, retrieving and modifying data from any user.
Database management systems allow for the access and storage of data without concern for
the internal representation of data.
Today’s most popular database systems are relational databases.A language called SQL—is the
international standard query language used almost universally with relational databases to
perform queries and to manipulate data.
Some popular relational database management systems (RDBMSs) are Microsoft SQL Server,
Oracle, Sybase, MySQL,etc. The JDK now comes with a pure-Java RDBMS called Java DB—
Oracles’s version of Apache Derby.
Java programs communicate with databases and manipulate their data using the Java Database
Connectivity (JDBC) API.
A JDBC driver enables Java applications to connect to a database in a particular DBMS and allows
you to manipulate that database using the JDBC API.
JDBC Introduction
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database.
JDBC helps to write Java applications that manage these three programming activities:
JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC
architecture. It is quite small and simple.
JDBC Test Suite — The JDBC driver test suite helps you to determine that JDBC drivers will run your
program. These tests are not comprehensive or exhaustive, but they do exercise many of the
important features in the JDBC API.
JDBC-ODBC Bridge — The Java Software Bridge provides JDBC access via ODBC drivers. Note that
you need to load ODBC binary code onto each client machine that uses this driver. As a result,
the ODBC driver is most appropriate on a corporate network where client installations are not a
major problem, or for application server code written in Java in three-tier architecture.
fig.JDBC-to-database communication path
A type 2 driver is written partly in Java and partly in native code; it communicates with the
client API of a database. When you use such a driver, you must install some platform-specific
code in addition to a Java library.
A type 3 driver is a pure Java client library that uses a database-independent protocol to
communicate database requests to a server component, which then translates the requests
into a database-specific protocol. This can simplify deployment since the database-
dependent code is located only on the server.
A type 4 driver is a pure Java library that translates JDBC requests directly to a database-
specific protocol.
Most database vendors supply either a type 3 or type 4 driver with their database. Furthermore, a
number of third-party companies specialize in producing drivers with better standards
conformance, support for more platforms, better performance, or, in some cases, simply better
reliability than the drivers that are provided by the database vendors.
The traditional client/server model has a rich GUI on the client and a database on the server (figure
below). In this model, a JDBC driver is deployed on the client.
fig. Two-tier Architecture for Data Access.
However, the world is moving away from client/server and toward a "three-tier model" or even more
advanced "n-tier models." In the three-tier model, the client does not make database calls. Instead,
it calls on a middleware layer on the server that in turn makes the database queries. The three-tier
model has a couple of advantages. It separates visual presentation (on the client) from the business
logic (in the middle tier) and the raw data (in the database). Therefore, it becomes possible to
access the same data and the same business rules from multiple clients, such as a Java application or
applet or a web form.
Communication between the client and middle tier can occur through HTTP (when you use a web
browser as the client), RMI (when you use an application), or another mechanism. JDBC manages the
communication between the middle tier and the back-end database. Figure below shows the basic
three tier architecture.
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
Establishing a connection - An object that implements interface Connection manages the connection
between the Java program and the database. Connection objects enable programs to create SQL
statements that manipulate databases. The program initializes connection with the result of a call to
static method getConnection of class DriverManager (package java.sql), which attempts to connect
to the database specified by itsURL.
Method get-Connection takes three arguments—a String that specifies the database URL, a String that
specifies the username and a String that specifies the password.
e.g.
import java.sql.*;
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection conn = null;
conn = DriverManager.getConnection(“jdbc:odbc:mydata”,””,””);
// conn now has a live connection to the database
2. Create JDBC Statements
JDBC API provides 3 different interfaces to execute the different types of SQL queries.
They are:
1) Statement – Used to execute normal SQL queries. Parameters cannot be passed to SQL query at
runtime. This interface is preferred if you are executing a particular SQL query only once. Most of
the times it is used with DDL statements like CREATE,ALTER,DROP etc.
e.g.
e.g
//Executing PreparedStatement
pstmt.executeUpdate();
e.g
cstmt.execute();
//Use cstmt.getter() methods to retrieve the result returned by the stored procedur
Mapping types JDBC – Java
Retrieving and Modifying Values from Result Sets
A ResultSet object is a table of data representing a database result set, which is usually generated by
executing a statement that queries the database. A ResultSet object can be created through any
object that implements the Statement interface, including PreparedStatement, CallableStatement,
and RowSet.
You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor.
This cursor is a pointer that points to one row of data in the ResultSet. Initially, the cursor is
positioned before the first row. The method ResultSet.next() moves the cursor to the next row. This
method returns false if the cursor is positioned after the last row. This method repeatedly calls the
ResultSet.next method with a while loop to iterate through all the data in the ResultSet.
ResultSet Interface
The ResultSet interface provides methods for retrieving and manipulating the results of executed
queries, and ResultSet objects can have different functionality and characteristics. These
characteristics are type, concurrency, and cursor hold ability.
ResultSet Types
The type of a ResultSet object determines the level of its functionality in two areas: the ways in which
the cursor can be manipulated, and how concurrent changes made to the underlying data source
are reflected by the ResultSet object.
The sensitivity of a ResultSet object is determined by one of three different ResultSet types:
(a)TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor moves forward only, from before
the first row to after the last row. The rows contained in the result set depend on how the
underlying database generates the results. That is, it contains the rows that satisfy the query at
either the time the query is executed or as the rows are retrieved.
(b)TYPE_SCROLL_INSENSITIVE: The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position. The result set is
insensitive to changes made to the underlying data source while it is open. It contains the rows that
satisfy the query at either the time the query is executed or as the rows are retrieved.
(c)TYPE_SCROLL_SENSITIVE: The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position. The result set
reflects changes made to the underlying data source while the result set remains open.
Note: Not all databases and JDBC drivers support all ResultSet types. The method
DatabaseMetaData.supportsResultSetType returns true if the specified ResultSet type is supported
and false otherwise.
ResultSet Concurrency
The concurrency of a ResultSet object determines what level of update functionality is supported.
There are two concurrency levels:
CONCUR_READ_ONLY: The ResultSet object cannot be updated using the ResultSet interface.
CONCUR_UPDATABLE: The ResultSet object can be updated using the ResultSet interface.
Note: Not all JDBC drivers and databases support concurrency. The method
DatabaseMetaData.supportsResultSetConcurrency returns true if the specified concurrency level is
supported by the driver and false otherwise.
Cursor Holdability
Calling the method Connection.commit can close the ResultSet objects that have been created during
the current transaction. In some cases, however, this may not be the desired behavior. The
ResultSet property holdability gives the application control over whether ResultSet objects (cursors)
are closed when commit is called.
The following ResultSet constants may be supplied to the Connection methods createStatement,
prepareStatement, and prepareCall:
HOLD_CURSORS_OVER_COMMIT: ResultSet cursors are not closed; they are holdable: they are
held open when the method commit is called. Holdable cursors might be ideal if your application
uses mostly read-only ResultSet objects.
CLOSE_CURSORS_AT_COMMIT: ResultSet objects (cursors) are closed when the commit method
is called. Closing cursors when this method is called can result in better performance for some
applications.
// query database
resultSet = statement.executeQuery(
"SELECT AuthorID, FirstName, LastName FROM authors" );
// process query results
ResultSetMetaData metaData = resultSet.getMetaData(); int
numberOfColumns = metaData.getColumnCount();
System.out.println( "Authors Table of Books Database:\n"
);
while ( resultSet.next() )
{
int id = rs.getInt("AuthorID");
String firstName = rs.getString("FirstName");
String lastName = rs.getString("LastName");
System.out.println(id+ "\t" + firstName+
"\t" + lastName );
} // end
while } // end
try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
Cursors
As mentioned previously, you access the data in a ResultSet object through a cursor, which points to
one row in the ResultSet object. However, when a ResultSet object is first created, the cursor is
positioned before the first row.There are other methods available to move the cursor:
next: Moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false
if the cursor is positioned after the last row.
previous: Moves the cursor backward one row. Returns true if the cursor is now positioned on a
row and false if the cursor is positioned before the first row.
first: Moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now
positioned on the first row and false if the ResultSet object does not contain any rows.
last: Moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now
positioned on the last row and false if the ResultSet object does not contain any rows.
beforeFirst: Positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet
object does not contain any rows, this method has no effect.
afterLast: Positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet
object does not contain any rows, this method has no effect. relative(int rows): Moves the cursor
relative to its current position.
absolute(int row): Positions the cursor on the row specified by the parameter row.
Note that the default sensitivity of a ResultSet is TYPE_FORWARD_ONLY, which means that it cannot be
scrolled; you cannot call any of these methods that move the cursor, except next, if your ResultSet
cannot be scrolled.
try {
// establish connection to database
connection =
DriverManager.getConnection(
DATABASE_URL, "root", "" );
statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs= statement.executeQuery("SELECT * FROM authors");
while (uprs.next()) {
uprs.updateString( "LastName","Sharma");
uprs.updateRow();
}
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
The field ResultSet.TYPE_SCROLL_SENSITIVE creates a ResultSet object whose cursor can move both
forward and backward relative to the current position and to an absolute position. The field
ResultSet.CONCUR_UPDATABLE creates a ResultSet object that can be updated. See the ResultSet
Javadoc for other fields you can specify to modify the behavior of ResultSet objects.
The method ResultSet.updateString updates the specified column (in this example, LastName with the
specified float value in the row where the cursor is positioned. ResultSet contains various updater
methods that enable you to update column values of various data types. However, none of these
updater methods modifies the database; you must call the method ResultSet.updateRow to update
the database.
try {
statement =
connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
uprs.moveToInsertRow();
uprs.updateInt("AuthorID",9);
uprs.updateString("FirstName","Subash");
uprs.updateString("LastName","Pakhrin");
uprs.insertRow();
uprs.beforeFirst();
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
The same stipulations for using strings in getter methods also apply to updater methods.
The method ResultSet.moveToInsertRow moves the cursor to the insert row. The insert row is a special
row associated with an updatable result set. It is essentially a buffer where a new row can be
constructed by calling the updater methods prior to inserting the row into the result set. For
example, this method calls the method ResultSet.updateString to update the insert row's
COF_NAME column to Kona.
The method ResultSet.insertRow inserts the contents of the insert row into the ResultSet object and into
the database.
Note: After inserting a row with the ResultSet.insertRow, you should move the cursor to a row other
than the insert row. For example, this example moves it to before the first row in the result set with
the method ResultSet.beforeFirst. Unexpected results can occur if another part of your application
uses the same result set and the cursor is still pointing to the insert row.
The list, which is associated with a Statement object at its creation, is initially empty. You can add SQL
commands to this list with the method addBatch and empty it with the method clearBatch. When
you have finished adding statements to the list, call the method executeBatch to send them all to
the database to be executed as a unit, or batch.
try {
connection = DriverManager.getConnection(
DATABASE_URL, "root", "" );
connection.setAutoCommit(false);
statement = connection.createStatement();
statement.addBatch(
"INSERT INTO authors " +
"VALUES('15','Hari','Shrestha')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('16','Ram','Acharya')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('17','Shyam','Gautam')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('18','Govinda','Paudel')");
The following line disables auto-commit mode for the Connection object con so that the transaction will
not be automatically committed or rolled back when the method executeBatch is called.
connection.setAutoCommit(false);
To allow for correct error handling, you should always disable auto-commit mode before beginning a
batch update.
The method Statement.addBatch adds a command to the list of commands associated with the
Statement object statement. In this example, these commands are all INSERT INTO statements, each
one adding a row consisting of three column values.
The following line sends the four SQL commands that were added to its list of commands to the
database to be executed as a batch:
Note that statement uses the method executeBatch to send the batch of insertions, not the method
executeUpdate, which sends only one command and returns a single update count. The DBMS
executes the commands in the order in which they were added to the list of commands, so it will
first add the row of values for "Hari" , then add the row for "Ram", then "Shyam" , and finally
"Govinda". If all four commands execute successfully, the DBMS will return an update count for each
command in the order in which it was executed. The update counts that indicate how many rows
were affected by each command are stored in the array updateCounts.
If all four of the commands in the batch are executed successfully, updateCounts will contain four
values, all of which are 1 because an insertion affects one row. The list of commands associated
with stmt will now be empty because the four commands added previously were sent to the
database when stmt called the method executeBatch. You can at any time explicitly empty this list
of commands with the method clearBatch.
The Connection.commit method makes the batch of updates to the "authors" table permanent. This
method needs to be called explicitly because the auto-commit mode for this connection was
disabled previously.
The following line enables auto-commit mode for the current Connection object.
connection.setAutoCommit(true);
Now each statement in the example will automatically be committed after it is executed, and it no
longer needs to invoke the method commit.
Transaction Processing
Many database applications require guarantees that a series of database insertions, updates and
deletions executes properly before the application continues processing the next database
operation. For example, when you transfer money electronically between bank accounts, several
factors determine if the transaction is successful. You begin by specifying the source account and
the amount you wish to transfer from that account to a destination account. Next, you specify the
destination account. The bank checks the source account to determine whether its funds are
sufficient to complete the transfer. If so, the bank withdraws the specified amount and, if all goes
well, deposits it into the destination account to complete the transfer. What happens if the transfer
fails after the bank withdraws the money from the source account? In a proper banking system, the
bank redeposits the money in the source account.The way to be sure that either both actions occur
or neither action occurs is to use a transaction. A transaction is a set of one or more statements
that is executed as a unit, so either all of the statements are executed, or none of the statements
is executed.
The way to allow two or more statements to be grouped into a transaction is to disable the auto-
commit mode.
Disabling Auto-Commit Mode
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement
is treated as a transaction and is automatically committed right after it is executed.
The way to allow two or more statements to be grouped into a transaction is to disable the auto-
commit mode.
con.setAutoCommit(false);
Committing Transactions
After the auto-commit mode is disabled, no SQL statements are committed until you call the method
commit explicitly. All statements executed after the previous call to the method commit are
included in the current transaction and committed together as a unit. con.commit();
Rollback
If you group update statements to a transaction, then the transaction either succeeds in its entirety and
it can be committed, or it fails somewhere in the middle. In that case, you can carry out a rollback
and the database automatically undoes the effect of all updates that occurred since the last
committed transaction.
RowSet Interface
A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use than a
result set.The RowSet interface configures the database connection and prepares query statements
automatically.It provides several set methods that allow you to specify the properties needed to
establish a connection (such as the database URL, user name and password of the database) and
create a Statement (such as a query). RowSet also provides several get methods that return these
properties.
Connected and Disconnected RowSets
There are two types of RowSet objects—connected and disconnected. A connected RowSet object
connects to the database once and remains connected while the object is in use. A disconnected
RowSet object connects to the database, executes a query to retrieve the data from the database
and then closes the connection. A program may change the data in a disconnected RowSet while it’s
disconnected. Modified data can be updated in the database
after a disconnected RowSet reestablishes the connection with the database.
JdbcRowSet
Navigating JdbcRowSet Objects
JdbcRowSet jdbcRs = new JdbcRowSetImpl();
jdbcRs.absolute(4);
jdbcRs.previous();
jdbcRs.absolute(3);
jdbcRs.updateString("lastName", "Sharma");
jdbcRs.updateRow();
Inserting Rows
jdbcRs.moveToInsertRow();
jdbcRs.updateInt("Author_ID", 10);
jdbcRs.updateString("FirstName", "Navin");
jdbcRs.updateString("LastName", "Sharma");
jdbcRs.insertRow();
Deleting Rows
jdbcRs.last();
jdbcRs.deleteRow();
References:
https://docs.oracle.com
https://www.javatpoint.com
UNIT 2 SERVLETS
2.0 Introduction
2.1 Objective
2.2 What is a Java Servlet?
2.3 Servlet API
2.4 Servlet Life-cycle
2.5 Working with Apache Tomcat
2.6 GenericServlets
2.7 HttpServlet
2.8 HttpSession
2.9 Session Binding/Tracking
2.10 Inter-Servlet Communication.
2.11 Summary
2.12 Important Questions
2.0 INTRODUCTION
__________________________________________________________________
Till now we have learned how to connect a Java Application to a Database. In this Unit we will
learn a Server side technology known as Servlet that extends the capability of a Web server.
2.1 OBJECTIVE
Servlets are Java programs that can be run dynamically from a Web Server. They are a Server
side technology.A Servlet is an intermediating layer between an HTTP request of a client and the
Web server.
For example, a Servlet might be responsible for taking data in an HTML order-entry form and
applying the business logic used to update a company's order database
Figure 2.1
The Servlet API is made up of two packages. These packages contains the classes and interfaces
required to build servlets.They are javax.servlet and javax.servlet.http. These packages are not
part of the Java core packages. Instead, they are standard extensions. Therefore, they are not
included in the Java Software Development Kit. You must download Tomcat or Glass Fish
server to obtain their functionality.
The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
The following table lists the core interfaces that are provided in this package. The most
important is Servlet. All servlets you create must implement this interface or extend to a class
that implements this interface.
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access information about
their environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
SingleThreadModel Indicates that the servlet is thread safe.
The following table summarizes the core classes that are provided in the javax.servlet package.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable.
The Servlet Interface
All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy(
) methods that are called by the server during the life cycle of a servlet. The methods defined by
Servlet are shown below:
Method Summary
void destroy()
Called by the servlet container to indicate to a servlet that the servlet is
being taken out of service.
ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup
parameters for this servlet.
java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and
copyright.
void init(ServletConfig config)
Called by the servlet container to indicate to a servlet that the servlet is
being placed into service.
void service(ServletRequest req, ServletResponse res)
Called by the servlet container to allow the servlet to respond to a
request.
Table 2.1
Table 2.3
____________________________________________________________________________
Figure 2.2
The steps of the life cycle of the servlet are:
1. The server loads the Servlet class and initializes one instance of it
2. Servlet instance is created. Each client request is handled by the Serlvet instance in a separate
thread
3. init() method is invoked.
4. service() method is invoked.
5. destroy () method is invoked.
<servlet>
<servlet-name>ServletName</servlet-name>
<servlet-class>ServletClassFile</servlet-class>
<init-param>
<param-name>initParam1</param-name>
<param-value>initParam1Value</param-value>
</init-param>
<init-param>
<param-name>initParam2</param-name>
<param-value>initParam2Value</param-value>
</init-param>
</servlet>
The ServletConfig interface defines these methods to retrieve the initialization parameters for
this servlet.
Apache Tomcat is a Java-capable HTTP server, which can execute special Java web programs
known as "Java Servlets" and "Java Server Pages (JSP)". Tomcat is an open-source project,
under the "Apache Software Foundation" The mother site for Tomcat is http://tomcat.apache.org.
Tomcat was originally written by James Duncan Davison (then working in Sun) in 1998, based
on an earlier Sun's server called Java Web Server (JWS). Sun subsequently made Tomcat open-
source and gave it to Apache.
Tomcat Server is a container for Java Servlets. To run a Servlet the Apache Tomcat web server
has to be downloaded from http://tomcat.apache.org.
2. Right click on Computer from properties select advance tab and select environment variable.
e.g:
C:\ mywebproject\tomcat \webapps\examples\WEB-INF\classes>javac Login.java
11. Make changes to web.config file which is in the following path of Tomcat
C:\ mywebproject\tomcat \webapps\examples\WEB-INF
12. e.g
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlets/servlet/Login</url-pattern>
</servlet-mapping>
13. Start Tomcat server by selecting startup.exe from the following path
C:\mywebproject\ tomcat\bin
Generic Servlets make writing a Servlet easier. Simple versions of the init and destroy are
provided, it also provides simple version ServletConfig interface methods. A log method, from
the ServletContext interface is also provided. The written servlet should override only the service
abstract method.
The following diagram shows the hierarchy of the Servlet interface and classes.
Figure 2.3
<html>
<title>Generic Servlet Demo</title>
</head>
<body>
<a href="welcome">Click here for call to Generic Servlet</a>
</body>
</html>
import java.io.*;
import javax.servlet.*;
2.7 HttpServlets
________________________________________________________________________
As shown in Figure 2.2 the HttpServlet class extends the GenericServlet class. It is an http
protocol based servlet which implements the Serializable interface. It provides http specific
methods such as doGet, doPost, doHead, doTrace etc.
To write the HttpServlet we have to override either the doGet or doPost method. The doGet
method is overridden if the Servlet supports the HTTP Get request and doPost for HTTP POST
request.
In the following example we see how to create and invoke an HttpServlet.
We have to create 3 files :
1. HTML file
First we create an HTML file that will call the servlet once we click on the link on the web page.
<html>
<title>Http Servlet Demo</title>
</head>
<body>
<a href="welcome">Click here for calling Http Servlet</a>
</body>
</html>
import java.io.*;
import javax.servlet.*;
Session in Servlets
The interactive time between client and server on a single connection is known as a session or
the period of time between connection establishment and connection closing between client and
server is known as a session. A Session begins when the client logs in to a Web site and ends
when the user logs out.
A connection is well maintained by the Servlet container while the client and server are
conversing back and forth in a session.
HttpSession
The HttpSession object is used for session management. A session contains information specific
to a particular user across the whole application. When a user enters into a website (or an online
application) for the first time HttpSession is obtained via request.getSession(), the user is given a
unique ID to identify his session. This unique ID can be stored into a cookie or in a request
parameter.
The HttpSession stays alive until it has not been used for more than the timeout value specified
in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is
used if you don‘t specify the value in tag. This means that when the user doesn‘t visit web
application time specified, the session is destroyed by servlet container. The subsequent request
will not be served from this session anymore; the servlet container will create a new session.
HttpSession methods
public void setAttribute(String name, Object value): This method binds the object with a
name and stores the name/value pair as an attribute of the HttpSession object. If an attribute
already exists, then this method replaces the existing attributes.
public Object getAttribute(String name): This method returns the String object specified in
the parameter, from the session object. If no object is found for the specified attribute, then the
getAttribute() method returns null.
public void removeAttribute(String name): This method removes the given attribute from
session.
setMaxInactiveInterval(int interval): This method sets the session inactivity time in seconds.
This is the time in seconds that specifies how long a sessions remains active since last request
received from client.
2.9 Session Binding/Tracking
____________________________________________________________________________
A session can temporarily store information related to the activities of the user while logged in.
A servlet should be capable to store temporary information pertaining to the activities of the user
in a session.
Session Example
index.html
<form action="login">
User Name:<input type="text" name="userNm"/><br/>
Password:<input type="password" name="userPsw"/><br/>
<input type="submit" value="Submit"/>
</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
web.xml
<web-app>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
______________________________________________________________________________
2.10 Inter Servlet Communication
________________
__________________________________
The communication between the servlets of a web application is known as Inter Servlet
Communication. The uses of Inter Servlet communication are direct servlet manipulation,
reusing servlets and servlet collaboration. There are various ways through which servlets
communicate with each other; we are going to discuss Request Dispatcher method and Redirect
methods.
Request Dispatcher:
An object of the javax.servlet.RequestDispatcher interface that allows inter-servlet
communication.
Object is used to include or forward the content of another servlet.
To get RequestDispatcher Object:
Examples:
RequestDispatcher rd;
rd = request.getRequestDispatcher("xyz.jsp?user=fred");
rd.include(request, response);
Or
RequestDispatcher dispatcher = req.getRequestDispatcher("/index.html");
dispatcher.forward(req, res);
Inter-servlet communication using Send Redirect
Send Redirect can be used to communicate between two servlet present in different servers, the
output will be same as request dispatcher forward example but the url of the page will be
changed to redirected page
Example:
response.sendRedirect
("http://localhost:9999/Test/ServletTwo");
________________
2.11 Summary
In this Unit what is a Servlet was explained. The different types of Servlets, the Servlet APIs
were discussed. How to create a Generic and Http servlet was explained with example. What is
session, session management was explained. The topic inter servlet communication was also
discussed.
1. What is a servlet?
2. Can we use the constructor, instead of Init(), to initialize Servlet?
3. What is Servlet Context?
4. What Is A Servlet Filter? Explain life cycle.
5. What Is A War File? Describe the structure in brief.
6. What Is Genericservlet Class?
7. How Can The Session In Servlet Be Destroyed?
8. What Are The Mechanisms Used By A Servlet Container For Maintaining Session
Information?
9. What Is The Procedure For Initializing A Servlet?
10. What Is The Web Container?
11. What Are The Uses Of Servletrequest?
12. What Are The Uses Of Servletresponse Interface?
13. How Http Servlet Handles Client Requests?
14. What Is Pre Initialization Of A Servlet?
15. How Do You Communicate Between The Servlets?
16. What Are The Differences Between A Session And A Cookie?
17. Why Should We Go For Inter Servlet Communication?
18. What's The Servlet Interface?
19. What Is The Difference Between Servletcontext And Servletconfig?
20. What is different between web server and application server?
21. What is the difference between GET and POST method?
22. What is MIME Type?
23. What is a web application and what is it‘s directory structure?
24. What are common tasks performed by Servlet Container?
25. What is ServletConfig object?
26. What is difference between GenericServlet and HttpServlet?
27. What is servlet attributes and their scope?
28. How can we invoke another servlet in a different application?
29. What are the phases of servlet life cycle?
30. What are life cycle methods of a servlet?
References:
1. beginnersbook.com
2. javabeat.com
3. javatutorialpoint.com
UNIT 3 JSP
3.0 Introduction
3.1 Objective
3.2 What is JSP?
3.3 JSP Syntax
3.4 Page Directives
3.5 Include Directives
3.6 Data Declaration
3.7 Method Definition
3.8 Scriplets
3.9 Implicit Objects
3.10 Custom Tags
3.11 Session Tracking in JSP
3.12 Page Context
3.13 Exceptions
3.14 Summary
3.15 Important Questions
3.0 INTRODUCTION
__________________________________________________________________
In the previous chapter, we learned how to generate dynamic Web pages with servlets.
In the Servlet examples most of the code generated output consisted of the HTML elements.
Only a small part of the code dealt with the business logic. Servlet writers have to be Java
programmers. However, Web application developers and Web site designers, may not know
Java. It is difficult for people who are not Java programmers to implement, maintain and extend
a Web application that consists of primarily of servlets. The answer to this problem is Java
Server Pages (JSP) an extension of servlet technology that separates the presentation from the
business logic.
_____________________________________________________________________________________
3.1 OBJECTIVE
_____________________________________________________________________________________
Java Server Pages or JSP simplify dynamic Web content delivery. They enable Web application
programmers to create dynamic content by reusing predefined components and by interacting
with components using server-side scripting. JSP contain Custom-tag libraries that allows Java
developers to hide complex code for database access and other useful services for dynamic Web
pages.
The classes and interfaces that are specific to JavaServer Pages programming are located in
various packages.packages.
JavaServer Page (JSP) like Microsoft's Active Server Pages (ASP) allows you to
mix static HTML with dynamically generated HTML - in the way that the business logic and
the presentation are well separated.
The advantages of JSP are:
1. Separation of static and dynamic contents: JSP enables the separation
of static contents from dynamic contents. The dynamic contents are generated via
programming logic and inserted into the static template. This greatly simplifies the
creation and maintenance of web contents.
2. Reuse of components and tag libraries: The dynamic contents can be provided by
reusable components such as JavaBean, Enterprise JavaBean (EJB) and tag libraries.
3. Java's power and portability
There are four key components to JSP page -directives, actions, scripting elements and tag
libraries. Directives are messages to the JSP container-the server component that executes JSPs-
that enable the programmer to specify page settings, to include content from other resources and
to specify custom tag libraries for use in a JSP. Actions encapsulate functionality in predefined
tags that programmers can embed in a JSP. Actions often are performed based on the information
sent to the server as part of a particular client request. They also can create Java objects for use in
JSP scriptlets. Scripting elements enable programmers to insert Java code that interacts with
components in a JSP (and possibly other Web application components) to perform request
processing. Scriptlets, one kind of scripting element, contain code fragments that describe the
action to be performed in response to a user request. Tag libraries are part of the tag extension
mechanism that enables programmers to create custom tags. Such tags enable Web page
designers to manipulate JSP content without prior Java knowledge.
In some ways, JavaServer Pages look like standard XHTML or XML documents. In fact, JSPs
normally include XHTML or XML markup. Such markup is known as fixed-template data or
fixed-template text. Fixed-template data often helps a programmer decide whether to use a
servlet or a JSP. Programmers tend to use JSPs when most of the content sent to the client is
fixed-template data and little or none of the content is generated dynamically with Java code.
Programmers typically use servlets when only a small portion of the content sent to the client is
fixed-template data. In fact, some servlets do not produce content. Rather, they perform a task on
behalf of the client, then invoke other servlets or JSPs to provide a response. Note that in most
cases servlet and JSP technologies are interchangeable. As with servlets, JSPs normally execute
as part of a Web server.
When a JSP-enabled server receives the first request for a JSP, the JSP container translates the
JSP into a Java servlet that handles the current request and future requests to the JSP. Literal text
in a JSP becomes string literals in the servlet that represents the translated JSP. Any errors that
occur in compiling the new servlet result in translation-time errors. The JSP container places the
Java statements that implement the JSP's response in method _jspService at translation time. If
the new servlet compiles properly, the JSP container invokes method _jspService to process the
request. The JSP may respond directly or may invoke other Web application components to
assist in processing the request. Any errors that occur during request processing are known as
request-time errors.
Overall, the request-response mechanism and the JSP life cycle are the same as those of a servlet.
JSPs can override methods jspInit and jspDestroy (similar to servlet methods init and destroy),
which the JSP container invokes when initializing and terminating a JSP, respectively. JSP
programmers can define these methods using JSP declarations--part of the JSP scripting
mechanism.
A Simple JSP Example
JSP expression inserting the date and time into a Web page.
//test.jsp
<html>
<head>
<meta http-equiv = "refresh" content = "60" />
<title>A Simple JSP Example</title>
<style type = "text/css">
.big { font-family: helvetica, arial, sans-serif;
font-weight: bold;
font-size: 2em; }
</style>
</head>
<body>
<p class = "big">Simple JSP Example</p>
<table style = "border: 6px outset;">
<tr>
<td style = "background-color: black;">
<p class = "big" style = "color: cyan;">
<!-- JSP expression to insert date/time -->
<%= new java.util.Date() %>
</p>
</td>
</tr>
</table>
</body
</html>
As you can see, most of test.jsp consists of XHTML markup.In cases like this, JSPs are easier to
implement than servlets. In a servlet that performs the same task as this JSP, each line of
XHTML markup typically is a separate Java statement that outputs the string representing the
markup as part of the response to the client. Writing code to output markup can often lead to
errors.That's why in such scenarios JSP is preferred than Servlets.The key line in the above
program is the expression
JSP expressions are delimited by <%= and %>. The preceding expression creates a new
instance of class Date (package java.util). By default, a Date object is initialized with the current
date and time. When the client requests this JSP, the preceding expression inserts the String
representation of the date and time in the response to the client. [Note: Because the client of a
JSP could be anywhere in the world, the JSP should return the date in the client locale's
format. However, the JSP executes on the server, so the server's locale determines the String
representation of the Date.
We use the XHTML meta element in line 9 to set a refresh interval of 60 seconds for the
document. This causes the browser to request test.jsp every 60 seconds. For each request to
test.jsp, the JSP container reevaluates the expression in line 24, creating a new Date object with
the server's current date and time.
When you first invoke the JSP, you may notice a brief delay as GlassFish Server translates the
JSP into a servlet and invokes the servlet to respond to your request
A page directive 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 also used to provide instructions to a container that pertains to current JSP page.
Syntax of Page Directive:
Example:
In the above example the attribute language defines the programming language used in the page,
contentType defines the character coding scheme, charset defines the character set used,
import indicates the classes which have been imported, pageEncoding defines the character
encoding for JSP page.
1. Besides these there are many other attributes like session, extends, info, autoflush,
isErrorPage etc.
An include directive instructs the JSP container to include an external file in the JSP page.This
directive can be used anywhere in the JSP page.
General Syntax:
<%@ include file = "relative url" >
XML syntax:
<jsp:directive.include file = "relative url" />
Example:
<%@ include file = "first.jspl" >
3.6 Data Declaration
______________________________________________________________________________
A declaration statement declares variables or methods that you will use in Java code inyour JSP
page. It is compulsory to declare all the variables and methods before its use.
<jsp:declaration>
Java code fragment
</jsp:declaration>
Example:
Syntax;
<%!
access_specifier returndatatype function_name(list of arguments)
{
java code fragment
return expression
}
%>
The following example shows a method square which returns the square of the number passed to
it.
<%!
public int square(int num)
{
return num*num;
}
%>
____________________________________________________________________________________
3.8 Scriplets
______________________________________________________________________________
JavaServer Pages often present dynamically generated content as part of an XHTML document
that is sent to the client in response to a request.
JSP programmers can insert Java code and logic in a JSP using scripting.
Scripting Components
The JSP scripting components include scriptlets, comments, expressions, declarations and
escape sequences.
Scriptlets are blocks of code delimited by <% and %>. They contain Java statements that the
container places in method _jspService at translation time.
JSPs support three comment styles: JSP comments, XHTML comments and scripting-
language comments. JSP comments are delimited by <%-- and --%>. These can be placed
throughout a JSP, but not inside scriptlets.
XHTML comments are delimited with <!-- and -->. These, too, can be placed throughout a JSP,
but not inside scriptlets.
Scripting language comments are currently Java comments, because Java currently is the only
JSP scripting language.
Scriptlets can use Java's end-of-line // comments and traditional comments (delimited by /* and
*/).
JSP comments and scripting-language comments are ignored and do not appear in the response
to a client. When clients view the source code of a JSP response, they will see only the XHTML
comments in the source code.
JSP expressions are delimited by <%= and %> and contain a Java expression that is evaluated
when a client requests the JSP containing the expression. The container converts the result of a
JSP expression to a String object, then outputs the String as part of the response to the client.
As already discussed Declarations are delimited by <%! and %>, enable a JSP programmer to
define variables and methods for use in a JSP. Variables become instance variables of the servlet
class that represents the translated JSP. Similarly, methods become members of the class that
represents the translated JSP. Declarations of variables and methods in a JSP use Java syntax.
Thus, a variable declaration must end with a semicolon, as in
Special characters or character sequences that the JSP container normally uses to delimit JSP
code can be included in a JSP as literal characters in scripting elements, fixed template data and
attribute values using escape sequences. The escape sequences used are:
Figure 2.1
Scriplet Example
//welcome.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-
8"> <title>Processing "get" requests with data</title>
</head>
<!-- body section of document -->
<body>
<% // begin scriptlet
String name = request.getParameter( "firstName" );
if ( name != null )
{
%> <%-- end scriptlet to insert fixed template data --%>
<h1>
Hello <%= name %>, <br />
Welcome to JavaServer Pages!
</h1>
} // end if
else {
} // end else
Implicit objects provide access to many servlet capabilities in the context of a JavaServer
Page. Implicit objects have four scopes: application, page, request and session. The JSP
container owns objects with application scope. Any JSP can manipulate such objects. Objects
with page scope exist only in the page that defines them. Each page has its own instances of
the page-scope implicit objects. Objects with request scope exist for the duration of the
request. For example, a JSP can partially process a request, and then forward it to a servlet or
another JSP for further processing. Request-scope objects go out of scope when request
processing completes with a response to the client. Objects with session scope exist for the
client's entire browsing session. The following list describes the JSP implicit objects and their
scopes.
3.10 Custom Tags
___________________________________________________________________________
___
2) TLD file: Tag descriptor file where we will specify our tag name, tag handler class and tag
attributes.
3) JSP page: A JSP page where we will be using our custom tag.
Example:
In the below example we are creating a custom tag MyTag which will display the message
―This is a custom tag‖ when used in a JSP page.
A tag handler class should implement Tag/IterationTag/ BodyTag interface or it can also
extend TagSupport/BodyTagSupport/SimpleTagSupport class. All the classes that support
custom tags are present inside javax.servlet.jsp.tagext. In the below we are extending the
class SimpleTagSupport.
Details.java
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class Details extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
TLD File
This file should present at the location: Project Name/WebContent/WEB-INF/ and it should
have a .tld extension.
Note:
<name> tag: custom tag name. In this example we have given it as MyTag
<tag-class> tag: Fully qualified class name. The package in which the tag handler
class Details.java is present has to be written .
message.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My Custom Tag</short-name>
<tag>
<name>MyMsg</name>
<tag-class>mypackage.Details</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Sessions are mechanism for storing client data across multiple HTTP requests. From one
request to another user the HTTP server does not maintain a reference or keep any record of
client previous request.
HttpSession Methods
getAttribute : it returns stored value from session object. It returns null if no value is
associated with name.
setAttribute : It associates a value with name.
removeAttribute : It removes all the values associated with name.
getAttributeNames : It returns all attributes names in the session.
getId : it returns unique id in the session.
isNew : It determine if session is new to client.
getcreationTime : It returns time at which session was created.
getlastAccessedTime : It returns time at which session was accessed last by client.
getMaxInactiveInterval : It gets maximum amount of time session in seconds that
access session before being invalidated.
setMaxInaxctiveInterval : It sets maximum amount of time session in seconds
between client requests before session being invalidated.
Following ways are used to maintain session between client and web server:
Cookies
A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of
data sent from a website and stored in a user‘s web browser while the user is browsing that
website.
A cookie‘s value can uniquely identify a client, so cookies are commonly used for session
management. Browser stores each message in a small file, called cookie.txt. When you
request another page from the server, your browser sends the cookie back to the server.
Cookies have lifespan and are flushed by the client browser at the end of lifespan.
It is hidden (invisible) text field used for maintaining the state of user. We store the
information in the hidden field and get it from another servlet.
Following shows how to store value in hidden field.
URL Rewriting
A static HTML page or form must be dynamically generated to encode every URL. If you
cannot verify that every user of web application uses cookies, then you must consider web
container need to use URL-rewriting. If the browser does not support cookies, or if cookies
are disabled, you can still enable session tracking using URL rewriting.
A web container attempts to use cookies to store the session ID. If that fails then web
container tries to use URL-rewriting. URL rewriting essentially includes the session ID
within the link itself as a name/value.
Adding the session ID to a link contain following methods:
JSP Page Context Object is used to store and retrieve the page-related information and
sharing objects. PageContext is an instance of javax.servlet.jsp.PageContext. PageContext is
used to findAttribute, setAttribute, getAttribute and removeAttribute and it
has the following scope.
Page_Context scope
Request_Context scope
Session_Context scope
Application_Context scope
findAttribute(String AttributeName): This method is used to search the attributes like the
page, session, request, application. Return type is an object. If there is no attribute it returns
null.
Syntax
pageContext.findAttribute(―name of attribute‖);
getAttribute(String AttributeName, int scope):This method is used to get the attribute with
specified scope. This is same as findAttribute() method but getAttribute look for specific
scope. It returns the object, if there is no attribute, it returns null.
Syntax
Object object = pageContext.getAttribute(―Attribute
name‖, PageContext.SESSION_CONTEXT);
Syntax
pageContext.removeAttribute(―Attribute Name‖,PageContext.REQUEST_CONTEXT);
Syntax
pageContext.setAttribute(―AttributeName‖,‖AttributeValue‖,
PageContext. APPLICATION_CONTEXT);
Example of JSP Page Context Object.
pagecontext.html
<html>
<body>
<form action="pageContext.jsp">
Name: <input type="text" name="Name"/></br>
FullName:<input type="text" name="fullName"/></br></br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
Here the developer just created two text boxes such as Name and fullName and also created
submit button.
pageContext.jsp
<html>
<body>
<form action="getPageContext.jsp">
<%
String Name = request.getParameter("Name");
String fullName = request.getParameter("fullName");
out.println("Hello "+ Name+" ");
pageContext.setAttribute("Name", Name, PageContext.SESSION_SCOPE);
pageContext.setAttribute("fullName", fullName, PageContext.SESSION_SCOPE);
%>
<input type="submit" value="Click Here"/>
</form>
</body>
</html>
request.getParameter() method is used to retrieve the details which are placed in HTML
page. pageContext.setAttribute() method is used to set the name of the attribute, attribute
value and scope of that object. This method has no return type.
getPageContext.jsp
<html>
<body>
<%
String Name = (String) pageContext.getAttribute("Name", PageContext.SESSION_SCOPE);
String fullName = (String) pageContext.getAttribute("fullName", PageContext.SESSION_SCOPE);
out.println("Hi "+ Name+" ");
out.println("This is your fullname :"+fullName);
%>
</body>
</html>
getAttribute(String AttributeName, int scope) method is used to get the attribute with
specified scope.
3.13 Exceptions
___________________________________________________________________________
___
The exception is normally an object that is thrown at runtime. Exception Handling is the
process to handle the runtime errors. There may occur exception any time in your web
application. So handling exceptions is a safer side for the web developer. In JSP, there are
two ways to perform exception handling:
1. By errorPage and isErrorPage attributes of page directive
2. By <error-page> element in web.xml file
index.jsp
<form action="arithmetic.jsp">
Enter first Number : <input type="text" name="num1" /><br/><br/>
Enter second Number : <input type="text" name="num2" /><br/><br/>
<input type="submit" value="Divide"/>
</form>
arithmetic.jsp
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
This approach is better because you don't need to specify the errorPage attribute in each jsp
page. Specifying the single entry in the web.xml file will handle the exception. In this case,
either specify exception-type or error-code with the location element. If you want to handle
all the exception, you will have to specify the java.lang.Exception in the exception-type
element. Let's see the simple example:
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
This approach is better if you want to handle any exception. If you know any specific error
code and you want to handle that exception, specify the error-code element instead of
exception-type as given below:
1) web.xml file if you want to handle the exception for a specific error code
<web-app>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
2) index.jsp file is same as in the above example
3) arithmetic.jsp
Now, you don't need to specify the errorPage attribute of page directive in the jsp page.
<%@ page errorPage="error.jsp" %>
<%
String n1=request.getParameter("num1");
String n2=request.getParameter("num2");
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
4) error.jsp file is same as in the above example
3.14 Summary
________________________________________________________________
__
In this Unit we learned how to create a JSP page. The syntax of JSP both general and XML
equivalent.
The different types of directives- Page directive and Include directive.
How data is declared and methods are defined. What is meant by JSP Scriplet?
Making a custom tag with example. Session Tracking methods of JSP. We also learned
Exception handling with example.
Hibernate (framework)
What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for
converting data between relational databases and object oriented programming languages
such as Java, C#, etc.
An ORM system has the following advantages over plain JDBC –
1. Lets the business logic code access objects rather than DB tables.
2. Hides details of SQL queries from OO logic.
3. No need to deal with the database implementation.
4. Entities based on business concepts rather than database structure.
5. Transaction management and automatic key generation.
An ORM solution consists of the following advantages :–
• Transparent Persistence (POJO/JavaBeans)
• Persistent/transient instances
• Automatic Dirty Checking
• Transitive Persistence
• Lazy Fetching
• Outer Join Fetching
• Runtime SQL Generation
• Three Basic Inheritance Mapping Strategies
Hibernate is a great tool for ORM mappings in Java. It can cut down a lot of complexity and
is specially a boon for Java developers with limited knowledge of SQL.
Hibernate Architecture
The following diagram shows the main building blocks in hibernate architecture.
Explanation of each block:
}
2. Create Database Tables
Second step would be creating tables in your database. There would be one table
corresponding to each object, to provide persistence. Consider above objects need to be
stored and retrieved into the following RDBMS table –
You should save the mapping document in a file with the format <classname>.hbm.xml.
example Employee.hbm.xml. Let us see little detail about the mapping document −
The mapping document is an XML document having <hibernate-mapping> as the root
element which contains all the <class> elements.
The <class> elements are used to define specific mappings from a Java classes to the
database tables. TheJava class name is specified using the name attribute of the class
element and the database table name isspecified using the table attribute.
The <meta> element is optional element and can be used to create the class
description.
The <id> element maps the unique ID attribute in class to the primary key of the
database table. The name attribute of the id element refers to the property in the class
and the column attribute refers to the column in the database table. The type attribute
holds the hibernate mapping type, this mapping types will convert from Java to SQL
data type.
The <generator> element within the id element is used to generate the primary key
values automatically. The class attribute of the generator element is set to native to let
hibernate pick up either identity, sequence or hilo algorithm to create primary key
depending upon the capabilities of the underlying database.
The <property> element is used to map a Java class property to a column in the
database table. The name attribute of the element refers to the property in the class
and the column attribute refers to the column in the database table. The type attribute
holds the hibernate mapping type, this mapping types will convert from Java to SQL
data type.
Transient Object
Transient objects exist in heap memory. Hibernate does not manage transient objects or
persist changes to transient objects.
Detached objects exist in the database but are not maintained by Hibernate
A detached object can be created by closing the session that it was associated with, or by
evicting it from the session with a call to the session‘s evict() method.
One reason you might consider doing this would be to read an object out of the database,
modify the properties of the object in memory, and then store the results some place other
than your database. This would be an alternative to doing a deep copy of the object.
In order to persist changes made to a detached object, the application must reattach it to a
valid Hibernate session. A detached instance can be associated with a new Hibernate session
when your application calls one of the load, refresh, merge, update(), or save() methods on
the new session with a reference to the detached object. After the call, the detached object
would be a persistent object managed by the new Hibernate session.
Removed Object
Removed objects are objects that are being managed by Hibernate (persistent objects, in other
words) that have been passed to the session‘s remove() method. When the application marks
the changes held in the session as to be committed, the entries in the database that correspond
to removed objects are deleted.
Now let‘s not note down the take-aways from this tutorial.
Bullet Points
1. Newly created POJO object will be in the transient state. Transient object doesn‘t
represent any row of the database i.e. not associated with any session object. It‘s plain
simple java object.
2. Persistent object represent one row of the database and always associated with some
unique hibernate session. Changes to persistent objects are tracked by hibernate and
are saved into database when commit call happen.
3. Detached objects are those who were once persistent in past, and now they are no
longer persistent. To persist changes done in detached objects, you must reattach them
to hibernate session.
4. Removed objects are persistent objects that have been passed to the session‘s
remove() method and soon will be deleted as soon as changes held in the session will
be committed to database.
Introduction
Hibernate Servlet Integration, Developing an application using hibernate is a very simple task if
developer has knowledge in flow of code why because every hibernate application will have two
minimum files they are configuration file and hibernate mapping file, remaining files are
regarding required java files , as earlier discussed the main advantage of hibernate is tables will
be created automatically after the execution of a program.Here input values are sent from
the Html page to Servlet which calls Dao class of Hibernate and it will pass input values
to Database.
Example
If an example is taken such that, employee details are given to Html page, it will store the details
in the Database.If details are saved into Database, then Servlet gives the response as ‗Employee
details successfully saved’. If not the response will be ‘Employee details already saved’.
Conceptual figure
Execution flows diagram of servlet-hibernate example.
Add all the hibernate jar files, ojdbc14.jar and servlet-api.jar in lib folder.
Example
</form>
</body>
</html>
ServletDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iquickinfo.Dao;
int employeeId=Integer.parseInt(request.getParameter("id").trim());
String employeeName=request.getParameter("name").trim();
int salary=Integer.parseInt(request.getParameter("salary").trim());
}
else
{
out.println("<h1>Employee details already existed.</h1>");
}
out.println("");
out.close();
}
}
In doGet(), the parameters are appended to the URL and sent along with the header information.
The serialVersionUID is used as a version control in a Serializable class. If you do not explicitly
declare a serialVersionUID, JVM will do it for you automatically, based on various aspects of
your Serializable class, as described in the Java(TM) Object Serialization Specification. Sets
the content type of the response being sent to the client, if the response has not been committed
yet.The given content type may include a character encoding specification.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ServletToHibernate</display-name>
<servlet>
<servlet-name>ServletDemo</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDemo</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
</web-app>
Employee.java
package com.itoolsinfo;
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.itoolsinfo.Employee" table="employee">
<id name="employeeId">
<generator class="assigned"></generator>
</id>
<property name="employeeName"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
The generator class subelement of id utilized to produce the unique identifier for the objects of
persistence class. There are numerous generator classes characterized in the Hibernate
Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator
interface.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">system</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Create the Dao class and store the POJO class object details which will be sent to the servlet
class.
Dao.java
package com.itoolsinfo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
}
session.close();
return flag;
}
}
HQL: Hibernate Query Language.
HQL is an object-oriented query language, similar to SQL, but instead of operating on tables
and columns, HQL works with persistent objects and their properties. This is main difference
between hql vs sql. HQL is a superset of the JPQL, the Java Persistence Query Language. A
JPQL query is a valid HQL query, but not all HQL queries are valid JPQL queries.
HQL is a language with its own syntax and grammar.
It is written as strings, like ―from Product p―. HQL queries are translated by Hibernate into
conventional SQL queries. Hibernate also provides an API that allows us to directly issue
SQL queries as well.
1. HQL Syntax
HQL syntax is defined as an ANTLR (ANother Tool for Language Recognition) grammar.
The grammar files are included in the grammar directory of the Hibernate core download.
(ANTLR is a tool for building language parsers). Lets outline the syntax for the four
fundamental CRUD operations here:
UPDATE [VERSIONED]
[FROM] path [[AS] alias] [, ...]
SET property = value [, ...]
[WHERE logicalExpression]
DELETE
[FROM] path [[AS] alias]
[WHERE logicalExpression]
INSERT
INTO path ( property [, ...])
Select
The name of an entity is path. The property names are the names of properties of entities
listed in the FROM path of the incorporated SELECT query. The select query is an HQL
SELECT query (as described in the next section).
As this HQL statement can only use data provided by an HQL select, its application can be
limited. An example of copying users to a purged table before actually purging them might
look like this:
The fully qualified name of an entity is path. The alias names may be used to abbreviate
references to specific entities or their properties, and must be used when property names used
in the query would otherwise be ambiguous.
The property names are the names of properties of entities listed in the FROM path.
If FETCH ALL PROPERTIES is used, then lazy loading semantics will be ignored, and all
the immediate properties of the retrieved object(s) will be actively loaded (this does not apply
recursively).
WHERE is used to create hql select query with where clause.
Unit 5
Introduction
The movement of Plain Old Java Object (POJO) was started in the beginning of the current
century and became main stream in the enterprise Java world. This quick popularity is certainly
closely related with the open source movement during that time. Many projects appeared, and
most of them helped this programming model become mature with the time. This unit will tell
how a thing were before this programming model existed in the enterprise Java community and
discusses the problems of the old Enterprise JavaBeans (EJB) programming model. It‘s important
that you understand the characteristics of the POJO programming model and what it provides to
developers. The second half of the unit focuses on containers as well as the inversion of control
patterns that are at the heart of the lightweight containers which are used today. We will learn
what is a container? Which services are offered? And how a container is made lightweight? We
will also learn about the inversion of control patterns, its close relationship with dependency
injection terminology.
The POJO means Plain Old Java Objects. The name was coined by Martin Fowler, Rebecca
Parsons, and Josh MacKenzie to provide some different name. It represents a programming trend
that aims to simplify the coding, testing, and deployment phases of enterprise Java applications.
We will have a better understanding of what problems the POJO model solves after understanding
the problems caused by EJB Programming model.
Spring framework is an open source Java platform. The first version was written by Rod
Johnson, who released the framework with the publication of his book Expert One-on-One J2EE
Design and Development in October 2002. The framework was first released under the Apache
2.0 license in June 2003. The first milestone release, 1.0, was released in March 2004 with further
milestone releases in September 2004 and March 2005.
The spring enables developers to develop enterprise class applications using POJO
programming model. The advantage of using only POJO is that we don‘t require an EJB
container product such as an application server but we have the option of using only robust
Servlet container such as Apache Tomcat.
Spring is organized in a modular fashion. Even though the number of packages and classes are
significant, we have to worry only about the ones we need and dismiss the rest.
Spring does not recreate anything; instead it makes use of some of the existing technologies
like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and many
other view technologies.
It's web framework is a well-designed web MVC framework, which provides a good option to
web frameworks such as Struts or remaining over-engineered or less popular web frameworks.
It provides a consistent transaction management interface that can reduce to a local transaction
and increase to global transactions.
The spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
WEB MVC etc. Let's understand the IOC and Dependency Injection first.
The prime aim of Inversion of control and Dependency Injection is to remove dependencies
of an application. This makes the system more decoupled and rectifiable. Inversion of control is
used to increase modularity of the program and make it extensible, and has applications in object-
oriented programming and other programming paradigms. The term was used by Michael
Mattsson in a thesis, taken from there by Stefano Mazzocchi and popularized by him in 1999 in a
defunct Apache Software Foundation project, Avalon, then further popularized in 2004 by Robert
C. Martin and Martin Fowler.
First let‘s try to understand IOC (Inversion of control). If we go back to old computer
programming days, program flow used to run in its own control. For instance let‘s consider a
simple chat application flow as shown in the below flow chart.
Send a message
NO
YES
Print a message
Now if you examine the program flow, it is direct sequential. The program is in control of itself.
Inversion of control means the program delegates control to someone else who will drive this
flow. For instance if we make the chatting application event based then the flow of the program
will go something as below:-
Send a message
You can see that the program flow is not sequential, its event based. So now the control is altered. It
means that the internal program controlling the flow, events drive the program flow. Event flow
approach is more flexible as their no direct invocation which leads to more flexibility.
We can say that IOC are implemented by only events. You can delegate the control flow by callback
delegates, observer pattern, events, DI (Dependency injection) and lot of other ways.
IOC (Inversion of control) is a general parent term whereas DI (Dependency injection) is a subset of
IOC. IOC is a concept where the flow of application is inverted. So for example rather than the
caller calling the method.
SomeObject.Call();
SomeObject.WhenEvent += Call();
In this code the caller is exposing an event and when that event occurs he is taking action. It‘s based
on the principle ―Don‘t call us, we will call you‖. For example, in Hollywood when artists used to
give auditions the judges would say them ―Don‘t call us, we will call you‖.
This conceptualization makes code more flexible as the caller is not aware of the object methods and
the object is not aware of caller‘s program flow.
Inversion of Control is a principle in software engineering by which the control of objects or portions
of a program is transferred to a container or framework. It‘s most often used in the context of
object-oriented programming.
By contrast with traditional programming, in which our custom code calls to a library, IoC enables a
framework to take control of the program flow and make calls to our custom code. In order to
enable this, frameworks use abstractions with additional behavior built-in. If we want to add our
own behavior, we need to extend the classes of the framework or plug-in our own classes.
The advantages
The Spring container is at the center of the Spring Framework. It create the objects, wire them
together, configure them, and manage their complete life cycle from creation till destruction. The
Spring container uses DI to manage the components that make up an application. These objects
are called Spring Beans.
The container gets its instructions on what objects to instantiate, configure, and assemble by reading
the configuration meta-data provided. The configuration meta-data can be represented either by
XML, Java annotations, or Java code. The following diagram represents a high-level view of how
Spring works. The Spring IoC container makes use of Java POJO classes and configuration
metadata to produce a fully configured and executable system or application.
POJO Classes
Final
Result
Ready to use
application
The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container
gets informations from the XML file and works with it accordingly. The main operations
performed by IoC container are:
Instantiate the application class
Configure the object
Assemble the dependencies between the objects
BeanFactory
This is the simplest container providing the basic support for DI and is defined by the
org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related
interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in
Spring for the purpose of backward compatibility with a large number of third-party frameworks
that integrate with Spring.
Spring has objects of the BeanFactory type that behave like the Factory object. We specify the
blueprints object in a configuration file, which is an XML file, and then supply it to BeanFactory .
Afterwards, if we need the instance of any object, we can ask BeanFactory for the same, which
then refers to the XML file and constructs the bean as given. This bean is now a Spring bean as it
has been created by Spring Container and is returned to us. This is how it is done.
1. Spring has BeanFactory , which creates new objects for us. So, the XYZ object will call
BeanFactory .
2. BeanFactory would read from Spring XML, which contains all the bean definitions. Bean
definitions are the blueprints. BeanFactory will then create beans from this blueprint and then
make a new Spring bean.
3. Finally, this new Spring bean is handed back to XYZ , as shown here:
BeanFactory
Object XYZ
Spring Bean
Spring XML
The advantage here is that this new bean has been created in this BeanFactory, which is known by
Spring. Spring handles the creation and the entire life cycle of this bean. So, for this case, Spring
acts as container for this newly created Spring bean. BeanFactory is defined by the
org.springframework.beans.factory.BeanFactory interface. The BeanFactory interface is the
central IoC container interface in Spring and provides the basic end point for Spring Core
Container towards the application to access the core container service. It is responsible for
containing and managing the beans. It is a factory class that contains a collection of beans. It
holds multiple bean definitions within itself and then instantiates that bean as per the client's
demands. BeanFactory creates associations between collaborating objects as they're instantiated.
This removes the burden of configuration from the bean itself along with the bean's client. It also
takes part in the life cycle of a bean and makes calls to custom initialization and destruction
methods.
ApplicationContext
This container adds more enterprise-specific functionality such as the ability to resolve textual
messages from a properties file and the ability to publish application events to interested event
listeners. This container is defined by the org.springframework.context.ApplicationContext
interface.
Creating a JavaBean
A bean in Java context is a simple Java class which has some properties (also called fields) and their
getter and setter methods. These properties can be regarded as instance variables of the bean. The
name of the properties and their getter/setter methods should adhere to the JavaBeans
specifications that follow general conventions for a Java class.
How to create ?
There are many ways to create a bean in Spring.. All of the methods involve creating a class which
will be regarded as a bean. So first let‘s create a class called User.
package com.mitu;
In this Java program, we are creating an instance of this class using new keyword but in Spring, there
are different ways to create an instance of a bean class without using new. Although, using new
keyword is permitted but is not recommended since injection of properties and Auto-wiring does
not work if you create a bean using new.
Following are the ways to create a bean in Spring.
This is the most primitive approach of creating a bean. The bean is declared in Spring‘s XML
configuration file. Upon startup, Spring container reads this configuration file and creates and
initializes all the beans defined in this file which can be used anytime during application
execution. Here is how we define a bean in configuration XML.
This method assumes that you are familiar with Spring XML configuration and how it is configured.
Details
A bean in Spring XML configuration file is defined by using element declaration. The id attribute is
identifier of the bean and get its reference during execution. The class attribute should contain the
fully qualified class name, including top level packages. This bean can be retrieved and used in
the application in the following way.
@SuppressWarnings("resource")
public static void main(String[] args) {
Lets get in to this code. The id attribute is not mandatory and is only required when you want to
access this bean in application or provide this bean as a dependency to some other bean.
The id of a bean should be unique otherwise we will get an error at start up like
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration
problem: Bean name ‗test‘ is already used in this <beans> element.
The scope of bean will be singleton by default, which means every time the bean is referred, same
instance will be given. The scope of the bean can be changed by adding a scopeattribute in bean
declaration.
Bean properties referred in the propertyelement should have valid setter methods otherwise following
error will be received.
Spring automatically performs the string to number conversion when the type of a class property is
numeric while the values provided in XML configuration file are there in string format. But , we
will get a java.lang.NumberFormatException if the property is not possible to get converted to
number.
@Component annotation above a class indicates that this class is a component and should be
automatically detected and instantiated. Thus a Spring component bean will be created in this
way.
package com.mitu;
@Component
public class Manager {
private String name;
Explanation:
We need to instruct Spring container to find our beans and tell it about the package where it should
find the beans, in order for a bean to be auto-discoverable and instantiated. Hence, for
instantiating annotated beans, we require to add below declaration in our Spring XML
configuration file :
If the bean annotated with @Componentannotation is outside of the package given in base-package
attribute of this above element, then it will not be scanned and instantiated and thus won‘t be
found. This bean can also be used in the same way as the bean in the previous method. Thus, only
bean declaration methods differs while the method of using them remains the same as of the first.
@Component annotation can only be applied at the class level. Applying it to some other location
such as above a field will result it in a compiler error. The annotation @Component is not allowed
for this location.
If a bean is referred and it has not been annotated with @Component or declared in XML
configuration then we will get an exception as show below.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
[com.mitu.Manager] is defined
Automatic instantiating a bean using @Component annotation needs that there must be a default
constructor present in the class. As we know that, default constructor is a constructor without any
arguments. If there is no constructor present in a class, then a default constructor is automatically
created and used. If there is a constructor in your bean class which accepts some arguments then
you have to create a default constructor yourself. If default constructor is not available, then
following error will be generated.
Inversion of Control
Dependency Injection
Dependency Injection (DI) is a design pattern that is used to remove the dependency from the
programming code so that it can be easy to manage and test our application. Dependency
Injection makes our programming code loosely coupled.
It solves problems such as-
How can an application or class be independent of how its objects are created?
How can the way objects are created be specified in separate configuration files?
How can an application support different configurations?
Creating objects directly within the class that requires the objects is inflexible because it commits the
class to particular objects and makes it impossible to change the instantiation later independently
from the class. It stops the class from being reusable if other objects are required, and it makes the
class hard to test because real objects can't be replaced with mock objects.
A class is no longer responsible for creating the objects it needs, and it doesn't have to delegate
instantiation to a factory object as in the Abstract Factory design pattern.
In order to learn the DI, let's understand the Dependency Lookup (DL).
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There can be
various ways to get the resource for example:
In such way, we get the resource (instance of X class) directly by using new keyword. Another way is
to use factory method:
X obj = X.getX();
Using this way, we get the resource (instance of X class) by calling the static factory method getX().
Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) such as:
1. Context con = new InitialContext();
2. Context environmentCon = (Context) con.lookup("java:comp/env");
3. X obj = (X) environmentCon.lookup("X");
There can be various ways to to obtain the resource. But there are several problems in this approach.
Using constructor-based dependency injection, the container will raise a constructor with arguments
each representing a dependency that we want to fix.
The Spring resolves each argument primarily by type, followed by name of the attribute and index for
clarity. See the below example of the configuration of a bean and its dependencies using
annotations:
@Configuration
public class Application {
@Bean
public Item item1() {
return new ItemImpl1();
}
@Bean
public Store store() {
return new Store(item1());
}
}
The @Configuration annotation indicates that the class is a source of bean definitions. Also, it is
possible to add it to multiple configuration classes.
The @Bean annotation is used on a method for a bean definition. If we don‘t specify a custom name,
the bean name will default to the method name.
For a bean with the default singleton scope, Spring first checks if a cached instance of the bean
already exists and only creates a new one if it is not existing. If we‘re using the prototype scope,
the container returns a new bean instance for each of the method call.
Following is one more way to create the configuration of the beans is through XML configuration:
Constructor Injection is the process of injecting the dependencies of an object through its constructor
argument at the time of instantiating it. In other words, we can say that dependencies are supplied
as an object through the object's own constructor. The bean definition can use a constructor with
any number of arguments to initiate the bean, as shown here:
In the preceding code, the object of the EmplDao emplDao type is injected as a constructor argument
to the EmplServiceImpl class. We need to configure bean definition in the configuration file that
will do Constructor Injection. The Spring bean XML configuration tag <constructor-arg> is used
for Constructor Injection:
...
<bean id="emplService"
class="org.mitu.Spring.second.dependencyinjection.EmplServiceImpl">
<constructor-arg ref="emplDao" />
</bean>
<bean id="emplDao"
class="org.mitu.Spring.second.dependencyinjection.EmplDaoImpl">
</bean>
...
In the above pseudo-code, there is a Has-A relationship between the classes, which is
EmplServiceImpl HAS-A EmplDao . Here, we inject a user-defined object as the source bean into
a target bean using Constructor Injection. Once we have the emplDao bean to inject it into the
target emplService bean, we need another attribute called ref —its value is the name of the ID
attribute of the source bean, which in our case is "emplDao" .
The <constructor-arg> sub-element of the <bean> element is used for creating the Constructor
Injection. This tag element supports four attributes. They are explained in the following table:
We inject simple Java types into a target bean using the Constructor Injection. The Empl class has
emplName as String , emplAge as int , and married as boolean. The constructor initializes all
these three fields. Following is the Empl.java file:
package org.mitu.Spring.second.constructioninjection.simplejavatype;
public class Empl
{
private String emplName;
private int emplAge;
private boolean married;
public Empl(String emplName, int emplAge, boolean married)
{
this.emplName = emplName;
this.emplAge = emplAge;
this.married = married;
}
@Override
public String toString()
{
return "Empl Name: " + this.emplName + " , Age:" + this.emplAge + ",
IsMarried: " + married;
}
}
...
<bean id="empl" class="org.mitu.Spring.second.constructioninjection.simplejavatype.Empl">
<constructor-arg value="Rashmi Thorave" />
<constructor-arg value="28" />
<constructor-arg value="True" />
</bean>
…
In the Spring Framework, whenever we create a Spring bean definition file and provide values to the
constructor, Spring decides implicitly and assigns the bean's value in the constructor by means of
following main factors:
Whenever Spring tries to create bean using Construction Injection by following the mentioned rules, it
tries to resolve the constructor to be chosen while creating Spring bean and hence results in the
following circumstances.
No ambiguity
When Spring tries to create a Spring bean using the preceding rule if no matching constructor is
found, it throws BeanCreationException exception with the message: Could not resolve matching
constructor .
We will understand this scenario in more detail by taking the Empl class from earlier, which has three
instance variables and a constructor to set the value of this instance variable.
The Empl class has a constructor in the order of String, int, and boolean to be passed while defining
the bean in the definition file. In the beans.xml file, you'll have the following code:
...
<bean id="empl" class= "org.mitu.Spring.second.constructioninjection.simplejavatype.Empl">
<constructor-arg value="Rashmi Thorave" />
<constructor-arg value="True" />
<constructor-arg value="28" />
</bean>
…
If the orders in which constructor-arg is defined are not matching, then we will receive the following
exception:
Solution
The solution to this problem is to fix the order of elements sent. Either we modify the constructor-arg
order of the bean definition file or we use the index attribute of constructor-arg as follows:
...
<bean id="empl"
class="org.mitu.Spring.second.constructioninjection.simplejavatype.Empl">
<constructor-arg value="Rashmi Thorave" index="0" />
<constructor-arg value="True" index="2" />
<constructor-arg value="28" index="1" />
</bean>
…
Remember that the index attribute in all collection elements always starts with 0.
Parameter ambiguity
Sometimes, there is no problem in resolution of the constructor, but the constructor chosen is leading
to in-convertible data. In this case, org.springframework.beans.
factory.UnsatisfiedDependencyException is thrown just before the data is converted to the actual
data type.
We will understand this scenario in more detail; the Empl class contains two constructor methods and
both accept three arguments with different data types.
The following code snippet is also present in Empl.java :
package org.mitu.Spring.second.constructioninjection.simplejavatype;
public class Empl
{
private String emplName;
private int emplAge;
private String emplId;
Empl(String emplName, int emplAge, String emplId)
{
this.emplName = emplName;
this.emplAge = emplAge;
this.emplId = emplId;
}
Empl(String emplName, String emplId, int emplAge)
{
this.emplName = emplName;
this.emplId = emplId;
this.emplAge = emplAge;
}
@Override
public String toString()
{
return "Empl Name: " + emplName + ", EmplAge: " + emplAge + ",
Empl Id: " + emplId;
}
}
...
<bean id="empl" class="org.mitu.Spring.second.constructioninjection.simplejavatype.Empl">
<constructor-arg value="Rashmi Thorave" />
<constructor-arg value="534" />
<constructor-arg value="28" />
</bean>
…
Spring chooses the wrong constructor to create the bean. The preceding bean definition has been
written in the hope that Spring will choose the second constructor as Rashmi Thorave for
emplName , 534 for emplId , and 28 for emplAge . But the actual output will be:
constructor arguments specified but no matching constructor found in bean 'CustomerBean' (hint:
specify index and/or type arguments for simple parameters to avoid type ambiguities)
Solution
The solution to this problem uses the type attribute to specify the exact data type for the constructor:
...
<bean id="empl"
class="org.mitu.Spring.second.constructioninjection.simplejavatype.Empl">
<constructor-arg value="Rashmi Thorave" type="java.lang.String"/>
<constructor-arg value="534" type="java.lang.String"/>
<constructor-arg value="28" type="int"/>
</bean>
…
Empl Name: Rashmi Thorave, Empl Age: 28, Empl Id: 534
Setter Injection in Spring is a type of dependency injection in which the framework injects the
dependent objects into the client by the setter method. The container first calls the default
argument constructor and then calls the setters. The setter based injection can work even If some
dependencies have been injected using the constructor.
@Bean
public Store store()
{
Store store = new Store();
store.set(item1());
return store;
}
We can also use XML for the same configuration of the beans:
Constructor-based and setter-based types of injection can be combined together for the same bean.
The Spring documentation recommends using constructor-based injection for compulsory
dependencies, and setter-based injection for optional ones.
The setter-based D.I. is the method of injecting the dependencies of an object using the setter method.
In setter injection, the Spring container uses set() of the Spring bean class to assign a dependent
variable to the bean property from the bean configuration file. The setter method is more
convenient to inject more dependencies since a large number of constructor arguments makes it
clumsy.
In the EmplServiceImpl.java class, you'll ind the following code:
In the given pseudo-code, the EmplServiceImpl class defined the setEmplDao() method as the setter
method where EmplDao is the property of this class. This method injects values of the emplDao
bean from the bean configuration file before making the emplService bean available to the
application.
The Spring bean XML configuration tag <property> is used to configure properties. The ref attribute
of property elements is used to specify the reference of another bean.
...
<bean id="emplService" class="org.mitu.Spring.second.dependencyinjection.EmplServiceImpl">
<property name="emplDao" ref="emplDao" />
</bean>
<bean id="emplDao" class="org.mitu.Spring.second.dependencyinjection.EmplDaoImpl">
</bean>
…
The <property> element invokes the setter method. The bean definition can be describing the zero or
more properties to inject before making the bean object gettable in the application. The
<property> element tallies to JavaBeans' setter methods, which are exposed by bean classes. The
<property> element supports the following three attributes:
Here, we inject string-based values using the setter method. The Empl class contains the emplName
ield with its setter method.
In the Empl.java class, we will have the following code:
package org.mitu.Spring.second.setterinjection;
public class Empl
{
String emplName;
public void setEmplName(String emplName)
{
this.emplName = emplName;
}
@Override
public String toString()
{
return "Empl Name: " + emplName;
}
}
...
<bean id="empl" class="org.mitu.Spring.second.setterinjection.Empl">
<property name="emplName" value="Rashmi Thorave" />
</bean>
…
In this pseudo-code, the bean configuration file set the property value. In the Payroll.java class, lets
have the following code.
package org.mitu.Spring.second.setterinjection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXml.ApplicationContext;
public class Payroll
{
public static void main(String[] args)
{
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
Empl empl = (Empl)
context.getBean("empl");
System.out.println(empl);
}
}
In the Spring IoC container, beans can also access collections of the objects. Spring allows us to inject
a collection of objects in a bean using Java's collection framework. Setter Injection can be used to
inject collection of values into the Spring Framework. If we have a dependent object in the
collection, we can inject this information using the ref element in the list, set, or map. See the
below elements.
•<list> : It describes a java.util.List type. A list can contain multiple bean , ref , value , null , another
list , set , and map elements. The required conversion is automatically performed by BeanFactory.
• <set> : It describes a java.util.Set type. A set will have multiple bean , ref , value , null , another set ,
list , and map elements.
• <map> : It describes a java.util.Map type. A map can contain zero or more <entry> elements, which
describes a key and value.
The Empl class is a class with an injecting collection. In the Empl.java class, we will have the
following code:
package org.mitu.Spring.second.setterinjection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Empl
{
private List<Object> lists;
private Set<Object> sets;
private Map<Object, Object> maps;
The bean configuration file of this code is the one that injects each and every property of the Empl
class.
In the beans.xml file, we will have the following code:
...
<bean id="empl" class="org.mitu.Spring.second.setterinjection.Empl">
<property name="lists">
<list>
<value>Rashmi Thorave</value>
<value>Aniket Thorave</value>
<value>Rahul Thorave</value>
</list>
</property>
<property name="sets">
<set>
<value>Vihaan Thorave</value>
<value>Pravina Thorave</value>
</set>
</property>
<property name="maps">
<map>
<entry key="Key 1" value="Shiroli Bk"/>
<entry key="Key 2" value="Maharashtra"/>
</map>
</property>
</bean>
...
In this pseudo code, we have injected values of all three setter methods of the Empl class. The List
and Set instances are injected with the <list> and <set> tags. For the map property of the Empl
class, we injected a Map instance using the <map> tag. Each entry of the <map> tag is specified
with the <entry> tag that contains a key-value pair of the Map instance.
Introduction
The presentation layer in an enterprise application is the front door to your application created in Java.
It provides users a interactive view of the information, allowing them to perform business
functions provided and managed by the application. The development of the presentation layer is
a difficult task these days because of the rise of cloud computing and different kinds of devices
that people are using on regular basis. Many technologies and frameworks are now getting used to
develop enterprise web applications, such as Spring Web MVC, Java Server Faces (JSF), Struts,
Google Web Toolkit (GWT), as well as as jQuery. These provide rich component libraries that
can help develop the interactive web front-ends. Many frameworks also provide widget libraries
and tools targeting mobile devices, including tables and smart-phones.
6.1 The Spring Web Model View Controller (MVC)
The Spring Web Model View Controller (MVC) framework supports web application development by
providing broadas well as intensive support for the Java application. The framework is flexible,
robust, and well-designed and is used to develop web applications. It is designed in such a way
that development of a web application is highly configurable into Model, View, and Controller. In
the MVC design pattern, Model represents the information or data of a web application; View
represents the User Interface (UI) components by which user interacts with it, such as checkbox,
textbox, radio buttons and so forth that are used to display web pages; and Controller processes as
per the user request. The Spring MVC framework helps in integrating other frameworks, such as
Struts and WebWork, with a Spring application. This framework also supports the integration of
other view technologies such as Java Server Pages (JSP), FreeMarker, Tiles, and Velocity in a
Spring web application.
Fig. 6.1 Spring MVC Architecture
Model – It contains the data of the application. A data can be a single object or a collection of objects.
Controller –It contains the business logic of an application. Here, the @Controller annotation is used
to mark the class as the controller.
View –It represents the provided information in a particular format. Generally, JSP+JSTL is used to
create a view page. Although spring also supports other view technologies such as Apache
Velocity, Thymeleaf and FreeMarker.
Front Controller – In Spring Web MVC, the DispatcherServlet class works as the front controller. It
is responsible to manage the flow of the Spring MVC application.
Isolated roles - The Spring MVC isolates each role, where the model object, controller, command
object, view resolver, DispatcherServlet, validator, can be fulfilled by a specialized object.
Light-weight - This uses light-weight Servlet container to develop and deploy your application.
Mighty Configuration - It provides a robust configuration for both framework and application classes
which includes easy referencing across contexts, such as from web controllers to business objects
and validators.
Fast development - The Spring MVC facilitates rapid and parallel development.
Reusable business code - Instead of creating new objects, it allows us to use the existing business
objects.
Effortless to test - In Spring, generally we create JavaBeans classes that enablesus to inject test data
using the setter methods.
Flexible Mapping - It provides the specific annotation that easily redirects the page.
class SView
{
public void show()
{
System.out.println("Student View");
}
}
class Dispatch
{
private SView SView;
private TView TView;
public Dispatch()
{
SView = new SView();
TView = new TView();
}
class FrController
{
private Dispatch Dispatch;
public FrController()
{
Dispatch = new Dispatch();
}
if(isAuthenticUser())
{
Dispatch.dispatch(request);
}
}
}
class FrControllerPattern
{
public static void main(String[] args)
{
FrController frController = new FrController();
frController.dispatchRequest("Teacher");
frController.dispatchRequest("Student");
}
}
Benefits:
Focused control : TheFront controller handles all the requests to the Web application. This
implementation of focused control that ignores using multiple controllers is desirable for
imposing application-wide policies such as users tracking and safety.
Thread safety : A new command object uprises when receiving a new request and the command
objects are not meant to be thread-safe. Thus, it will be safe in the command classes. Although
safety is not guaranteed when threading issues are collected, codes that act with the command are
still thread safe.
Drawbacks:
It is not possible to scale an application using a front controller. The scaling up the application
requires additional programming.
It has several performance issues. Performance is better if you deal with a single request
uniquely.
The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class of servlet
package), and as such is declared in the web.xml of our web application. We need to map requests
that we want the DispatcherServlet to handle, by using a URL mapping in the same web.xml file.
This is standard J2EE Servlet configuration; the example given below shows such a
DispatcherServlet declaration and mapping:
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/example/*</url-pattern>
</servlet-mapping>
</web-app>
In the given example, all requests starting with /example will be handled by the DispatcherServlet
instance named example. In a Servlet 3.0 and ahead environment, we also have the option of
configuring the Servlet container by programs. The code shown below is based equivalent of the
above web.xml example:
Let's take a look at some of the MVC features used in the pseudo code above.
<mvc:annotation-driven/> : This tells the Spring Framework to support annotations like @Controller ,
@RequestMapping , and others, all of which simplify the writing and configuration of controllers.
InternalResourceViewResolver : The Spring MVC framework supports various types of views for
presentation technologies, including JSPs, HTML, PDF, JSON, and many more. When the
DispatcherServlet class defined in the application's web.xml file gets a view name returned from
the handler, it resolves the logical view name into a view implementation for rendering.
In the above pseudo code, we have configured the InternalResourceViewResolver bean to resolve the
bean into JSP files in the /WEB-INF/views/ directory.
<context:component-scan> : This tells Spring to automatically detect annotations. It takes the value of
the base package, which corresponds to the one used in the Spring MVC controller.
package org.mitu.Spring.third.springmvc.controller;
import org.springframework.stereotype.Controller;
@Controller
public class EmplController
{
// …
}
The @Controller annotation indicates the role to the annotated class. Such an annotated class is
scanned by the dispatcher for mapped methods and finds the @RequestMapping annotation. This
defined controller can be automatically registered in the Spring container by adding –
<context:component-scan/> in SpringDispatcher-servlet.xml ile.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.mitu.Spring.third.springmvc"/>
<!-- ... -->
</beans>
Unit 7
Introduction to Java API
Introduction
An e-mail plays an important role in all daily activities in this era of inter-connected networks. For
example, we want to get regular updates of a particular feature on a website, by just subscribing to
that feature, we will start receiving e-mails regarding these updates. E-mails also allow us to
receive notifications, business related communications, or any periodical reports of a producer.
Oracle JAVA provides a simple yet mighty API called as a JavaMail API for creating an
application to have an e-mail support. This API is actually a set of classes and interfaces for
creating the e-mail applications. Writing the program using this API in Java, we can send as well
as receive the e-mails, which can be scaled up to work with different protocols associated with the
mailing system like POP and SMTP. Being a very powerful API, it is complex, and using the
JavaMail API directly in our application is a slightly tiresome work as it involves writing a lot of
programming lines.
7.1 What is an API?
API is means Application Programming Interface which is a collection of communication protocols
and subroutines used by various programs of language to convey data among them. A
programmer can use various Application Programming Interface tools to make its program easy.
Also, an API facilitates the programmers with an efficient way to develop their programs.
Thus in simple term, an Application Programming Interface helps two programs or applications to
communicate with each other by providing them with essential tools as well as functions and
methods. It receives the request from the user and transmits it to the service provider and again
sends the result generated from the service provider to the desired user.
The developers use Application Programming Interfaces in their software to implement different
features by using an API call without writing the complicated codes for it. We can write an API
for an operating system, database systems, hardware system etc. An API is similar to a GUI
(Graphical User Interface) with one prime difference.
Disadvantages of APIs
Cost: Development and implementation of the API is costly at times and needs high maintenance and
support from developer.
Security: The API adds another layer of surface which is then prone to attacks, and hence the security
risk problem occurs in APIs.
// Sender's email ID
String from = "data@xyz.com";
try
{
// Create a MimeMessage class object.
MimeMessage mime = new MimeMessage(session);
// Send message
Transport.send(message); // This is javax.mail package
System.out.println("The message is sent successfully!");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
When we compile and run this program, we will get the following output
Output
$ java EmailSend
The message is sent successfully!
If we want to send an e-mail to multiple recipients then the following methods would be used to
specify multiple e-mail IDs:
Parameters:
type − This would be set to TO, CC or BCC. Here TO represents original receiver of message, CC
represents Carbon Copy and BCC represents Black Carbon Copy. Example:
Message.RecipientType.TO
addresses − This is an array of e-mail IDs. We would need to use InternetAddress() method while
specifying email IDs.
The output of this application can be checked by opening the inbox of your email.
Now check the Spring Java Messaging Service.
The Spring Framework supports JMS with the help of the classes as mentioned below:
ActiveMQConnectionFactory : This class is used to create a JMS ConnectionFactory for
ActiveMQ that connects to a remote broker on a specific host name and the port.
ActiveMQQueue: This class will configure the ActiveMQ queue name, as in our case it is
myMessageQueue.
JmsTemplate :This class allows us to hide some of the lower-level JMS description while
sending a message.
Start ActiveMQ
Before we run Application.java , we have to start ActiveMQ, which allows us to run a broker; it will
run ActiveMQ Broker using the out-of-the-box configuration.
Output:
Run Application.java and get the output on the console as shown below:
Message Sent to JMS Queue: {state=Maharashtra, Hello=India, country=India, city=Nashik}
// Sender's email ID
String from = "data@xyz.com";
// Actual message
msg.setContent("<h1>This is your message</h1>", "text/html");
// Send message
Transport.send(msg);
System.out.println("Message is sent successfully!");
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
Output:
$ java HtmlEmail
Message is sent successfully!
7.7 Sending email with attachment
JavaMail API provides some useful classes like BodyPart, MimeBodyPart etc for sending email with
attachment. Let‘s see the steps of sending email using JavaMail API first. For sending the email
using JavaMail API, we need to load the two jar files:
mail.jar
activation.jar
So wee need to download these jar files (or) go to the Oracle site to download the latest version of
them.
We need to go with 7 steps for sending attachment with email.
Create the session object
Compose the message
Create object of MimeBodyPart and set your message text
Create new MimeBodyPart object and set DataHandler object to this object
Create Multipart object and add MimeBodyPart objects to this object
Set the multiplart object to the message object
Finally, send the message
//Fourth: create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
//Fifth: Create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(msgBodyPart1);
multipart.addBodyPart(msgBodyPart2);
//Sixth: Set the multiplart object to the message object
msg.setContent(multipart);
As you can see in the above code, total 7 steps are followed to send email with attachment. Now run
this program by :
Load the jar file c:\> set classpath=mail.jar;activation.jar;.;
Compile the source file c:\> javac SendWithAttachment.java
Run using c:\> java SendWithAttachment
As we can see in the above example, userid and password need to be authenticated. As, this program
illustrates, we can send email easily but change the username and password as per the account
used.
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import com.sun.mail.pop3.POP3Store;
public class ReceiveMail
{
public static void receiveEmail(String pop3Host, String storeType, String user, String password)
{
try {
//First:Create the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);
Session emailSession = Session.getDefaultInstance(properties);
//Second: create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//Fourth:acquire the messages from the folder in an array element and print it
Message[ ] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++)
{
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number: " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//Fifth: close the store and folder objects
emailFolder.close(false);
emailStore.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (NoSuchProviderException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
String host = "mail.gmail.com"; // Change as per requirement
String mailStoreType = "pop3";
String username= "data@gmail.com";
String password= "xxxxx"; // User password
receiveEmail(host, mailStoreType, username, password);
}
}
In the above example, userid and password need to be authenticated. We can receive email easily but
change the username and password as per our account.
Receiving email with attachment
As we receive the email, we can receive the attachment also by using Multipart and BodyPart classes
available in JavaMail API.
import java.util.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.*;
import java.io.*;
class ReadAttachments
{
public static void main(String [] args) throws Exception
{
String host="mail.zoho.com";
final String user="mail@zoho.com";
final String password="xxxxx"; // Actual password
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class ForwardingEMail
{
public static void main(String[] args) throws Exception
{
final String user="maya@abc.com"; // User ID
final String password="xxxxx"; // Password
// Send message
Transport.send(msg2);
System.out.println("The message is forwarded!");
}
}
Unit 8
JSON
Introduction
JavaScript Object Notation (JSON) is an open-standard file format that uses human-readable text to
transfer data objects consisting of attribute–value pairs and array data types (or any other
serializable value). It is a very common type of data format used for asynchronous browser–server
communication.
JSON is a language-independent data format. It was derived from JavaScript, but many modern
programming languages include code to produce and parse JSON-format data. The official
Internet media type for JSON is application/json. The JSON filenames use the extension .json.
Developer Douglas Crockford originally specified the JSON format in the early 2000s. It was first
standardized in 2013 as RFC 7158 and ECMA-404.
8.1 What is JSON ?
JSON is an acronym of JavaScript Object Notation.
It is a lightweight data-interchange file format.
It is simple to read and write than XML.
It is language independent file format.
It supports array, object, string, number and values.
Applications of JSON
It is used while writing JavaScript based applications that has browser extensions and websites.
JSON data format is used for serializing and transmitting structured data all over network
connection.
It is primarily used to transfer data among a server and web applications.
Web services and APIs use JSON format to provide public data for various services.
It is compatible with all modern programming languages like Python, Ruby and R.
{
"id":"02",
"language": "Python",
"edition": "Fifth",
"author": "Yela Rawbundy"
}
]
}
This file data format can be added for the HTML code and JavaScript. Following is the code for
json.htm −
<html>
<head>
<title>JSON </title>
<script language = "javascript">
var object1 = { "language" : "C", "author" : "Yashwant Kanetkar" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied from book written by " +
object2.author);
document.write("<hr />");
</script>
</head>
<body>
</body>
</html>
Now let's try to open json.htm using any web browser or any other javascript enabled browser that
produces the following result −
Fig. 8.1 Output of JavaScript using JSON data format
8.3 JSON – Syntax
Let‘s look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript
syntax; it includes the following −
Data is represented in the format of key/value pairs.
Four symbols are used in JSON. The curly braces { } hold objects and each name is followed
by ':' (colon), and the key/value pairs are separated by , (comma).
Square brackets hold arrays and values are separated by , (comma).
Number
1
It is double-precision floating-point format of JavaScript
String
2
It is double-quoted Unicode set of characters
Boolean
3
either true or false
Array
4
It is an ordered sequence of values of same type
Value
5
It can be a string, a number, a boolean, or null value
Object
6
It is an unordered collection of key-value pairs
Whitespace
7
This can be used between any pair of tokens
null
8
The empty character (referred as nothing)
Number
It is a double precision floating-point format in JavaScript and it depends on its implementation.
Unlike other programming languages, Octal and hexadecimal formats are not used. It does not have a
NaN or Infinity number.
The following table shows the number types data.
Integer
1 All decimal Digits from 0 to 9 including the positive and
negative numbers
Fraction
2
Floating point values with a decimal dot (.)
Exponent
3
The float values including e, -e, E or -E e.g. 4.5e12
Syntax:
The following way is used to declare the variable with the data type and constant.
var json-object-name = { string : number_value, .......}
Example:
The example below shows Number Datatype, value should not be quoted −
var obj = {marks: 59}
String
It is a sequence of double quoted Unicode characters which also allows the escape sequence
characters. Character is a single character string i.e. a string with length 1. The table below shows
various special characters that you can use in strings of a JSON document.
\"
1
double quotation character
\\
2
backslash character
\/
3
forward slash character
\b
4
backspace character
\f
5
form feed character
\n
6
new line character
\r
7
carriage return
\t
8
horizontal tab character
\u
9
four hexadecimal digits or unicode character
Syntax:
var json-object-name = { string : "string value", .......}
Example
The example below showsthe String type data.
var obj = { name: ―Rashmi‖ }
Boolean:
It includes either true or false values. The concept is similar to the one in Java
Syntax
var json-object-name = { string : true/false, .......}
Example
var obj = {name: 'Rashmi', marks: 59, distinction: false}
8.5 Array
It is an ordered collection of values stored in homogeneous order in memory. The values of array are
enclosed in pair of square brackets which means that array begins with .[. and ends with .].. The
values are separated by, (comma) within it. Array indexing can be started at 0 and ends till n-1,
where n is total number of elements in array. Arrays should be used when the key names are
sequential integers.
Syntax
[ value, .......]
Example
Example showing array containing multiple objects −
{
"books": [
{ "language":"Marathi" , "Region":"Goa" },
{ "language":"Urdu" , "Type":"Indo-Aryan" },
{ "language":"Kannada" , "Region":"Karnataka" }
]
}
Object
The object is an unordered set of key – value pairs. They are enclosed in a pair of curly braces that is,
it starts with '{' and ends with '}'. Each key in this pair is followed by ':'(colon) and the key-value
pairs are separated by , (comma). The keys must be strings and should be unique in all the set.The
objects should be used when the key names are arbitrary strings.
Syntax
{ string : value, .......}
Example
Example showing Object −
{
"pin": "411061",
"city": "Pune",
"ranking": 2,
}
Whitespace
The whitespace can be inserted between any pair of tokens. It is added to make a code more readable.
The example shown below gives declaration with and without whitespace.
Syntax:
{string:"",....}
Example:
var obj1 = {"name": "Amar Choudhary"}
var obj2 = {"name": "Shane Warne"}
var obj3 = {"name": "Aniket Vishwasrao"}
null
It means empty type.
Syntax
null
Example:
var i = null;
if(i == null)
{
document.write("<h3>value is null</h3>");
}
else
{
document.write("<h3>value is not null</h3>");
}
JSON Value
Syntax:
String | Number | Object | Array | TRUE | FALSE | NULL
Example
var i = 45.44;
var j = "Hi Python";
var b = true;
var k = null;
In the given example, player is an object in which "name", "runs" and "bowler" are the keys. And
there are string, number and boolean value are used for the keys.
{
"firstName": "Rakesh",
"lastName": "Sharma",
"age": 35,
"address" : {
"streetAddress": "301, Akanksha Plaza",
"city": "Nashik",
"state": "Maharashtra",
"postalCode": "422006"
}
}
JSON Array
The JSON array represents ordered list of values stored in a homogeneous locations. The JSON array
can store multiple values of same type of data. It can store string, number, boolean or object in
JSON array. The values here must be separated by comma. The [ (square bracket) represents
JSON array.
Jackson
The Jackson is a multi-purpose Java library for processing JSON data format. Jackson aims to be the
best possible combination of fast, correct, lightweight, and ergonomic for developers.
The Jackson offers three methods for processing JSON format, each of them having it‘s own
advantages and disadvantages.
Streaming API or incremental parsing/generation: reads and writes JSON content as discrete
events.
Tree model: provides a mutable in-memory tree representation of a JSON document. The data
representation is done in graphical format.
Data binding: converts JSON to and from POJO‘s
If we are only interested in converting Java object to and from JSON string then the third method can
be used more effectively.
The advantage of Jackson is that it suppliesthe heaps of features, and looks to be a good tool for
reading and writing JSON in a variety of ways, but same time its size becomes a disadvantage if
our requirement is just to serialize and deserialize Java object to JSON String.
In order to use Jackson, we can include following maven dependency or manually include jackson-
core-2.3.1.jar, jackson-databind-2.3.1.jar, and jackson-annotations-2.3.1.jar in Classpath.
When we serialize an instance of this entity, we get all the key-values in the Map as standard, plain
properties:
{
"name":"The First Bean",
"attr2":"val2",
"attr1":"val1"
}
And here how the serialization of this entity looks like in practice:
@Test
public void whenSerializingUsingJsonAnyGetter_thenCorrect() throws JsonProcessingException
{
ExtendableBean bean = new ExtendableBean("My bean");
bean.add("attr1", "val1");
bean.add("attr2", "val2");
assertThat(result, containsString("attr1"));
assertThat(result, containsString("val1"));
}
We can also use optional argument enabled as false to disable @JsonAnyGetter(). In this case, the
Map will be converted as JSON and will appear under properties variable after serialization.
GSON
The full form of GSON is the google-gson library. Gson is a Java library capable of converting Java
objects into their JSON representation and JSON strings to an equivalent Java object without the
requirement of placing Java annotations in our classes.
Features of Gson library:
It provides simple toJson() and fromJson() methods to convert Java objects to JSON and vice-
versa.
It Supports arbitrarily complex objects
It has extensive support of Java Generics library
It allows custom representation for Java objects
It allows pre-existing unmodifiable objects to be converted to and from JSON.
How to use GSON?
1. Maven Dependency
First of all, we have to include the gson dependency in our pom.xml file as-
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
We can find the latest version of gson on Maven Central online website.
2. Using JsonParser
The first approach is for converting a JSON String to a JsonObject is a two-step process that uses the
JsonParser class. In this step, we need to parse our original String. Gson provides us a parser
called JsonParser, which parses the specified JSON String into a parse tree of JsonElements:
public JsonElement parse(String json) throws JsonSyntaxException
Once we have our String parsed in a JsonElement tree, we‘ll use the getAsJsonObject() method,
which will return the desired result to us.
Let‘s see how we get our final JsonObject:
String json = "{ \"name\": \"Schildt\", \"python\": false }";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
Assert.assertTrue(jsonObject.isJsonObject());
Assert.assertTrue(jsonObject.get("name").getAsString().equals("Baeldung"));
Assert.assertTrue(jsonObject.get("java").getAsBoolean() == true);
3. Using fromJson( ) method.
In the second approach, we create a Gson instance and use the fromJson method. This method
deserializes the specified JSON String into an object of the specified class:
public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException
The following way is used to see this method to parse our JSON String, passing the JsonObject class
as the second parameter:
String json = "{ \"name\": \"Schildt\", \"python\": false }";
JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class);
Assert.assertTrue(convertedObject.isJsonObject());
Assert.assertTrue(convertedObject.get("name").getAsString().equals("Schildt"));
Assert.assertTrue(convertedObject.get("python").getAsBoolean() == true);
8.8 json-simple
The json-simple is one of the simplest JSON library used by developers, which is also lightweight.
We can use this library to encode or decode JSON text in any format specified. It's an open source
library which is flexible and simple to be used by reusing Map and List interfaces from Java
Development Kit. A good thing about this library that it has no external dependency present and
both source and binaries are JDK 1.2 and above compatible.
The benefit of using Json-simple is that it is lightweight, having just 12 classes and it provides support
for Java IO readers and writers classes. We can take our decision better if we know about JSON
format i.e. how information is represented there in JSON.
If we are looking for a simple lightweight Java library that reads and writes JSON and supports
Streams, json-simple is probably a good match. It does what it says with just 12 classes, and
works on legacy (1.4) JREs also.
In order to use JSON-Simple API, we need to include maven dependency in our project's pom.xml
file or alternatively, we can also include following JAR files in your classpath. You can also see
this tutorial to learn about how to read JSON String in Java using json-simple.
How to use the json-simple?
Following steps are undertaken to use the json-simple library in Java.
1. Install json.simple
In order to install json.simple, we need to set classpath of json-simple.jar or add the Maven
dependency from their online website.
2. Add maven dependency, in pom.xml file.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.2</version>
</dependency>
Output:
{"name":"Amarpreet","salary":22000.0,"age":22}
Output:
{"name":"Rashmi","salary":67000 .0,"age":30}
Output:
["Parampara",42,111000.0]
Output:
Rajinikanth 55000.0 66
Flexjson
The Flexjson is another lightweight library for serializing and deserializing Java objects into and from
JSON format. It allowscreation of both deep and shallow copies of objects. The depth to which an
object is serialized can be controlled with Flexjson and thus making it similar to lazy-loading,
allowing us to extract only the information that we need. This is not the case since we want an
entire object to be written to file, but it‘s good to know that it can do that.
If we know that we are going to use only a small amount of data in our application and we wish to
store or read it to and from JSON format, we should consider using Flexjson or Gson.
How to use Flexjson?
The Flexjson takes a different approach allowing us to control the depth to which it will serialize. It's
very similar in concept to lazy loading in Hibernate which allows us to have a connected object
model, but control what objects are loaded out of our database for performance. Let's look at a
simple example first to get a feel for how the library works. Say we are serializing an instance of
Animal. We might do it in the following way.
public String do( Object arg1, ... )
{
Animal a = ...load an animal...;
JSONSerializer serializer = new JSONSerializer();
return serializer.serialize( a );
}
Output:
{
"class": "Animal",
"name": "Xenial Xerus",
"nickname": "Wolf"
}
JSON-lib
JSON-lib is a Java library, based on the original work by creator of JSON, Douglas Crockford,
capable of transforming beans, maps, collections, Java arrays and XML to JSON and back again
to beans and DynaBeans.
If we are going to use big amounts of data and wish to store or read it to and from JSON format, we
should consider using Jackson or JSON-lib.
How to use this library ?
1. Here is our pom.xml:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
The latest version can be found in the Maven Central repository online. This package has already been
included in Android SDK, so we shouldn‘t include it while using the same.
2. JSON in Java [package org.json]
The JSON-Java library is also known as org.json (not Google‘s org.json.simple) provides us with
classes that are used to parse and manipulate JSON.
Furthermore, this library can also convert among JSON, XML, HTTP Headers, Cookies, Comma-
Delimited List or Text, etc.
Following are the classes used to JSON embedding in Java.
JSONObject – similar to Java‘s native Map like object which stores unsorted key-value pairs in
it.
JSONArray – This is ordered sequence of values similar to Java‘s native Vector class
implementation.
JSONTokener – This is a tool that breaks a piece of text into a series of tokens which can be
used by JSONObject or JSONArray to parse JSON strings from it.
CDL – This tool provides methods to convert comma-delimited text into a JSONArray and vice
versa.
Cookie – It is used to convert from JSON String to cookies and vice versa.
HTTP – It is used to convert from JSON String to HTTP headers and vice versa.
JSONException – This is subclass of Exception and a standard exception thrown by this
library.
JSONObject
The A JSONObject is an unsorted collection of key and value pairs, corresponding Java‘s native Map
implementations. Keys are unique Strings that cannot be null. The values can be anything from a
Boolean, Number, String, JSONArray or even a JSONObject.NULL object.
The A JSONObject can be represented by a String enclosed within curly braces { } with keys and
values separated by a colon, and pairs separated by a comma like general JSON format. It has
several constructors with which to construct a JSONObject. It also supports the following
methods:
get(String key) – It is used to get the object associated with the supplied key, throws
JSONException if the key is not found in it.
opt(String key)- It is used get the object associated with the supplied key, null otherwise.
put(String key, Object value) – It is used to insert or replace a key-value pair in current
JSONObject.
The put() method is an overloaded method which accepts a key of type String and multiple types for
the value.
Following are the operations supported by JSON library here.
1. Creating JSON Directly from JSONObject
The JSONObject explores an API similar to Java‘s Map interface. We can use the put( ) method and
supply the key and value as an argument:
JSONObject jo = new JSONObject();
jo.put("name", "Aniket");
jo.put("age", "28");
jo.put("city", "Pune");
There are seven different overloaded signatures of JSONObject.put() method are available. The data
present in the object will have the key only be unique, non-null String, the value can be anything.
The passed String argument must be a legal JSON string otherwise this constructor may throw a
JSONException.
In order to publish a service using JSON, at plain jsp project, it will need json library. We may use
any json library. Here we used json-simple. We need to download the library from Maven repository.
The Apache Tomcat 6 is also required, so jar file will put at lib folder, just paste and restart server.
<script>
function submitForm(){
var inp = $('#dept').val().toUpperCase();
$.ajax({
async: false,
type: "GET",
contentType: "application/json; charset=utf-8",
url: "services.jsp",
data: { dept: inp}
}).success(function(data){
var jsondata = JSON.parse(data);
loadData(jsondata);
$('#conCode').html(data);
}).fail(function(jqXHR, textStatus){
console.log("[AJAX] Error: JSON WSDL Lookup>>>" + textStatus);
}).done(function(){
console.log("[AJAX] Complete: JSON WSDL Lookup");
});
}
function loadData(datas){
var sb = '';
var table = $('#tableBody');
$('#json').show();
$('#table').show();
table.html('');
table.append(sb);
}
$(function(){
$('#conBtn').click(function(e){
e.preventDefault();
submitForm();
});
});
</script>
</body>
</html>
INSERT INTO 'employees' VALUES ('1', 'Akbar', 'IT', '301, Pimple Anex, Pune');
INSERT INTO 'employees' VALUES ('2', 'Baban', 'COMM', 'Rno. 34, Rajat Soc, Pune');
INSERT INTO 'employees' VALUES ('3', 'Chandrakant', 'IT', 'Katepuram Chowk, Pune');
INSERT INTO 'employees' VALUES ('4', 'Dattu', 'HR', 'Akashay Plaza First, Pune');
INSERT INTO 'employees' VALUES ('5', 'Eknath', 'FINANCE', 'Ambar Apartment, Pune');
In the above example our MySQL Database with database name is jspjson, username root, with no
password. The json-simple library is installed and setup first. The example at services can accept
more params and use more fun query. The main purpose is with response as JSON data, we could
retrieve it at jsp or android or anywhere we want.