Advanced Java Programming (J2Ee) : Bca/Bscit Sem 5
Advanced Java Programming (J2Ee) : Bca/Bscit Sem 5
UNIT 1
1 1
31-07-2024
INTRODUCTION TO J2EE
J2EE stands for Java 2 Platform, Enterprise Edition. J2EE is the standard platform for
developing applications in the enterprise and is designed for enterprise applications
that run on servers.
It is used to develop multi tier architecture-based applications. It is used to reduces
the cost and complexity of developing multi-tier services.
J2EE is a platform-independent environment used for configuring web-based
enterprise applications.
It contains several API, protocols, and run time environment for the development of
network-based web services.
It creates multi-tiered applications, large scale, reliable, and secure network
applications.
Advantages of J2EE:
Services of J2EE:
J2EE supports pure HTML as well as Java Applets. It is based on Java Server Pages
and Servlet code to create applications.
EJB (Enterprise Java Beans) provides a separate layer for storing the logic.
JDBC (Java Database Connectivity) creates a connection between an application and
a database.
1 2
31-07-2024
Two-Tier Architecture
The 2-tier Architecture is based on a client-server
machine.
In this type of architecture, the applications on client-
side interact directly with the database present at the
server-side.
This interaction between client and server uses
Application Program Interface like ODBC and JDBC.
ODBC − Open Database Connectivity
JDBC − Java Database Connectivity
When there are many users at client side to access the
database, this architecture gives a poor performance.
Three-Tier Architecture
Application which is divided into 3 tier namely Client tier, middle tier, and database
tier is known as Three Tier Architecture.
Three-Tier Architecture is an is a well-established software application design pattern
which will organizes the application in the three logical and physical computing tiers
as following:
1. Presentation Tier
It is the user interface and topmost tier in the architecture. Its purpose is to take
request from the client and displays information to the client. It communicates with
other tiers using a web browser as it gives output on the browser.
If we talk about Web-based tiers then these are developed using languages like-
HTML, CSS, JavaScript.
1 3
31-07-2024
2. Application Tier
It is the middle tier of the architecture also known as the logic tier as the
information/request gathered through the presentation tier is processed in detail
here. It also interacts with the server that stores the data. It processes the client’s
request, formats, it and sends it back to the client. It is developed using languages
like- Python, Java, PHP, etc.
3. Data Tier
It is the last tier of the architecture also known as the Database Tier. It is used to
store the processed information so that it can be retrieved later on when required. It
consists of Database Servers like- Oracle, MySQL, DB2, etc.
N-Tier Architecture
N-tier architecture is also called multi-tier architecture because the software is
engineered to have the processing, data management, and presentation functions
physically and logically separated.
multi-tier architecture is a cost-effective way to build an application that is flexible,
scalable, and responsive to the expectation of clients.
1 4
31-07-2024
It consists of programs that interact with the users. These components take a
request from the user to forward to software on the component that processes the
request and returns the result to the client program. Components under Client tier in
J2EE Specification:
Applet Client- It is a component used by Web clients that operate within Applet
Container. It is a Java-enabled web browser.
Application Client –It is a Java application that operates within the application
container. It is the Java Runtime Environment (JRE).
2. Web Tier
It provides the Internet functionality to the J2EE application. The components on the
web tier use HTTP to receive requests and send responses to the client that resides
on the tier. Web-Tier Provides services to Client-tier using HTTP.
The intermediary activities are:
• Accepting info from other applications sent using POST, GET, and PUT using HTTP.
• Transmit data such as images and dynamic content.
Components of Web Tier:
Servlets
Java server pages (JSP)
1 5
31-07-2024
J2EE Applications
J2EE applications are made up of components such as Java Server Pages (JSP),
Java servlets, and Enterprise JavaBeans (EJB) modules. These components enable
software developers to build large-scale, distributed applications. Developers
package J2EE applications in Java Archive (JAR) files (like zip files), which can be
distributed to production sites. Administrators install J2EE applications onto the
Application Server by deploying J2EE JAR files onto one or more server instances.
1 6
31-07-2024
Containers
Each server instance includes two containers: web and EJB. A container is a runtime
environment that provides services such as security and transaction management to
J2EE components. Web components, such as Java Server Pages and servlets, run
within the web container. Enterprise JavaBeans run within the EJB container.
J2EE Services
The J2EE platform provides services for applications, including:
Web Services
Clients can access a J2EE application as a remote web service in addition to
accessing it through HTTP, and JMS. A J2EE application can also act as a client to
web services, which would be typical in network applications.
Web Services Description Language (WSDL) is an XML format that describes web
service interfaces. The Application Server distributes web services interface
descriptions using a registry that other applications can access through the Java API.
1 7
31-07-2024
Client Access
Clients can access J2EE applications in several ways. Browser clients access web
applications using hypertext transfer protocol (HTTP). For secure communication,
browsers use the HTTP secure (HTTPS) protocol that uses secure sockets layer
(SSL).
They can access applications and web services using HTTP/HTTPS, and JMS. They
can use JMS to send messages to and receive messages from applications and
message-driven beans.
JavaMail - Through the JavaMail API, applications can connect to a Simple Mail
Transport Protocol (SMTP) server to send and receive email.
1 8
31-07-2024
Servlets
Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, and then send a response back
to the web server.
JSP
JSP stands for Java Server Pages. It is a server-side technology which is used for
creating web applications. It is used to create dynamic web content. JSP consists of
both HTML tags and JSP tags. In this, JSP tags are used to insert JAVA code into
HTML pages. It is an advanced version of Servlet Technology.
EJB
Enterprise Java Beans (EJB) is the Java APIs for standard manufacture of enterprise
software. EJB is a server-side software element that summarizes business logic of
an application. To run EJB application we need an application server.
JMS
JMS (Java Message Service) is an API that provides the facility to create, send and
read messages. Messaging is a technique to communicate applications or software
components. JMS is mainly used to send and receive message from one application
to another.
JavaMail
The JavaMail API provides a framework to build mail and messaging applications.
The JavaMail API provides a set of abstract classes defining objects that create a
mail system.
1 9
31-07-2024
JSF
Java Server Faces (JSF) technology includes a set of APIs, which represent different
UI components. These APIs further help in handling events on the UI components
and validate user inputs through the UI components. JSF framework provides the
flexibility of creating simple as well as complex applications.
JNDI
The interface used by the Java programming language is by the name Java Naming
and Directory Interface (JNDI). It is an API that communicates with servers and uses
naming conventions to get files from databases or files.
INTRODUCTION TO CONTAINERS
• The application server which controls and provides services through an interface
is called a container.
• Containers are interface between a component and client.
• It is a platform or place which stores and supports component.
• The J2EE container helps in the deployment and execution of J2EE components.
• In J2EE there are 5 containers types.
1 10
31-07-2024
Web container:
This container contains A component that works on the server-side.
A web application executes within a web container of a web server which is also
known as servlet container.
Web container manages the execution of the JSP page and servlet components for
java enterprise edition(J2EE) applications.
1 11
31-07-2024
Tomcat Installation
Installing Tomcat on Windows is easy. It is a step-by-step process. Go to the Apache
Tomcat website.
Once you go there, check for the recent Tomcat version and download it. When the
download is done, you need to set up essential environment variables.
After setting up the environment variables, you can start Tomcat. You can start
Tomcat in different ways. It can be run as a service or the startup scripts that are
given can be used. You can also start it in manual mode from the command line.
1 12
31-07-2024
You first need to build an application as a WAR file to get it deployed. The WAR file
contains all the necessary components of your web application, including servlets,
JSP files, HTML files, and resource files.
To create war file, go inside the project directory of your project (outside the WEB-
INF), then write the following command in CMD:
jar -cvf projectname.war *
Once you have the WAR file, copy it to the "web apps" directory within the Tomcat
installation directory. Tomcat automatically deploys the application by unpacking the
WAR file and creating the necessary directory structure.
JDBC ARCHITECTURE
1 13
31-07-2024
The JDBC API: The JDBC API allows Java programs to execute SQL statements and
retrieve results. Some of the important interfaces defined in JDBC API are as follows:
Driver interface , ResultSet Interface , RowSet Interface , PreparedStatement
interface, Connection inteface, and Classes defined in JDBC API are as follows:
DriverManager class, Types class, Blob(Binary Large Objects) class, Clob(Character
Large Objects) class.
JDBC drivers: To communicate with a data source through JDBC, you need a JDBC
driver that intelligently communicates with the respective data source.
Two-tier model: A java application communicates directly to the data source. The
JDBC driver enables the communication between the application and the data
source. When a user sends a query to the data source, the answers for those
queries are sent back to the user in the form of results.
Three-tier model: In this, the user’s queries are sent to middle-tier services, from
which the commands are again sent to the data source. The results are sent back to
the middle tier, and from there to the user.
1 14
31-07-2024
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC
function calls. Type-1 driver is also called Universal driver because it can be used to
connect to any of the databases.
The Native API driver uses the client -side libraries of the database. This driver
converts JDBC method calls into native calls of the database API. In order to interact
with different database, this driver needs their local API, that’s why data transfer is
much more secure as compared to type-1 driver. This driver is not fully written in
Java that is why it is also called Partially Java driver.
1 15
31-07-2024
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. Here all the
database connectivity drivers are present in a single server, hence no need of
individual client-side installation.
Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known
as Thin Driver.
Class/interface Description
DriverManager This class manages the JDBC drivers. You need to register
your drivers to this. It provides methods such as
registerDriver() and getConnection().
Driver This interface is the Base interface for every driver class i.e.
If you want to create a JDBC Driver of your own, you need to
implement this interface. If you load a Driver class
(implementation of this interface), it will create an instance
of itself and register with the driver manager.
1 16
31-07-2024
Class/interface Description
CallableStatement Using an object of this interface you can execute the stored
procedures. You can create a CallableStatement using the
prepareCall() method of the Connection interface.
Class/interface Description
1 17
31-07-2024
Import the packages − Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, import java.sql.* will use.
Open a connection − Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the
database.
Execute a query − Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Extract data from result set − Requires that you use the appropriate ResultSet
method to retrieve the data from the result set.
Clean up the environment − Requires closing all database resources.
index.html
<h1> <a href="Data">Show data from Database</a></h1>
web.xml
<web-app>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/Data</url-pattern>
</servlet-mapping>
</web-app>
1 18
31-07-2024
JDBCServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
try {
Connection connection;
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/dbname", "root", "");
Statement statement;
statement = connection.createStatement();
ResultSet resultSet;
resultSet = statement.executeQuery("select * from tablename");
int id;
String name;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<h1>Student Information</h1>");
out.println("<table border='1'><tr><th>Id</th>");
out.println("<th>Name</th></tr>");
1 19
31-07-2024
while (resultSet.next()) {
id = resultSet.getInt("id");
name = resultSet.getString("stuname");
out.println("<tr><td>"+id+"</td>");
out.println("<td>"+name+"</td></tr>");
}
out.println("</table>");
resultSet.close();
statement.close();
connection.close();
}
catch (IOException | ClassNotFoundException | SQLException exception) {
System.out.println(exception);
}
}
}
The statement interface is used to create SQL basic statements in Java it provides
methods to execute queries with the database.
Once a connection is obtained, we can interact with the database.
There are different types of statements that are used in JDBC as follows:
Create Statement
Prepared Statement
Callable Statement
1. Create a Statement:
From the connection interface, you can create the object for this interface. It is
generally used for general–purpose access to databases.
1 20
31-07-2024
Syntax:
Statement statement = connection.createStatement();
Implementation:
Once the Statement object is created, there are three ways to execute it.
boolean execute(String SQL): If the ResultSet object is retrieved, then it returns true
else false is returned. Is used to execute SQL DDL statements or for dynamic SQL.
int executeUpdate(String SQL): Returns number of rows that are affected by the
execution of the statement, used when you need a number for INSERT, DELETE or
UPDATE statements.
Example:
Statement statement = con.createStatement();
String sql = "select * from table_name";
ResultSet result = statement.executeQuery(sql);
2. Prepared Statement:
It represents a recompiled SQL statement, that can be executed many times. This
accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED
STATEMENT at run time.
1 21
31-07-2024
execute(): This returns a boolean value and executes a static SQL statement that is
present in the prepared statement object.
executeUpdate(): Returns the number of rows affected by the DML statements such
as INSERT, DELETE, and more that is present in the current Prepared Statement.
Example:
3. Callable Statement:
Callable Statements are stored procedures which are a group of statements that we
compile in the database for some task, they are beneficial when we are dealing with
multiple tables with complex scenario & rather than sending multiple queries to the
database.
The Callable Statement interface provided by JDBC API helps in executing stored
procedures.
1 22
31-07-2024
Example:
Statement s = con.createStatement();
CallableStatement cs = con.prepareCall("{call peopleinfo(?,?)}");
cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result = s.executeQuery("select * from people");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");
System.out.println("Connection established.");
} catch(ClassNotFoundException | SQLException exception){
System.out.println(exception);
}
1 23
31-07-2024
try {
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.setInt(3, 123);
statement.executeUpdate();
System.out.println("Record created.");
} catch(ClassNotFoundException | SQLException exception){
System.out.println(exception);
}
3. Read a record
To read a record from the database, you will need to use an SQL SELECT statement.
try {
String sql = "SELECT column1, column2 FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
ResultSet result = statement.executeQuery();
if (result.next()) {
String column1 = result.getString("column1");
String column2 = result.getString("column2");
System.out.println("Column 1: " + column1);
System.out.println("Column 2: " + column2);
}
} catch(ClassNotFoundException | SQLException exception){
System.out.println(exception);
}
1 24
31-07-2024
4. Update a record
To update a record in the database, you will need to use an SQL UPDATE statement
and execute it using the connection object.
try {
String sql = "UPDATE table_name SET column1 = ?, column2 = ? WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "new_value1");
statement.setString(2, "new_value2");
statement.setInt(4, 1);
statement.executeUpdate();
System.out.println("Record updated.");
} catch(ClassNotFoundException | SQLException exception){
System.out.println(exception);
}
5. Delete a record
To delete a record from the database, you will need to use an SQL DELETE
statement and execute it using the connection object.
try {
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
statement.executeUpdate();
System.out.println("Record deleted.");
} catch(ClassNotFoundException | SQLException exception){
System.out.println(exception);
}
1 25
31-07-2024
CRUD Example:
Index.html
<h1>
<a href="ShowClass"><input type="button" value="Show"></a>
<a href="InsertClass"><input type="button" value="Insert"/></a>
<a href="UpdateClass"><input type="button" value="Update"/></a>
<a href="DeleteClass"><input type="button" value="Delete"/></a>
</h1>
1 26
31-07-2024
<servlet-mapping>
<servlet-name>ShowClass</servlet-name>
<url-pattern>/ShowClass</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>InsertClass</servlet-name>
<url-pattern>/InsertClass</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UpdateClass</servlet-name>
<url-pattern>/UpdateClass</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeleteClass</servlet-name>
<url-pattern>/DeleteClass</url-pattern>
</servlet-mapping>
</web-app>
InsertClass.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
1 27
31-07-2024
if(count >0){
p.println("Data inserted");
}
}
catch(ClassNotFoundException | SQLException exception){
System.out.println(exception);
}
}
}
ShowClass.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
1 28
31-07-2024
Statement stmt;
ResultSet rs;
stmt = con.createStatement();
rs = stmt.executeQuery("select * from user");
int id;
String name;
while(rs.next()){
id = rs.getInt("id");
name = rs.getString("uname");
p.println("Id: "+id+ "Name: "+name);
}
}
catch(ClassNotFoundException | SQLException exception){
System.out.println(exception);
}
}
}
UpdateClass.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
1 29
31-07-2024
pst = con.prepareStatement(sql);
pst.setString(1, "Hardik");
pst.setInt(2, 4);
DeleteClass.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
1 30
31-07-2024
pst = con.prepareStatement(sql);
pst.setInt(1, 4);
END OF UNIT 1
1 31