Rudra Ajp
Rudra Ajp
CERTIFICATE
Place: ___________
Date: ___________
Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant competencies
in psychomotor domain. By keeping in view, GTU has designed competency focused outcome-
based curriculum for engineering degree programs where sufficient weightage is given to
practical work. It shows importance of enhancement of skills amongst the students and it pays
attention to utilize every second of time allotted for practical amongst students, instructors and
faculty members to achieve relevant outcomes by performing the experiments rather than having
merely study type experiments. It is must for effective implementation of competency focused
outcome-based curriculum that every practical is keenly designed to serve as a tool to develop
and enhance relevant competency required by the various industry among every student. These
psychomotor skills are very difficult to develop through traditional chalk and board content
delivery method in the classroom. Accordingly, this lab manual is designed to focus on the
industry defined relevant outcomes, rather than old practice of conducting practical to prove
concept and theory.
By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each experiment
in this manual begins with competency, industry relevant skills, course outcomes as well as
practical outcomes (objectives). The students will also achieve safety and necessary precautions
to be taken while performing practical.
This manual also provides guidelines to faculty members to facilitate student centric lab activities
through each experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.
Advance Java Programming is an Elective course. It covers various java based technologies like
socket, JDBC, Servlet and JSP which help students to develop enterprise application. Web
application based on Java uses Servlet, JSP, JSF etc. To store the data database connectivity and
database JDBC component is needed. Networking components are needed to transfer data over
network. Model-View-Controller (MVC) architecture gives flexibility and makes the web
applications loosely coupled.
Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal of
errors if any.
Advance Java Programming 3160707
DTE’s Vision
Institute’s Vision
Institute’s Mission
Department’s Vision
Department’s Mission
The following industry relevant competency are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to develop web application using Netbeans/Ecllipse IDE
2. Will be able to use MVC architecture for application development
3. Will be able to use JSF and Hibernate framework
1 In java console application, provide the user with following options: add movie, view
movie, modify movie details, delete movie details. On entering a particular option on
the console by user, perform appropriate operation and display the success/failure or
any output on your console.
2 Make the practical 1 application as server for sending/receiving strings. Create a client
application that will send a search movie string to the server application and server will
replay with the matching movie name “string” back to the client application after
fetching from the database.
3 Modify practical 1 by replacing the console based user interface to a web based user
interface. Use a servlet.
4
Modify the practical 4 to use JSP instead of Servlet.
5
Use JSF framework to replace JSP and calculate the reduction in programming
6
Make custom tag for a component that will be able to add/view/delete/modify Records
7 Use Object Relational Mapping and based on that prepare one configuration file along
with the hibernet mapping file for 1 table of the application and test its working by
replacing SQL to HQL.
8 Use Hibernet framework to replace JDBC calls and calculate the reduction in
programming efforts for the entire application
9 Use Spring or any other MVC architecture and implement the Interface in that
architecture that supports multi-tier architecture.
10
Compare and analyze the JSF with the Spring/any other framework.
Index
(Progressive Assessment Sheet)
Experiment No: 1
In java console application, provide the user with following options: add product, view product,
modify product details, delete product details. On entering a particular option on the console by
user, perform appropriate operation and display the success/failure or any output on your
console.
Date:
Theory:
A JDBC program comprises the following FIVE steps:
• STEP 1: Allocate a Connection object, for connecting to the database server.
• STEP 2: Allocate a Statement object, under the Connection created earlier, for holding a SQL
command.
• STEP 3: Write a SQL query and execute the query, via the Statement and Connection created.
• STEP 4: Process the query result.
• STEP 5: Close the Statement and Connection to free up the resources.
Procedure:
1. Create a database for your project
2. Write java program to interact with tables in database using Type 4 JDBC driver.
Observations:
import java.sql.*;
import java.util.Scanner;
public class s {
Statement st = con.createStatement();
st.execute(insertQuery); // Execute query
ResultSet rs = st.executeQuery(getIdQuery);
rs.next();
final int id = rs.getInt("id");
System.out.println("Entered Data Successfully with Generated id " + id);
System.out.println();
st.close();
} catch (Exception e) {
System.out.println(e);
}
} else if (choice == 2) { // Read the Database Records
String selectQuery = "SELECT * FROM product_details";
// Read Data with while loop
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(selectQuery);
System.out.println("-----------------------------------");
System.out.println(" Id Name Price Stock");
System.out.println("-----------------------------------");
while (rs.next()) { // Particular Record
System.out.println(" " + rs.getInt("id") + " "
+ rs.getString("name") + s.getSpace(rs.getString("name").length())
+ rs.getString("price") + s.getSpace(rs.getString("price").length())
+ rs.getString("stock") + s.getSpace(rs.getString("stock").length()));
}
System.out.println();
st.close();
} catch (Exception e) {
System.out.println(e);
}
} else if (choice == 3) { // Update Product Price and Stock with id
int id, stock, price;
System.out.print("Enter productID to Update : ");
id = sc.nextInt();
System.out.print("Enter Updated Stock : ");
stock = sc.nextInt();
System.out.print("Enter Updated Price : ");
price = sc.nextInt();
String updateQuery = String.format("UPDATE `product_details` SET
`price`='%d',`stock`='%d' WHERE id=%d",
price, stock, id);
try {
Statement st = con.createStatement();
// check Database Updation after deletion of Record
if (st.executeUpdate(updateQuery) != 0) {
System.out.println("Inventory Updated Successfully");
} else {
System.out.println("Inventory Product Not Found");
}
st.close();
} catch (Exception e) {
System.out.println(e);
}
} else if (choice == 4) { // Delete the record with id
int id;
System.out.print("Enter productID to Delete : ");
id = sc.nextInt();
String deleteQuery = String.format("DELETE FROM `product_details`
WHERE id=%d", id);
try {
Statement st = con.createStatement();
// check Database Updation after deletion of Record
if (st.executeUpdate(deleteQuery) != 0) {
System.out.println("Inventory Deleted Successfully");
} else {
System.out.println("Inventory Product Not Found");
}
st.close();
} catch (Exception e) {
System.out.println(e);
}
} else {
System.out.println("Please Enter Valid Operation Choice");
}
}
}
}
Output:
Conclusion:
Quiz:
- Requires an ODBC driver manager and an ODBC driver, which may be a limitation
depending on the platform.
- It's platform-dependent and not suitable for deployment in environments where ODBC
is not available or is deprecated.
The main purpose of using parameterized queries is to prevent SQL injection attacks and
improve performance by allowing the database engine to cache query execution plans.
1. Create a Connection: First, establish a connection to your database using JDBC. You
typically use the `DriverManager.getConnection()` method to create a connection
object.
2. Prepare the Query: Instead of constructing a SQL query string directly, use a
`PreparedStatement` object to create a parameterized query. You define placeholders
in the query where values will be inserted later.
3. Set Parameter Values: Set values for each parameter in the prepared statement using
methods like `setString()`, `setInt()`, etc. These methods correspond to the data types
of the parameters in your query.
4. Execute the Query: Once all parameters are set, execute the prepared statement using
the `executeQuery()` method for queries that return a result set or `executeUpdate()`
for queries that perform updates.
5. Process Results (if applicable): If the query returns a result set, iterate over the result
set and process the data accordingly. Otherwise, handle any exceptions that may
occur during execution.
1. DriverManager:
- This class manages a list of database drivers, which are responsible for establishing
database connections.
- It provides methods like `getConnection` to establish connections to a database using a
JDBC URL, username, and password.
2. Connection:
3. Statement:
- This interface represents a static SQL statement that can be executed against a database.
- Allows execution of SQL queries using the `executeQuery` method, which returns a
ResultSet containing the query results.
- Also supports executing SQL commands that don't produce a ResultSet using methods
like `executeUpdate`.
4. PreparedStatement:
- Extends the Statement interface and represents a precompiled SQL statement.
- Allows the use of parameterized queries, improving performance and security by
preventing SQL injection attacks.
- Provides methods for setting parameter values using placeholders and executing the
statement.
5. CallableStatement:
- Extends the PreparedStatement interface and represents a stored procedure call.
- Allows execution of stored procedures defined in the database, with support for input
and output parameters.
- Useful for invoking database functions or procedures from Java code.
6. ResultSet:
- Represents a set of rows retrieved from a database in response to a query.
- Provides methods for navigating through the result set, accessing column values, and
performing operations like iteration and scrolling.
7. ResultSetMetaData:
- Provides information about the columns in a ResultSet, such as column names, types,
and properties.
- Allows dynamic retrieval of metadata about the result set, enabling more flexible
handling of query results.
8. DatabaseMetaData:
- Provides information about the database, such as its features, capabilities, and structure.
- Allows retrieval of metadata about database objects like tables, views, procedures, and
supported SQL syntax.
9. Savepoint:
- Represents a point within a transaction to which you can roll back if necessary.
- Enables finer control over transaction management by allowing partial rollback of
changes.
Suggested Reference:
JDBC™ API Tutorial and Reference, Third Edition, Maydene Fisher, Jon Ellis, Jonathan Bruce,
Addison Wesley
Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)
Rubrics 1 2 3 4 5 Total
Marks
Experiment No: 2
Make the practical 1 application as server for sending/receiving strings. Create a client
application that will send a search product string to the server application and server will
replay with the matching product name “string” back to the client application after fetching
from the database.
Date:
Objectives: (a) To show how to implement TCP/UDP communication between two java
program using Socket/ ServerSocket and DatagramSocket/DatagramPacket.
(b) To show how to implement client server relationship between programs.
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse
Theory:
Java Networking Terminology: IP Address, Protocol, Port Number, MAC Address, Connection-
oriented and connection-less protocol, Socket
2) Protocol: A protocol is a set of rules basically that is followed for communication. For example:
TCP, FTP, Telnet, SMTP, POP etc.
3) Port Number: The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications. The port number is associated with the IP address
for communication between two applications.
4) MAC Address: MAC (Media Access Control) address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
java.net package
The java.net package can be divided into two sections: A Low-Level API: It deals with the
abstractions of addresses i.e. networking identifiers, Sockets i.e. bidirectional data communication
mechanism and Interfaces i.e. network interfaces .A High Level API: It deals with the abstraction
of URIs i.e. Universal Resource Identifier, URLs i.e. Universal Resource Locator, and
Connections i.e. connections to the resource pointed by URLs.
Procedure:
1. Create a Sender/Client program and Receiver/Server program.
2. Compile them
3. Run Server/Receiver program first and then run Client/Sender program
Observations:
// Server Side
import java.io.*;
import java.sql.*;
import java.net.*;
if (choice[0].equals("1")) {
String name;
name = choice[1];
stock = Integer.parseInt(choice[2]);
price = Integer.parseInt(choice[3]);
try {
Statement st = con.createStatement();
st.execute(insertQuery);
ResultSet rs = st.executeQuery(getIdQuery);
rs.next();
} catch (Exception e) {
System.out.println(e);
}
} else if (choice[0].equals("2")) {
String selectQuery = "SELECT * FROM product_details";
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(selectQuery);
} catch (Exception e) {
System.out.println(e);
}
} else if (choice[0].equals("3")) { // Update Product Price and Stock with id
int id, stock, price;
id = Integer.parseInt(choice[1]);
stock = Integer.parseInt(choice[2]);
price = Integer.parseInt(choice[3]);
try {
Statement st = con.createStatement();
st.close();
} catch (Exception e) {
System.out.println(e);
}
try {
Statement st = con.createStatement();
st.close();
} catch (Exception e) {
System.out.println(e);
}
} else {
result = "STOP";
}
return result;
}
while (cont) {
String str = (String) din.readUTF();
if (result == "STOP") {
break;
}
}
din.close();
dout.close();
ss.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
// Client Side
import java.io.*;
import java.net.*;
import java.util.Scanner;
while (true) {
int c = sc.nextInt();
query += " " + name + " " + stock + " " + price;
break;
case 2:
break;
case 3:
System.out.print("Enter productID to Update : ");
String id = sc.next();
System.out.print("Enter Updated Stock : ");
String stockU = sc.next();
System.out.print("Enter Updated Price : ");
String priceU = sc.next();
query += " " + id + " " + stockU + " " + priceU;
break;
case 4:
System.out.print("Enter productID to Delete : ");
String idD = sc.next();
System.out.println(str2);
if (c > 4 || c < 1) {
break;
}
}
dout.flush();
dout.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
22
Conclusion:
• The Java network programming practical demonstrates the versatility of Java in
creating robust networked applications. Through socket programming, it
facilitates communication between distributed systems, enabling seamless data
exchange over networks. The project's implementation showcases Java's
networking APIs, empowering developers to build scalable and efficient
networked applications. Overall, the Java network programming practical
underscores the language's capability in handling complex networking tasks with
simplicity and reliability.
Quiz:
1. Explain InetAddress class and its use in network programming.
o `InetAddress` is a class in Java that represents an Internet Protocol (IP) address. It
provides methods for working with IP addresses, such as retrieving hostnames, IP
addresses, and checking reachability.
4. Working with IPv6 Addresses: `InetAddress` supports both IPv4 and IPv6
addresses transparently. You can use it to work with IPv6 addresses as easily as
IPv4 addresses.
2. With the help of example show the use of URL and URLConnection class.
o The `URL` and `URLConnection` classes in Java are used to handle URLs and
establish connections to resources on the internet.
Here's how you might typically use them:
1. Creating a URL Object: You create a `URL` object by passing the URL string
to its constructor. This URL object represents the location of a resource on the
internet, such as a web page.
2. Opening a Connection: Once you have a `URL` object, you can call the
`openConnection()` method to establish a connection to the resource specified
by the URL. This returns a `URLConnection` object.
3. Setting Request Properties (optional): You can set properties of the connection,
such as the user-agent string or request headers, using methods provided by
the `URLConnection` class.
4. Reading Data from the Connection: After establishing the connection, you can
read data from the resource using input streams obtained from the
`URLConnection` object.
5. Closing the Connection: Once you're done with the connection, make sure to
close it to release system resources.
1. DatagramSocket:
- `DatagramSocket` represents a socket for sending and receiving UDP packets. It is
used to establish communication endpoints.
- You create a `DatagramSocket` object to create a socket on a specific port for
sending and receiving UDP packets.
- It provides methods to send and receive `DatagramPacket` objects.
- `DatagramSocket` is connectionless, meaning it does not establish a persistent
connection between the client and server.
- You can create multiple `DatagramSocket` objects on the same machine, each
bound to a different port, to handle multiple simultaneous UDP communications.
2. DatagramPacket:
- `DatagramPacket` represents a UDP packet containing data to be sent or received.
It encapsulates the data, destination address, and port number.
- You create a `DatagramPacket` object to prepare data for sending or to hold
received data.
- For sending, you specify the data to be sent, the destination address, and port
number.
- For receiving, you create a `DatagramPacket` object to hold the incoming data and
provide it to the `DatagramSocket` for receiving.
Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)
Rubrics 1 2 3 4 5 Total
Marks
Experiment No: 3
Modify practical 1 by replacing the console based user interface to a web based user interface. Use
a servlet.
Date:
Objectives: (a) implement webpages using HTML for collecting user input.
(b) able to do server side programming using Servlet to process user input.
(c) To show how Servlet can interact with Database
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Apache Tomcat Server,
Netbeans/eclipse, Oracle Xpress edition 11g, Type4 JDBC driver for Oracle
Theory:
• Servlet technology is used to create web application
• Servlet technology is robust and scalable because of java language.
• Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a
server-side programming language.
• There are many interfaces and classes in the servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse etc.
Servlet APIs
• javax.servlet and javax.servlet.http
• javax.servlet package contains many interfaces and classes that are used by the servlet or
web container.
• javax.servlet.http package contains interfaces and classes that are responsible for http
requests
The servlet can be created by three ways:
By implementing Servlet interface,
By inheriting GenericServlet class,
By inheriting HttpServlet class
• The mostly used approach is by extending HttpServlet.
The steps are as follows:
• Create a directory structure
• Create a Servlet
• Compile the Servlet
• Create a deployment descriptor
• Start the server(Apache tomcat) and deploy the project
• Access the servlet
Safety and necessary Precautions:
1. Make sure the database server and application server are started before running the
program
2. Put you application directory in to root directory of Tomcat server
3. To run the program use any web browser
4. Handle all necessary compile time Exception
Procedure:
1. Create a directory structure for web application in application folder.
2. Create database for your project
3. Create an html file asking for data from user and submit those data to servlet in application
folder
4. Create a servlet class to receive the input and process it as per your requirement, Also this
servlet program can interact with database using Type 4 JDBC driver.
5. Prepare web.xml file to put deployment descriptor
6. Compile to servlet program
7. Put application folder into root directory of application server( wepapps folder of Tomcat
server)
8. Open any web browser and run the program by typing url in address bar.
Observations:
// INDEX.html
<html>
<body>
<h2>Servlet Example!</h2>
<a href="create.html"
><button style=" background-color: #55c2da; width: 250px; height: 50px; margin-
right: 100px; "> Create
</button></a>
<a href="./view">
<button type=""style="background-color: #55c2da;width: 250px; height: 50px;margin-
right: 100px; "> Read
</button></a>
<a href="update.html">
<button style="
background-color: #55c2da;
width: 250px;
height: 50px;
margin-right: 100px;
">
Update </button></a>
<a href="delete.html">
<button style="
background-color: #55c2da;
width: 250px;
height: 50px;
margin-right: 100px;
">
Delete
</button></a>
</body>
</html>
// Create.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product Inventory</title>
</head>
<style>
input[type=text], select { width: 100%;padding: 12px 20px;margin: 8px 0;display: inline-
block;border:
1px solid #ccc;border-radius: 4px;box-sizing: border-box;
}
input[type=number],select {
width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid
#ccc;border-
radius: 4px; box-sizing: border-box;}
input[type=submit] {
width: 100%; background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0;
border:
none; border-radius: 4px; cursor: pointer;
}
input[type=submit]:hover { background-
color: #45a049; }
</style>
<body>
<div style="border-radius:5px;background-
color:#f2f2f2;padding:20px;"> <form action="create"
method="post" >
<label for="p_name">Product name:</label><br>
<input type="text" id="p_name" name="p_name" placeholder="Product name..."
required><br> <label for="p_stock">Enter Stock:</label><br>
<input type="number" id="p_stock" name="p_stock" placeholder="Quantity..."
required><br> <label for="p_price">Enter Price:</label><br>
<input type="number" id="p_price" name="p_price" placeholder="Price..." required><br>
//delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete</title>
</head>
<style>
input[type="number"],
select {width: 50%;padding: 12px 20px;margin: 8px 0;display: inline-block;border:
1px solid
#ccc;border-radius: 4px;box-sizing: border-box;}
input[type="submit"] {
width: 50%;background-color: #4caf50;color: white;padding: 14px 20px;margin:
8px 0;border:
none;border-radius: 4px;cursor: pointer;}
</style>
<body>
<div>
<form action="delete" method="post">
<center><label for="p_id">Product
id:</label><br />
<input type="number" id="p_id" name="p_id" placeholder="Product Id..."/>
</center>
<br/>
</form>
</div>
</body>
</html>
// updat
e.html
<!DOC
TYPE
html>
<html
lang="e
n">
<head>
<meta
charset="UTF-
8" />
<title>Update
</title>
</head>
<style>
input[type
="number"
], select {
width: 100%;padding: 12px 20px;margin: 8px 0;display: inline-block;border: 1px solid
#ccc;border-radius: 4px;box-sizing: border-box;}
input[type="submit"] {
width: 100%;background-color: #4caf50;color: white;padding: 14px 20px;margin: 8px
// create.java
package com.test.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
pre.setString(1,pName);
pre.setInt(2,Integer.parseInt(pStock));
pre.setDouble(3,Double.parseDouble(pPrice));
pre.execute();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
//delete.java
package com.test.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
pre.setInt(1,Integer.parseInt(pId));
pre.execute();
System.out.println("Product Delete Sucessfully");
} catch (Exception e) {
// e.printStackTrace(e.mesa);
System.out.println(e.getMessage());
}
}
}
//service.java
package com.test.servlet;
import java.sql.*;
try {
Connection con = DriverManager.getConnection(url, username,
password); Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT * FROM inventory ");
while (rs.next()) {
size++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
product pro = new product(null,0,0);
try {
rt);
start =
start +
1;
return pro = new product(rs.getString(2), (int) rs.getDouble(4), rs.getInt(3));
}
System.out.println(start);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return null;
}
}
//update.java
package com.test.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
public class update extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException,ServletException,RuntimeException{
try {
String pId = req.getParameter("p_id");
String pStock = req.getParameter("p_stock");
String pPrice = req.getParameter("p_price");
String url = "jdbc:mysql://localhost:3306/advanejava";
String username = "root";
String password = "Firebase";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, username, password);
pre.setDouble(1,Double.parseDouble(pPrice));
pre.setInt(2,Integer.parseInt(pStock));
pre.setInt(3,Integer.parseInt(pId));
pre.executeUpdate();
System.out.println("Data Added Successfully");
} catch (Exception e) {
System.out.println(e.get
Message());
}
}
}
//view.java
package com.test.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// super.doPost(req, resp);
int size = 0;
while(rs.next()){
size++;
}
out.println("<html>");
out.println("<body>");
out.println("<table>");
out.println("<tr>");
out.println("<th> Product Name </th>");
out.println("<th> Price </th>");
out.println("<th> Qunatity </th>");
out.println("</tr>");
int start = 1;
product pr;
while (start <= size) {
pr = ser.printData();
// System.out.println(trx.getUserId());
out.println("<tr>");
out.println("<td>" + pr.getProductName() + "</td>");
out.println("<td>" + pr.getProductPrize() + "</td>");
out.println("<td>" + pr.getProductStock() + "</td>");
out.println("</tr>");
start++;
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
} catch (SQLException e) {
throw new RuntimeException(e);
} }}
OUTPUT:
Home Page
Add Item
Read Item
Update Item
Delete Item
Conclusion:
This are servlet class using this servlet class Make a interface and make form in the interface. Now
if user add the data in the form and select the add Data and that Data add in the Database and if
user wish to delete data than select delete and than Data was deleted and many other operation can
do.
Quiz:
1. List various characteristics of Enterprise application.
o Enterprise applications are large-scale software systems designed to support the
complex needs of organizations. Here are various characteristics typically
associated with enterprise applications:
2) Reliability: They are highly reliable and robust, ensuring minimal downtime and
consistent performance even under heavy loads.
4) Integration: They often integrate with various systems and technologies within an
organization, such as databases, legacy systems, third-party applications, and
external APIs.
8) High Performance: They are optimized for performance, ensuring fast response
times and efficient resource utilization.
10) Analytics and Reporting: They provide extensive analytics and reporting
capabilities to help organizations derive insights from their data and make
informed business decisions.
The servlet life cycle is the process that a servlet goes through from the time it is
loaded to the time it is destroyed.
The following are the steps in the servlet life cycle:
• The servlet container loads the servlet class.
• The servlet container calls the servlet's service() method to process a request.
• The servlet container calls the servlet's destroy() method when the servlet is no
longer needed.
The init() method is called only once, when the servlet is first loaded. The
service() method is called for every request that is made to the servlet. The
destroy() method is called when the servlet is no longer needed, such as when
the web application is shut down.
The servlet life cycle is managed by the servlet container. The servlet container is
responsible for loading, creating, and destroying servlets. The servlet container
also handles requests and responses to servlets.
2) Syntax:
- Servlets: Servlets use Java code to generate dynamic content, which is typically
embedded within the `doGet()` or `doPost()` methods. Servlet code is written in
Java and is independent of HTML.
- JSP: JSPs use a combination of HTML and Java code. Java code is embedded
within `<% %>` tags or using Expression Language (EL) `${}`. This allows
developers to mix presentation logic with HTML markup.
3) Development Ease:
- Servlets: Servlets are more suitable for developers with a strong Java background.
Handling HTML markup within Java code can sometimes lead to code clutter and
reduced readability.
- JSP: JSPs provide a more natural and intuitive way to develop web pages,
especially for developers familiar with HTML. The separation of HTML markup
and Java code enhances code maintainability and readability.
4) Maintenance:
- Servlets: Since Servlets mix HTML markup with Java code, making changes to
the presentation layer might require modifying Java code, which can be more
cumbersome.
- JSP: With JSPs, HTML markup is kept separate from Java code, making it easier
to update the presentation layer without touching the underlying Java logic.
5) Performance:
- Servlets: Servlets typically offer better performance compared to JSPs because
they are compiled into Java bytecode once and reused for subsequent requests.
- JSP: JSPs need to be translated into servlets by the servlet container before they
can be executed, which adds a slight overhead during the initial request.
6) Role in MVC:
- Servlets: Servlets are often used as controllers in the Model-View-Controller
(MVC) design pattern. They receive requests, process data, and delegate
presentation logic to JSP or other view technologies.
- JSP: JSPs are commonly used as view components in the MVC pattern. They
focus on generating dynamic HTML content based on data provided by servlets or
other controller components.
1) Cookies: Cookies are small pieces of data stored on the client-side (typically in the
user's browser) and sent with each HTTP request. Servlets can use cookies to
store a session identifier (session ID), which can be used to retrieve session-
specific data stored on the server.
2) URL Rewriting: In this technique, session IDs are appended to URLs as query
parameters. Servlets generate URLs with session IDs embedded in them, and the
server extracts the session ID from subsequent requests to identify the user's
session.
3) Hidden Form Fields: Servlets can include hidden form fields in HTML forms that
contain the session ID. When the form is submitted, the session ID is sent to the
server along with the form data, allowing the server to identify the user's session.
4) URL Path Parameters: Similar to URL rewriting, Servlets can append session IDs
to URLs as path parameters. The session ID is extracted from the request URL to
maintain session state.
5) HTTP Session Object: Servlets can also use the HttpSession object provided by the
servlet container. The HttpSession object allows Servlets to store session-specific
data on the server and associate it with a unique session ID. The session ID can be
transmitted to the client using cookies or URL rewriting, and subsequent requests
from the client include the session ID, allowing the server to retrieve the
HttpSession object and access session data.
Suggested Reference:
Complete Reference J2EE by James Keogh mcgraw publication
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley Publication
Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)
Rubrics 1 2 3 4 5 Total
Marks
Experiment No: 4
Date:
Objectives: (a) implement webpages using HTML for collecting user input.
(b) able to do server side programming using JSP to process user input.
(c) To show how JSP can interact with Database
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Apache Tomcat Server,
Netbeans/eclipse, Oracle Xpress edition 11g, Type4 JDBC driver for Oracle
Theory:
Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
platform-independent method for building Web-based applications.
JSP can be run as per the following diagram −
Steps to configure JDK and Tomcat server for servlet and JSP program
1) Download Java (JDK) and install it.
2) Set PATH and JAVA_HOME environment variable
set PATH = C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME = C:\jdk1.5.0_20
(Assuming java installed in c:\ and jdk1.5.0_20)
3) Download the latest version of Tomcat and install it
4) Create a CATALINA_HOME environment variable pointing to C:\apache-tomcat-5.5.29.
(assuming tomcat is installed in C:\apache-tomcat-5.5.29)
5) Run following command to start tomcat server
C:\apache-tomcat-5.5.29\bin\startup.bat
After a successful startup, the default web-applications included with Tomcat will be available by
visiting http://localhost:8080/.
6) Tomcat can be stopped by executing the following commands on the Windows machine −
C:\apache-tomcat-5.5.29\bin\shutdown
7) Set classpath as below,
set CATALINA = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%
Procedure:
1. Create a directory structure for web application in application folder.
2. Create database for your project
3. Create an html file asking for data from user and submit those data to jsp in application
folder
4. Create a jsp program to receive the input and process it as per your requirement, Also
this jsp program can interact with database using Type 4 JDBC driver.
5. Prepare web.xml file to put deployment descriptor
6. Put application folder into root directory of application server( wepapps folder of
Tomcat server)
7. Open any web browser and run the program by typing url in address bar.
Observations:
String name =
rs.getString("p_name
"); int price =
rs.getInt("p_price");
OUTPUT:
Home Page
Add Item
Read Item
Update Item
Delete Item
Conclusion:
In conclusion, this practical successfully modified Practical 4 by replacing the use of Servlet with
JSP (JavaServer Pages). By utilizing JSP, the application's dynamic web pages were generated,
making it easier to integrate Java code with HTML. This enhancement improved the overall
development experience and allowed for more efficient and streamlined creation of dynamic web
content. The successful implementation demonstrated the adaptability of the application to
leverage JSP technology, enhancing the web-based user interface.
Quiz:
1. List advantages of JSP.
• Easy to learn and use: JSP is a server-side scripting
language that is based on HTML. This makes it easy to
learn and use for developers who are already familiar with
HTML.
• Extensible: JSP is extensible with JavaBeans and tag libraries. This
allows developers to add custom functionality to their JSP pages.
• Portable: JSP is a standard technology that is supported by all major web
servers. This makes it easy to deploy JSP applications on different servers.
• Secure: JSP is a secure technology that can be used to develop secure web
applications. This is because JSP pages are compiled into Java servlets before
they are executed.
Suggested Reference:
Complete Reference J2EE by James Keogh mcgraw publication
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley Publication
Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)
Rubrics 1 2 3 4 5 Total
Marks
Experiment No: 5
Use JSF framework to replace JSP and calculate the reduction in programming.
Date:
Competency and Practical Skills: Design a web application using JSF Framework
Theory:
Java Server Faces (JSF) is a Java-based web application framework intended to simplify development
integration of web-based user interfaces.
Basic understanding of Java programming language, and understanding of other web technologies such
as HTML, CSS, AJAX, etc. is required to use JSF.
JSF facilitates Web application development by −
A JSF application consists of web pages with JSF UI components. A JSF application requires also some
configuration files ("faces-config.xml" and web.xml).
• Managed Bean -
the data elements of
the JSF application
(managed beans
and backing beans)
represent a Java
class which will be
created
dynamically
during runtime of
the JSF application. It
can be defined for
which scope the
bean is valid (Session,
Request,
Application or none)
• the navigation between web pages
• data validators - Used to check the validity of UI input
• data converters -Used to translate between UI and model
Procedure:
1) Create database for your project
2) Open netbeans and create a new project (web application with JSF)
Observations:
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@ManagedBean
@ViewScoped
public class ItemBean implements Serializable {
private List<Item> Items;
private Item newItem;
private Item selectedItem;
@PostConstruct
public void init() {
// Load Items data from
the database
loadItems();
newItem = new Item();
}
while (resultSet.next()) {
int id = resultSet.getInt("id");
String ItemId = resultSet.getString("Item_id");
String customerId =
resultSet.getString("customer_id"); String
routeId = resultSet.getString("route_id");
String customerRoute =
resultSet.getString("customer_route"); int
bookedAmount =
resultSet.getInt("booked_amount"); String
bookedSeat = resultSet.getString("booked_seat");
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//item
public class Item {
private Connection connection;
private String name;
private String id;
private int stock;
private int price;
public Item(){
//Output:
Home Page
Add Item
Read Item
Update Item
Delete Item
Conclusion:
In summary, this practical implemented the use of JSF (JavaServer Faces) framework to replace
JSP (JavaServer Pages) and calculated the reduction in programming. By leveraging the benefits
of JSF, the application was able to simplify the creation of dynamic user interfaces and reduce the
amount of code required. The successful implementation demonstrated the power and flexibility
of JSF in streamlining the development process and reducing programming efforts. Overall, this
practical showcased the significant reduction in programming that can be achieved by utilizing
JSF technology to enhance the web-based user interface.
Quiz:
1. What features Java Server Faces offer in web development?
• Component-based UI framework for building web applications
• Server-side event handling and data validation
• Support for various input types and conversion of data
• Integration with various Java technologies like JavaBeans, Servlets, and JSP
the decode method to extract its new value from the request parameters. Component stores
this value. If the conversion fails, an error message is generated and queued on
FacesContext.
Phase 3: Process validation
During this phase, JSF processes all validators registered on the component tree. It
examines the component attribute rules for the validation and compares these rules to the
local value stored for the component.
If the local value is invalid, JSF adds an error message to the FacesContext instance, and
the life cycle advances to the render response phase and displays the same page again with
the error message.
Phase 4: Update model values
After the JSF checks that the data is valid, it walks over the component tree and sets the
corresponding server-side object properties to the components' local values. JSF will
update the bean properties corresponding to the input component's value attribute.
Phase 5: Invoke application
During this phase, JSF handles any application-level events, such as submitting a
form/linking to another page.
Phase 6: Render response
During this phase, JSF asks container/application server to render the page if the
application is using JSP pages. For initial request, the components represented on the page
will be added to the component tree as JSP container executes the page. If this is not an
initial request, the component tree is already built so components need not be added again.
In either case, the components will render themselves as the JSP container/Application
server traverses the tags in the page. After the content of the view is rendered, the response
state is saved so that subsequent requests can access it and it is available to the restore view
phase.
Suggested Reference:
Java Server Faces in Action, Kito D. Mann, Manning Publication
Beginning JSP, JSF andTomcat, Giulio Zambon, Apress
JSF2.0 CookBook, Anghel Leonard, PACKT publication
Goo Averag Goo Averag Good Satisfactory Good Satisfactory Good Average
d (2) e (1) d (2) e (1) (2) (1) (2) (1) (2) (1)
Rubrics 1 2 3 4 5 Total
Marks
Experiment No: 6
Make custom tag for a component that will be able to add/view/delete/modifyRecords
Date:
Relevant CO:CO3
Objectives: (a) To be able to use custom tag for use in JSP for converting java scriptlets to tags
in a JSP page.
(b) To be able to implement the custom tag for CRUD operations.
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse, Oracle
Xpress edition 11g, Apache Tomcat / GlassFish / any other web server for Java.
Theory:
Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates the business
logic from the JSP page.
The same business logic can be used many times by the use of custom tag.
Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet tag which is considered
bad programming approach in JSP.
Separation of business logic from JSP The custom tags separate the the business logic from the JSP page
so that it may be easy to maintain.
Re-usability The custom tags makes the possibility to reuse the same business logic again and again.
Procedure:
1. Create the Tag handler class and perform action at the start or at the end of the tag.
To create the Tag Handler, we are inheriting the TagSupport class and overriding its
method doStartTag().To write data for the jsp, we need to use the JspWriter class.The
PageContext class provides getOut() method that returns the instance of JspWriter class.
TagSupport class provides instance of pageContextbydefault.
2. Create the Tag Library Descriptor (TLD) file and define tags
Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It
must be contained inside the WEB-INF directory.
3. Create the JSP file that uses the Custom tag defined in the TLD file
Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it
is recommended to use the uri name instead of full path of tld file. We will learn about
urilater.It uses taglib directive to use the tags defined in the tld file.
Observations:
import java.io.*;
import java.sql.*;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.JspWriter;
import jakarta.servlet.jsp.PageContext;
import jakarta.servlet.jsp.tagext.TagSupport;
this.stock = stock;
}
public Item(){
Connection conn =
Practical_01_DataBase.getConnection();
Statement stmt = conn.createStatement();
else if (operation.equals("view")) {
ResultSet rs = Practical_01_DataBase.searchData(stmt,
search); String searchResult =
Practical_01_DataBase.getSearchResult(rs);
out.print("searchResult"+searchResult);
}
else if (operation.equals("modify")) {
Practical_01_DataBase.updateBookDetail(stmt, new Book(bid, title,
author,
pages, publisher, year, language));
out.print("<h1>Material Deleted
Successfully!</h1>"); } else {
out.print("<h1>Invalid operation!</h1>
stmt.close();
conn.close();
}
catch(Exceptio n e) { e.printStckTrace();
pageContext.setAttribute("message", "An error occurred:"+e.getMessage());
}
return SKIP_BODY;
}
}
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>mytag</name>
<tag-class>com.JSF.MaterialTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>operation</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>search</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>bid</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>title</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// Get the parameter values
from the request String
BidStr =
request.getParameter("bid
")
int bid;
if (BidStr == null ||
BidStr.isEmpty()) { bid =
0;
} else {
bid = Integer.parseInt(BidStr);
}
String title =
request.getParameter("p_name");
String author =
request.getParameter("p_price");
int pages =
Integer.parseInt(request.getParameter("p_stock"));
String pagesStr = request.getParameter("pages");
int pages;
if (pagesStr == null ||
pagesStr.isEmpty()) { pages =
0;
} else {
pages = Integer.parseInt(pagesStr);
}
%>
<t:mytag operation="<%= operation %>" search="<%= search %>"
bid="<%= bid %>"
name="<%= p_name %>" price="<%= p_price %>" stock="<%= p_stock %>"
</body>
</html>
package com.sarang;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.*;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
} catch
(SQLException
e) {
e.printStackTrac
e();
}
}
}
}
CustomTag of jsp file for Book :-
<label for="price">Stock</label>
<input type="text" id="author" name="p_price"><br><br>
<label for="stock">Price</label>
Conclusion:
In conclusion, this practical focused on creating a custom tag for a component that enabled the
creation, reading, updating, and deletion of blogs. By implementing this custom tag, the
functionality of the application was extended, allowing users to perform essential operations on
blogs seamlessly. This practical showcased the power and flexibility of custom tags in simplifying
the development process and enhancing the user experience. Overall, the successful implementation
of the custom tag demonstrated the efficiency and convenience it brings to managing blog content
within the application.
Quiz:
1) List and explain types of custom tags.
CE-6th-A3-210130107049 60 Rudra Joshi
Advance Java Programming 3160707
• doAfterBody() - Used to process the body of the tag after the doStartTag()
method has been called.
• setPageContext() - Used to set the page context object for the tag.
3) Write and Explain the TLD file structure and steps for creating it.
• <tag-class> - Specifies the fully qualified name of the tag handler class.
d. Define the attributes of the custom tags using the <attribute> element.
Suggested Reference:
https://docs.oracle.com/cloud/latest/as111170/TAGLB/quickstart.htm
https://docs.oracle.com/cloud/latest/as111170/TAGLB/quickstart.htm
Experiment No: 7
Use Object Relational Mapping and based on that prepare one configuration file along with
the hibernet mapping file for 1 table of the application and test its working by replacing SQL
to HQL.
Date:
Objectives: (a) To understand object relational impedance and prepare the object relational
mapping and mapping file
(b) To understand and prepare hibernet configuration file
(c) To use HQL to execute a query
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse,
Hibernetframwork
Theory:
Hibernate Framework
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate framework.
There are two types of cache in hibernate framework first level cache and second level cache. First level
cache is enabled by default.
HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database
independent queries. So you don't need to write database specific queries. Before Hibernate, if database is
changed for the project, we need to change the SQL query as well that leads to the maintenance problem.
Hibernate framework provides the facility to create the tables of the database automatically. So there is no
need to create tables in the database manually.
Hibernate supports Query cache and provide statistics about query and database status.
For creating the first hibernate application, we must know the elements of Hibernate architecture. They are
as follows:
SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache
(optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of
Session.
Session
The session object provides an interface between the application and data stored in the database. It is a short-
lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-
level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and
delete the object. It also provides factory methods for Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.Transaction
interface provides methods for transaction management.
ConnectionProvider
TransactionFactory
Procedure:
For creating the first hibernate application, we need to follow the following steps:
Observations:
</session-factory>
</hibernate-configuration>
@Entity
@Table(name = "book1") public class Item {
private Connection connection;
private String name;
private String id;
private int stock;
private int price;
public Item(){
"");
PreparedStatement ps = connection.prepareStatement("INSERT INTO inventory (p_name,
p_price, p_stock) VALUES (?, ?, ?)");
ps.setString(1, name);
ps.setInt(1, price);
ps.setInt(2, stock);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return "success";
}
}
@Override
public String toString() { return "Data{" +
"p_id=" + p_id +
", p_name='" + p_name + '\'' +
", p_stock='" + p_stock + '\'' + ", p_price=" + p_price
}}
import org.hibernate.Query;
import org.hibernate.service.ServiceRegistryBuilder; import
org.hibernate.service.ServiceRegistry;
Sf.close();
OUTPUT:
(Add Data)
(Read Data)
(Update Data)
(Delete Data)
Conclusion:
In summary, this practical focused on utilizing Object Relational Mapping (ORM) to streamline
database operations. A configuration file, along with a Hibernate mapping file, was prepared for
one table in the application. By implementing ORM, the application reduced the reliance on SQL
queries and instead used Hibernate Query Language (HQL) for database interactions. The
successful testing of this implementation demonstrated the effectiveness of ORM in simplifying
database management and improving code maintainability. Overall, this practical showcased the
benefits of using ORM, such as HQL, to enhance the efficiency and functionality of the application's
database operations.
Quiz:
1. Explain the Object Relational mis-match. How can we overcome in hibernet?
3. What is a hibernet configuration file. Provide the steps to create the configuration file.
A Hibernate configuration file is an XML file that contains the settings and
configurations for
Hibernate. To create a Hibernate configuration file, you need to follow these steps:
Suggested Reference:
https://docs.oracle.com/cd/E11035_01/workshop102/ormworkbench/hibernate-
tutorial/tutHibernate1.html
https://docs.oracle.com/cd/E11035_01/workshop102/ormworkbench/hibernatetutorial/tutHibernate1.html
Experiment No: 8
Use Hibernet framework to replace JDBC calls and calculate the reduction in programming
efforts for the entire application
Date:
Theory:
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't
depends on the table of the database. Instead of table name, we use class name in HQL. So it is
database independent query language.
Advantage of HQL
There are many advantages of HQL. They are as follows:
1. database independent
2. supports polymorphic queries
3. easy to learn for Java Programmer
Query Interface
It is an object oriented representation of Hibernate Query. The object of Query can be obtained by
calling the createQuery() method Session interface.
The query interface provides many methods. There is given commonly used methods:
Play Video
Procedure:
For creating the first hibernate application in Eclipse IDE, we need to follow the following steps:
Observations:
</session-factory>
</hibernate-configuration>
package
com.javaProject.firstJavaProject;
import java.util.*;
CE-6th-A3-210130107049 72 Rudra Joshi
Advance Java Programming 3160707
import
org.hibernate.Query;
import
org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.Transaction;
import
org.hibernate.cfg.Configuration;
import
org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public static void main( String[] args )
{//Insert data
Data newData = new Data(“A”,5,100);
insertItemDetail(newData);
// Update data
Data updatedData = new Data(2, "A", 5,100);
updateItemDetails(updatedData);
deleteBookDetail(2);
sessionFactory.close();
+ "%"); try {
int searchNum = Integer.parseInt(searchString);
} catch (NumberFormatException e) {
// ignore if the search string is not a number
}
Query q = session.createQuery(hql);
for (Map.Entry<String, Object> entry :
params.entrySet()) {
q.setParameter(entry.getKey(), entry.getValue());
}
List<Data> datas =
q.list(); session.close();
return datas;
}
data.setName(updatedData.getName());
data.setStock(updatedData.getStock());
data.setPrice(updatedData.getPrices());
transaction.commit
(); session.close();
}
static void deleteBookDetail(int subjectCode) {
Session session =
sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Data data = (Data) session.get(Data.class,
subjectCode); session.delete(data);
transaction.commit
(); session.close();
}
//
static void searchBook(String searchString) {
List<Data> dataList =
searchData(searchString);
for (Data data : dataList) {
System.out.println(data.getPid() + " | " + data.getName() + " | " + data.getPrice() + " | "
CE-6th-A3-210130107049 74 Rudra Joshi
Advance Java Programming 3160707
+ data.getStock() );
}
}
}
Conclusion:
In this practical, Hibernate framework was used to replace JDBC calls, resulting in a significant
reduction in programming efforts for the entire application. By leveraging Hibernate's ORM
capabilities, manual SQL queries were eliminated, streamlining database operations and
improving productivity. The successful implementation demonstrated the efficiency and
effectiveness of Hibernate in reducing code complexity and enhancing the application's database
interactions.
Quiz:
1) How HQL supports database independence? Explain with example.
2) How HQL can help reduce the object querying for composite objects.
HQL can help reduce object querying for composite objects by using the
concept of lazy loading. Lazy loading means that the related objects are not
loaded from the database until they are explicitly accessed by the
application. This helps to reduce the number of unnecessary object queries
and improve performance. For example, consider the following HQL query:
Suggested Reference:
https://docs.oracle.com/cloud/latest/as111170/TAGLB/quickstart.htm
Experiment No: 9
Use Spring or any other MVC architecture and implement the Interface in that architecture
that supports multi-tier architecture.
Date:
Theory:
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB
MVC etc. We will learn these modules in next page. Let's understand the IOC and Dependency
Injection first.
class Employee{
Address address;
Employee(){
address=new Address();
}
}
In such case, there is dependency between the Employee and Address (tight coupling). In the
Inversion of Control scenario, we do this something like this:
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
}
Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if our
logic is moved to new environment.
CE-6th-A3-210130107049 77 Rudra Joshi
Advance Java Programming 3160707
In Spring framework, IOC container is responsible to inject the dependency. We provide metadata
to the IOC container either by XML file or annotation.
1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no
need to write too much code. It hides the basic steps of these technologies.
Let's take the example of JdbcTemplate, you don't need to write the code for exception handling,
creating connection, creating statement, committing transaction, closing connection etc. You need
to write the code of executing query only. Thus, it save a lot of JDBC code.
2) Loose Coupling
The Spring applications are loosely coupled because of dependency injection.
3) Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application require
server to run the application but Spring framework doesn't require server.
4) Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework
doesn't force the programmer to inherit any class or implement any interface. That is why it is said
non-invasive.
5) Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks
makes the easy development of JavaEE application.
6) Powerful abstraction
It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
7) Declarative support
It provides declarative support for caching, validation, transactions and formatting.
Procedure:
CE-6th-A3-210130107049 78 Rudra Joshi
Advance Java Programming 3160707
- Create a table
Observations:
First, we'll define the interface for our library management system. This will include methods
for adding, removing, and searching for books in the library, as well as checking out and
returning books.
public interface
InventoryManagement {
public void addItem(Item
item);
public void removeItem(int pId);
public List<Book> searchItem(String name, int pId);
}
Next, we'll create a data access layer to handle interactions with the database. We'll
use Spring Data JPA to simplify our interactions with the database.
@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
public List<Book> findByTitleContainingOrAuthorContaining(String title, String author);
}
Our service layer will then use this data access layer to perform the necessary operations.
We'll annotate our service class with @Service to let Spring know that it should manage
this bean.
@Service
public class InventoryServiceImpl implements
InventoryManagement { @Autowired
private Item items;
}
Finally, we'll create a presentation layer to handle interactions with the user. We'll use
Spring MVC to handle incoming HTTP requests and map them to the appropriate
controller method.
@Controller
@RequestMapping("/lib
rary") public class
InventoryController {
@Autowired
private InventoryManagement inventoryManagement;
@PostMapping("/add")
public String addItem(@ModelAttribute Item
item) { inventoryManagement.addItem(item);
return "redirect /";
}
@GetMapping("/remove/{pId}")
public String removeItem(@PathVariable int
bookId) {
inventoryManagement.removeItem(pId);
return "redirect: /";
}
@GetMapping("/search")
public String searchItems(@RequestParam String name, @RequestParam int id, Model
model) {
model.addAttribute("inventory",
inventoryManagement.searchItems(id, name)); return "index";
}
OUTPUT:
Home Page
Add Item
Read Item
Update Item
Delete Item
Conclusion:
his practical implemented the use of Spring or any other MVC architecture to support a multitier
architecture. The successful implementation showcased the benefits of this approach, including
improved modularity, maintainability, and scalability. Overall, the practical demonstrated the
effectiveness of utilizing MVC frameworks in building robust and scalable applications with a
multi-tier structure.
Quiz:
1. What is Dependency Injection? How is it useful for creating the maintainable projects?
Dependency Injection is a design pattern that allows objects to receive their
CE-6th-A3-210130107049 81 Rudra Joshi
Advance Java Programming 3160707
dependencies from an external source rather than creating them themselves. It helps
to make projects more maintainable by reducing the coupling between different
components and making it easier to replace or update dependencies.
Suggested Reference:
https://spring.io/
Experiment No: 10
Compare and analyze the JSF with the Spring framework. Use JSF for creating a CRUD
operation.
Date:
Theory:
JavaServer Faces
It is a server side component based user interface framework. It is used to develop web applications.
It provides a well-defined programming model and consists of rich API and tag libraries. The latest
version JSF 2 uses Facelets as its default templating system. It is written in Java.
The JSF API provides components (inputText, commandButtonetc) and helps to manage their
states. It also provides server-side validation, data conversion, defining page navigation, provides
extensibility, supports for internationalization, accessibility etc.
The JSF Tag libraries are used to add components on the web pages and connect components with
objects on the server. It also contains tag handlers that implements the component tag.
With the help of these features and tools, you can easily and effortlessly create server-side user
interface.
2) JavaServer Faces API?s are layered directly on top of the Servlet API. Which enables several
various application use cases, such as using different presentation technologies, creating your own
custom components directly from the component classes.
3) Including of Facelets technology in JavaServer Faces 2.0, provides massive advantages to it.
Facelets is now the preferred presentation technology for building JavaServer Faces based web
applications.
Procedure:
A Simple JavaServer Faces Application
To create a JSF application, we are using NetBeans IDE 8.2. You can also refer to other Java IDEs.
Here, we are creating a project after that we will run to test it's configuration settings. So, let's create
a new project fist.
- Go to file menu and select new Project.-> Select Category Java Web and Project Web
Application. -> Enter project name.
- Select Preferred Page Language: Earlier versions of JSF framework are default to JSP for
presentation pages. Now, in latest version 2.0 and later JSF has included powerful tool
"Facelets". So, here we have selected page language as facelets. We will talk about facelets
in more details in next chapter.
- Index.xhtml Page: After finishing, IDE creates a JSF project for you with a default
index.xhtml file. Xhtml is a extension of html and used to create facelets page.
- Run: Now, you can run your application by selecting run option after right click on the
project. It will produce a default message "Hello from Facelets".
Whenever we run the project, it renders index.xhtml as output. Now, we will create an application
which contains two web pages, one bean class and a configuration file.
Observations:
Index.Xhtml :-
xmlns="http://www.w3.org/1999/xht
ml"
xmlns:h="http://java.sun.com/jsf/ht
ml"
xmlns:f="http://java.sun.com/jsf/cor
e"
xmlns:ui="http://java.sun.com/jsf/fa
celets">
<h:head></h:head>
<h:body>
<h1> Book Details</h1>
<br></br>
<br></br>
<h:form>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
Item Price : <h:inputText value="#{crud.p_price}"></h:inputText>
<br></br>
<br></br>
<h:commandButton id="cmdinsert1" value="ADD"
action="#{crud.add()}"></h:commandButton>
<br></br>
<br></br>
<h:commandButton id="cmdinsert2" value="DELETE"
action="#{crud.delete()}"></h:commandButton>
<br></br>
<br></br>
<h:commandButton id="cmdinsert3" value="Update"
action="#{crud.update()}"></h:commandButton>
</h:form>
</h:body>
</html>
Crud.Java:-
return price;
}
public Item(){
Output :
Conclusion:
In summary, this practical compared JSF and Spring frameworks by implementing a CRUD
operation using JSF. The analysis considered factors like ease of use, flexibility, and community
support. The comparison provided insights into the strengths and weaknesses of both frameworks,
helping in the selection of the appropriate framework for CRUD development. Overall, this
practical facilitated a better understanding of JSF and Spring and their suitability for CRUD
operations.
Quiz:
1. What is Java ServerFaces? How is it useful?
JavaServer Faces (JSF) is a web application framework for developing user interfaces
for Java-based web applications. JSF is useful for creating dynamic web applications
that can interact with users in real-time.
2. How JSF is different from Spring? Explain the limitations and advantages.
JSF is different from Spring in that Spring is a more general-purpose framework that
offers a wide range of features for building enterprise applications, while JSF is
specifically designed for building web user interfaces.
The advantages of JSF include its component-based architecture, support for Ajax,
and built-in validation and error handling. Its limitations include a steep learning
curve, a complex lifecycle, and limited support for customization..
decode method to extract its new value from the request parameters. Component stores this value.
If the conversion fails, an error message is generated and queued on FacesContext.
Phase 3: Process validation
During this phase, JSF processes all validators registered on the component tree. It examines the
component attribute rules for the validation and compares these rules to the local value stored for
the component.
If the local value is invalid, JSF adds an error message to the FacesContext instance, and the life
cycle sadvances to the render response phase and displays the same page again with the error
message.
Phase 4: Update model values
After the JSF checks that the data is valid, it walks over the component tree and sets the
corresponding server-side object properties to the components' local values. JSF will update the
bean properties corresponding to the input component's value attribute.
Phase 5: Invoke application
During this phase, JSF handles any application-level events, such as submitting a
form/linking to another page.
Phase 6: Render response
During this phase, JSF asks container/application server to render the page if the application is
using JSP pages. For initial request, the components represented on the page will be added to the
component tree as JSP container executes the page. If this is not an initial request, the component
tree is already built so components need not be added again. In either case, the components will
render themselves as the JSP container/Application server traverses the tags in the page. After
the content of the view is rendered, the response state is saved so thatsubsequent requests can
access it and it is available to the restore view phase.
Suggested Reference:
https://www.oracle.com/java/technologies/javaserverfaces.html