0% found this document useful (0 votes)
39 views101 pages

Rudra Ajp

This laboratory manual is designed for the Advance Java Programming course, emphasizing practical skills and real-time problem-solving relevant to industry needs. It outlines course objectives, practical experiments, and guidelines for both students and faculty to enhance learning outcomes. The manual also includes safety instructions and a sample project to illustrate practical applications of Java technologies.

Uploaded by

meghpatel2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views101 pages

Rudra Ajp

This laboratory manual is designed for the Advance Java Programming course, emphasizing practical skills and real-time problem-solving relevant to industry needs. It outlines course objectives, practical experiments, and guidelines for both students and faculty to enhance learning outcomes. The manual also includes safety instructions and a sample project to illustrate practical applications of Java technologies.

Uploaded by

meghpatel2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

A Laboratory Manual for

Advance Java Programming


(3160707)

B.E. Semester 6 (Computer)

Directorate of Technical Education, Gandhinagar,


Gujarat
Government Engineering College, Gandhinagar
Department of Computer Engineering

CERTIFICATE

This is to certify that Mr./Ms.

____________________________________ Enrollment No.

_______________ of B.E. Semester ________ from Computer

Engineering Department of this Institute (GTU Code: 013) has

satisfactorily completed the Practical / Tutorial work for the subject

Advance Java Programming (3160707) for the academic year ________.

Place: ___________

Date: ___________

Signature of Course Faculty Head of the Departmet


Preface

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

▪ To provide globally competitive technical education


▪ Remove geographical imbalances and inconsistencies
▪ Develop student friendly resources with a special focus on girls’ education and support to
weaker sections
▪ Develop programs relevant to industry and create a vibrant pool of technical professionals

Institute’s Vision

▪ To create an ecosystem for proliferation of socially responsible and technically sound


engineers, innovators and entrepreneurs.

Institute’s Mission

▪ To develop state-of-the-art laboratories and well-equipped academic infrastructure.


▪ To motivate faculty and staff for qualification up-gradation, and enhancement of subject
knowledge.
▪ To promote research, innovation and real-life problem-solving skills.
▪ To strengthen linkages with industries, academic and research organizations.
▪ To reinforce concern for sustainability, natural resource conservation and social
responsibility.

Department’s Vision

▪ To create an environment for providing value-based education in Computer Engineering


through innovation, team work and ethical practices.

Department’s Mission

▪ To produce computer engineering graduates according to the needs of industry,


government, society and scientific community.
▪ To develop state of the art computing facilities and academic infrastructure.
▪ To develop partnership with industries, government agencies and R & D organizations for
knowledge sharing and overall development of faculties and students.
▪ To solve industrial, governance and societal issues by applying computing techniques.
▪ To create environment for research and entrepreneurship.

CE-6th-A3-210130107049 1 Rudra Joshi


Advance Java Programming 3160707

Programme Outcomes (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science,engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyzecomplex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineeringproblems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledgeand research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques,resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextualknowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professionalengineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics andresponsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as amember or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activitieswith the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understandingof the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and abilityto engage in
independent and life-long learning in the broadest context of technological change.

CE-6th-A3-210130107049 2 Rudra Joshi


Advance Java Programming 3160707

Program Specific Outcomes (PSOs)

• Sound knowledge of fundamentals of computer science and engineering including software


and hardware.
• Develop the software using sound software engineering principles having web based/mobile
based interface.
• Use various tools and technology supporting modern software frameworks for solving
problems having large volume of data in the domain of data science and machine learning.

Program Educational Objectives (PEOs)

• Possess technical competence in solving real life problems related to Computing.


• Acquire good analysis, design, development, implementation and testing skills to formulate
simple computing solutions to the business and societal needs.
• Provide requisite skills to pursue entrepreneurship, higher studies, research, and
development and imbibe high degree of professionalism in the fields of computing.
• Embrace life-long learning and remain continuously employable.
• Work and excel in a highly competence supportive, multicultural, and professional
environment which abiding to the legal and ethical responsibilities.

CE-6th-A3-210130107049 3 Rudra Joshi


Advance Java Programming 3160707

Practical – Course Outcome matrix

Course Outcomes (COs):


CO_3160707.1 Implement Networking and Data base connectivity in Java for given application.
CO_3160707.2 Implement webpage with dynamic content and server side web application using
Servlet and JSP.
CO_3160707.3 Use web application framework JSF to build user interfaces.
CO_3160707.4 Use Object Relation Mapping using Hibernate to build database dependent
applications
CO_3160707.5 Apply Model-View-Controller architecture to build complex client-server
applications.
C
Sr. CO CO CO CO
Objective(s) of Experiment O
No. 2 3 4 5
1
Create databases related to your project and query them
1. √
from console based java applications.
Create a client application that will connect with the
application mentioned in the practical 1, client
application will send a search “string” to the above
2. √
application and above application will send back the
string with the matching results after fetching from the
database.
Modify practical 1 by replacing the console based user
3. √
interface to a web based user interface. Use a servlet.

4. Modify the practical 4 to use JSP instead of Servlet. √

Use JSF framework to replace JSP and calculate the


5. √
reduction in programming
Make custom tag for a component that will be able to
6. √
add/view/delete/modify Records
Use Object Relational Mapping and based on that
prepare one configuration file along with the hibernet
7. √
mapping file for 1 table of the application and test its
working by replacing SQL to HQL.
Use Hibernet framework to replace JDBC calls and
8. calculate the reduction in programming efforts for the √
entire application
Use Spring or any other MVC architecture and
9. implement the Interface in that architecture that supports √
multi-tier architecture.

CE-6th-A3-210130107049 4 Rudra Joshi


Advance Java Programming 3160707

Compare and analyze the JSF with the Spring


10. √
framework.

CE-6th-A3-210130107049 5 Rudra Joshi


Advance Java Programming 3160707

Industry Relevant Skills

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

Guidelines for Faculty members


1. Teacher should provide the guideline with demonstration of practical to the students
with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students before
starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the
students and ensure that the respective skills and competencies are developed in the
students after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students


1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination scheme,
skill set to be developed etc.
2. We will have a project based learning methodology for practical in Advanced Java subject.
3. Students will form a team of maximum 4 people and then give the definition of a project..
4. Students can use the web application definition of Design Engineering subject also/ They
can give another definition for a web application project
5. You'll need to decide the project and submit your practical list sample list is shown in next
page.
6. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.

CE-6th-A3-210130107049 6 Rudra Joshi


Advance Java Programming 3160707

Common Safety Instructions


Students are expected to
1) switch on the PC carefully (not to use wet hands)
2) shutdown the PC properly at the end of your Lab
3) carefully Handle the peripherals (Mouse, Keyboard, Network cable etc)
4) Use Laptop in lab after getting permission from Teacher

CE-6th-A3-210130107049 7 Rudra Joshi


Advance Java Programming 3160707

Sample Practical List

Project Name: Product Inventory Management

Project Details: In Product Inventory Management, We can manage inventory of


product. In this project inventory admin can add product, delete product, update product
details and delete the products details.

Sr. Objective(s) of Experiment


No.

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.

CE-6th-A3-210130107049 8 Rudra Joshi


Advance Java Programming 3160707

Index
(Progressive Assessment Sheet)

Sr. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar


No. No. perform submiss nt Teacher ks
ance ion Marks with date
1. Create databases related to your project and
query them from console based java
applications.
2. Create a client application that will connect
with the application mentioned in the practical
1, client application will send a search “string”
to the above application and above application
will send back the string with the matching
results 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
framework.
Total

CE-6th-A3-210130107049 1 Rudra Joshi


Advance Java Programming 3160707

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:

Competency and Practical Skills: programming and database commands

Relevant CO: CO1

Objectives: (a) To show use of JDBC Drivers.


(b) To show how java program can interact with Database
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse, Oracle
Xpress edition 11g, Type4 JDBC driver for Oracle

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.

Safety and necessary Precautions:


1) Make sure the database server is started before running the program
2) Handle all necessary compile time Exception

Procedure:
1. Create a database for your project
2. Write java program to interact with tables in database using Type 4 JDBC driver.

CE-6th-A3-210130107049 2 Rudra Joshi


Advance Java Programming 3160707

Observations:

import java.sql.*;
import java.util.Scanner;

public class s {

public static String getSpace(int c) { // Adding Spaces For Decoration


String spaces = " ";
for (int i = 0; i < 12 - c; i++) {
spaces += " ";
}
return spaces;
}

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


Scanner sc = new Scanner(System.in);
int choice;
String url = "jdbc:mysql://localhost:3306/ajp"; // table details
String username = "root"; // MySQL credentials
String password = "root1234";
Class.forName("com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(url, username, password); // Build
Connection
System.out.println("Product product_details Management System");
System.out.println("1: Create 2: Read 3: Update 4: Delete");
// Infinite product_details CRUD Operations
while (true) {
System.out.print("Enter Choice : ");
choice = sc.nextInt();
if (choice == 1) { // Insert Product to product_details
String name;
int stock, price;
System.out.print("Enter Name : ");
name = sc.next();
System.out.print("Enter Stock : ");
stock = sc.nextInt();
System.out.print("Enter Price : ");
price = sc.nextInt();
String insertQuery = String.format("INSERT INTO
product_details(name,price,stock) VALUES ('%s','%d','%d')", name, price,stock);
String getIdQuery = "SELECT * FROM product_details ORDER BY id
DESC";
// Insert Product and return Automatically Generated id
try {

Statement st = con.createStatement();
st.execute(insertQuery); // Execute query
ResultSet rs = st.executeQuery(getIdQuery);

CE-6th-A3-210130107049 3 Rudra Joshi


Advance Java Programming 3160707

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) {

CE-6th-A3-210130107049 4 Rudra Joshi


Advance Java Programming 3160707

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:

CE-6th-A3-210130107049 5 Rudra Joshi


Advance Java Programming 3160707

Conclusion:

• The Java JDBC project successfully connects Java applications to databases,


enabling efficient data retrieval and manipulation. Through JDBC's robust
functionality, the project ensures seamless interaction between Java programs
and various database management systems. Its implementation enhances data
management capabilities, offering developers a reliable solution for integrating
database functionality into their applications. Overall, the Java JDBC project
empowers developers to build dynamic and scalable database-driven applications
with ease.

Quiz:

1) List and explain all four types of JDBC Drivers.


• JDBC (Java Database Connectivity) drivers are a set of classes and interfaces
that enable Java applications to interact with databases using standard SQL
queries. There are four types of JDBC drivers:

CE-6th-A3-210130107049 6 Rudra Joshi


Advance Java Programming 3160707

Type 1: JDBC-ODBC Bridge Driver:


- This driver translates JDBC method calls into ODBC (Open Database Connectivity)
function calls. It relies on ODBC drivers to communicate with the database.

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

Type 2: Native-API Partly Java Driver:


- This driver uses a database-specific native library or API to communicate with the
database. It employs JNI (Java Native Interface) to bridge between Java code and native
code.
- Offers better performance compared to the Type 1 driver as it directly interacts with the
database.
- Platform-dependent due to the usage of native libraries.

Type 3: Network Protocol Pure Java Driver:


- Also known as the middleware driver, this driver communicates with the database
server via middleware or a server that acts as an intermediary.
- It translates JDBC calls into a middleware-specific protocol which is then converted to
the database-specific protocol.
- Platform-independent and does not require any native libraries.
- Offers flexibility and can work across different databases with the appropriate
middleware.

Type 4: Thin Driver (Direct to Database Pure Java Driver):


- This driver communicates directly with the database server without the need for any
additional software or libraries.
- It implements the entire JDBC API in Java, hence the name "thin" driver.
- Platform-independent and offers high performance because it eliminates the need for
intermediate layers.
- Suitable for web applications and environments where simplicity, performance, and
platform independence are crucial.

2) What is parameterised query? How it can be executed in java?


• A parameterized query, also known as a prepared statement, is a SQL query
where placeholders are used for parameters instead of directly inserting values
into the query string. These placeholders are later filled in with the actual values
before the query is executed.

The main purpose of using parameterized queries is to prevent SQL injection attacks and

CE-6th-A3-210130107049 7 Rudra Joshi


Advance Java Programming 3160707

improve performance by allowing the database engine to cache query execution plans.

In Java, parameterized queries can be executed using JDBC (Java Database


Connectivity).
Here's a high-level overview of how it can be done without providing specific code:

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.

6. Close Resources: Finally, close the `PreparedStatement` and `Connection` objects to


release database resources.

3) Write a note on various APIs of java.sql package.


• The `java.sql` package in Java provides a set of APIs for database
programming, enabling Java applications to interact with relational databases
using SQL (Structured Query Language). Below are some of the key APIs
available in the `java.sql` package:

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:

CE-6th-A3-210130107049 8 Rudra Joshi


Advance Java Programming 3160707

- Represents a connection to a specific database. It allows the execution of SQL


statements and manages transactions.
- Provides methods for creating Statement and PreparedStatement objects for executing
SQL queries and updates.

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.

CE-6th-A3-210130107049 9 Rudra Joshi


Advance Java Programming 3160707

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

References used by the students:


https://www.javatpoint.com/java-jdbc

Rubric wise marks obtained:


Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

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

CE-6th-A3-210130107049 10 Rudra Joshi


Advance Java Programming 3160707

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:

Competency and Practical Skills: programming and database commands

Relevant CO: CO1

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

1) IP Address: IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It


is composed of octets that range from 0 to 255. It is a logical address that can be changed.

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.

5) Connection-oriented and connection-less protocol: In connection-oriented protocol,


acknowledgement is sent by the receiver. So it is reliable but slow. The example of connection-
oriented protocol is TCP. But, in connection-less protocol, acknowledgement is not sent by the
receiver. So it is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket : A socket is an endpoint between two way communications.

java.net package

CE-6th-A3-210130107049 11 Rudra Joshi


Advance Java Programming 3160707

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.

Safety and necessary Precautions:


1. Make sure the server/receiver program runs first
2. Handle all necessary compile time Exception

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.*;

public class MyServer {

public static String getSpace(int c) { // Adding Spaces For Decoration


String spaces = " ";

for (int i = 0; i < 12 - c; i++) {


spaces += " ";
}
return spaces;
}

public static String performOperation(String str, Connection con) {


String[] choice = str.split(" ");

String result = "";

if (choice[0].equals("1")) {
String name;

int stock, price;

name = choice[1];
stock = Integer.parseInt(choice[2]);
price = Integer.parseInt(choice[3]);

String insertQuery = String.format("INSERT INTO product_details(name,price,stock)


VALUES ('%s','%d','%d')",
name, price, stock);

CE-6th-A3-210130107049 12 Rudra Joshi


Advance Java Programming 3160707

String getIdQuery = "SELECT * FROM product_details ORDER BY id DESC";

try {

Statement st = con.createStatement();
st.execute(insertQuery);
ResultSet rs = st.executeQuery(getIdQuery);
rs.next();

final int id = rs.getInt("id");

result = "Entered Data Successfully with Generated id " + id + "\n";


st.close();

} 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);

result = "-----------------------------------\n Id Name Price Stock\n------------------------


-----------\n";

while (rs.next()) { // Particular Record


result = result + " " + rs.getInt("id") + " "
+ rs.getString("name") + MyServer.getSpace(rs.getString("name").length())
+ rs.getString("price") + MyServer.getSpace(rs.getString("price").length())
+ rs.getString("stock") + MyServer.getSpace(rs.getString("stock").length()) +
"\n";
}
st.close();

} 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]);

String updateQuery = String.format("UPDATE `product_details` SET

CE-6th-A3-210130107049 13 Rudra Joshi


Advance Java Programming 3160707

`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) {

result = "inventory Updated Successfully";


} else {

result = "inventory Product Not Found";


}

st.close();

} catch (Exception e) {
System.out.println(e);
}

} else if (choice[0].equals("4")) { // Delete the record with id


int id;
id = Integer.parseInt(choice[1]);

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) {

result = "Inventory Deleted Successfully";


} else {

result = "Inventory Product Not Found";


}

st.close();

} catch (Exception e) {
System.out.println(e);
}

} else {
result = "STOP";
}
return result;
}

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

CE-6th-A3-210130107049 14 Rudra Joshi


Advance Java Programming 3160707

String url = "jdbc:mysql://localhost:3306/ajp"; // table details


String username = "root"; // MySQL credentials

String password = "root1234";

Class.forName("com.mysql.cj.jdbc.Driver"); // Driver name

Connection con = DriverManager.getConnection(url, username, password); // Build


Connection
try {

ServerSocket ss = new ServerSocket(6666);


Socket s = ss.accept();// establishes connection

DataInputStream din = new DataInputStream(s.getInputStream());


DataOutputStream dout = new DataOutputStream(s.getOutputStream());

boolean cont = true;

while (cont) {
String str = (String) din.readUTF();

String result = performOperation(str, con);


dout.writeUTF(result);

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;

public class MyClient {


public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6666);

CE-6th-A3-210130107049 15 Rudra Joshi


Advance Java Programming 3160707

DataOutputStream dout = new DataOutputStream(s.getOutputStream());


DataInputStream din = new DataInputStream(s.getInputStream());

Scanner sc = new Scanner(System.in);

System.out.println("Product Inventory Management System");


System.out.println("Don't Include Space In Any Input.");
System.out.println("Enter Choice and its argument space seperated");
System.out.println("1: Create 2: Read 3: Update 4: Delete Other: Exit");

while (true) {
int c = sc.nextInt();

String query = Integer.toString(c);


switch (c) {
case 1:
System.out.print("Enter Name : ");
String name = sc.next();
System.out.print("Enter Stock : ");

String stock = sc.next();


System.out.print("Enter Price : ");
String price = sc.next();

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();

query += " " + idD;


}
dout.writeUTF(query);
String str2 = din.readUTF();

System.out.println(str2);
if (c > 4 || c < 1) {
break;
}
}

CE-6th-A3-210130107049 16 Rudra Joshi


Advance Java Programming 3160707

dout.flush();
dout.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}

}
}

Output:

22

CE-6th-A3-210130107049 17 Rudra Joshi


Advance Java Programming 3160707

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.

In network programming, `InetAddress` is commonly used for the following


purposes:

1. Resolving Hostnames to IP Addresses: You can use the `getByName()` method of


`InetAddress` to obtain an IP address corresponding to a hostname. This is useful
for converting human-readable domain names into IP addresses.

2. Obtaining Information about IP Addresses: The `InetAddress` class provides


methods to retrieve information about an IP address, such as the hostname
associated with it (`getHostName()`) or the IP address itself (`getHostAddress()`).

3. Checking Reachability: The `isReachable()` method allows you to check whether a


particular host is reachable from the local machine. This can be useful for network
diagnostics or determining the availability of remote hosts.

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:

CE-6th-A3-210130107049 18 Rudra Joshi


Advance Java Programming 3160707

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.

3. How can we do network programming using UDP in java? Explain DatagramSocket


and DatagramPacket in Java.
o In Java, network programming using UDP (User Datagram Protocol) is
accomplished using the `DatagramSocket` and `DatagramPacket` classes.

Here's how these classes are typically used:

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.

CE-6th-A3-210130107049 19 Rudra Joshi


Advance Java Programming 3160707

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

Suggested Reference: Professional Java Server Programming by Subrahmanyam Allamaraju,


Cedric Buest Wiley Publication

References used by the students:


https://www.javatpoint.com/java-networking

Rubric wise marks obtained:


Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

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

CE-6th-A3-210130107049 20 Rudra Joshi


Advance Java Programming 3160707

Experiment No: 3
Modify practical 1 by replacing the console based user interface to a web based user interface. Use
a servlet.

Date:

Competency and Practical Skills: Design a web application using Servlet

Relevant CO: CO2

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

CE-6th-A3-210130107049 21 Rudra Joshi


Advance Java Programming 3160707

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

CE-6th-A3-210130107049 22 Rudra Joshi


Advance Java Programming 3160707

<!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>

<a href="index.html"><input type="submit"


value="Submit"></a> </form>
</div>
</body>
</html>

//delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete</title>
</head>

CE-6th-A3-210130107049 23 Rudra Joshi


Advance Java Programming 3160707

<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..."/>

<a href="index.html"></a><input type="submit" value="Submit" /></a>

</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

CE-6th-A3-210130107049 24 Rudra Joshi


Advance Java Programming 3160707

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="update" method="post">
<label for="p_id">Product id:</label><br />
<input type="number" id="p_id" name="p_id" placeholder="Product Id..."
/><br />
<label for="p_stock">Enter Stock:</label><br />
<input type="number" id="p_stock" name="p_stock" placeholder="Quantity..."
/><br />
<label for="p_price">Enter Price:</label><br />
<input type="number" id="p_price" name="p_price" placeholder="Price..."
/><br />
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>

// 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;

public class create extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {
try {
String pName = req.getParameter("p_name");
String pStock = req.getParameter("p_stock");
String pPrice = req.getParameter("p_price");

String url = "jdbc:mysql://localhost:3306/advancejava";


String username = "root";
String password = "Firebase";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, username, password);

CE-6th-A3-210130107049 25 Rudra Joshi


Advance Java Programming 3160707

PreparedStatement pre = con.prepareStatement("INSERT INTO


inventory(p_name,p_price,p_stock) VALUES (?,?,?)");

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;

public class delete extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {
try {
String pId = req.getParameter("p_id");
String url = "jdbc:mysql://localhost:3306/advancejava";
String username = "root";
String password = "Firebase";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, username, password);

PreparedStatement pre = con.prepareStatement("DELETE FROM `inventory` WHERE


p_id=?");

pre.setInt(1,Integer.parseInt(pId));

pre.execute();
System.out.println("Product Delete Sucessfully");

CE-6th-A3-210130107049 26 Rudra Joshi


Advance Java Programming 3160707

} catch (Exception e) {
// e.printStackTrace(e.mesa);
System.out.println(e.getMessage());
}
}
}
//service.java

package com.test.servlet;

import java.sql.*;

public class service {

public product printData() {


String url = "jdbc:mysql://localhost:3306/advancejava";
String username = "root";
String password = "Firebase";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch
(ClassNotFoundException
e) { throw new
RuntimeException(e);
}
int size = 0;

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 {

// pro = new product(null, null, 0);


Connection con = DriverManager.getConnection(url, username,
password); Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT * FROM
inventory "); int start = 1;
while (start <= size) {
// rs.abso
lute(sta

CE-6th-A3-210130107049 27 Rudra Joshi


Advance Java Programming 3160707

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);

PreparedStatement pre = con.prepareStatement("UPDATE `inventory` SET


`p_price`=?,`p_stock`=? WHERE p_id=?");

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());

CE-6th-A3-210130107049 28 Rudra Joshi


Advance Java Programming 3160707

}
}
}
//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.*;

public class view extends HttpServlet {

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// super.doPost(req, resp);

PrintWriter out = resp.getWriter();

String url = "jdbc:mysql://localhost:3306/advacnejava";


String username = "root";
String password = "Firebase";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch
(ClassNotFoundExcepti
on e) { throw new
RuntimeException(e);
}
try {

Connection con = DriverManager.getConnection(url, username, password);


Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT * FROM inventory ");

int size = 0;
while(rs.next()){
size++;
}

service ser = new service();

out.println("<html>");
out.println("<body>");
out.println("<table>");

CE-6th-A3-210130107049 29 Rudra Joshi


Advance Java Programming 3160707

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

CE-6th-A3-210130107049 30 Rudra Joshi


Advance Java Programming 3160707

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:

1) Scalability: Enterprise applications are designed to handle large volumes of users,


data, and transactions, and can scale horizontally or vertically to accommodate
growing demands.

2) Reliability: They are highly reliable and robust, ensuring minimal downtime and
consistent performance even under heavy loads.

3) Security: Enterprise applications implement stringent security measures to protect


sensitive data and prevent unauthorized access, including encryption,
authentication, and authorization mechanisms.

4) Integration: They often integrate with various systems and technologies within an
organization, such as databases, legacy systems, third-party applications, and
external APIs.

CE-6th-A3-210130107049 31 Rudra Joshi


Advance Java Programming 3160707

5) Customization: Enterprise applications are customizable to suit the specific needs


and workflows of different organizations or departments within an organization.

6) Modularity: They are typically built using modular architectures, allowing


components to be developed, deployed, and maintained independently, facilitating
easier upgrades and enhancements.

7) Scalable Architecture: Enterprise applications often employ distributed


architectures such as microservices or service-oriented architectures (SOA) to
facilitate scalability, maintainability, and flexibility.

8) High Performance: They are optimized for performance, ensuring fast response
times and efficient resource utilization.

9) Compliance: Enterprise applications adhere to regulatory compliance standards


relevant to the industry they serve, such as GDPR, HIPAA, or PCI DSS.

10) Analytics and Reporting: They provide extensive analytics and reporting
capabilities to help organizations derive insights from their data and make
informed business decisions.

11) Cross-Platform Compatibility: Enterprise applications are often designed to work


seamlessly across multiple platforms, including desktop, web, and mobile
devices.

2. Draw and explain servlet life cycle.

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 creates an instance of the servlet.


• The servlet container calls the servlet's init() method.

CE-6th-A3-210130107049 32 Rudra Joshi


Advance Java Programming 3160707

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

3. Compare servlet with JSP.


o Servlets and JavaServer Pages (JSP) are both technologies used in Java web
development, but they serve different purposes and have distinct characteristics.
Here's a comparison between Servlets and JSP:
1) Purpose:
- Servlets: Servlets are Java classes that dynamically process and respond to client
requests on the server-side. They handle the business logic, interact with
databases, and generate dynamic content.
- JSP: JSP (JavaServer Pages) is a technology that allows embedding Java code into
HTML pages to create dynamic web content. JSPs are primarily used for
generating the presentation layer of web applications.

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:

CE-6th-A3-210130107049 33 Rudra Joshi


Advance Java Programming 3160707

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

4. What is session tracking? How can we implement it in Servlet?


o Session tracking is a mechanism used in web development to maintain the state of
a user's interaction with a web application across multiple requests. It allows the
server to recognize a specific user and retain information about their activities,
preferences, and session-specific data.

In Servlets, session tracking can be implemented using various techniques:

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.

CE-6th-A3-210130107049 34 Rudra Joshi


Advance Java Programming 3160707

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

References used by the students:


https://www.javatpoint.com/servlet-tutorial

Rubric wise marks obtained:


Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

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

CE-6th-A3-210130107049 35 Rudra Joshi


Advance Java Programming 3160707

Experiment No: 4

Modify the practical 4 to use JSP instead of Servlet.

Date:

Competency and Practical Skills: Design a web application using JSP

Relevant CO: CO2

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

CE-6th-A3-210130107049 36 Rudra Joshi


Advance Java Programming 3160707

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%

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 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:

<%@ page import="java.sql.*" %>


<%
// 1. Connect to the database
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);

// 2. Execute a SELECT query


and get the result set Statement
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM inventory");

// 3. Create a HTML table and display the data


out.println("<table>");
out.println("<tr><th>ID</th><th>Name</th><t
h>Age</th></tr>"); while (rs.next()) {

String name =
rs.getString("p_name
"); int price =
rs.getInt("p_price");

CE-6th-A3-210130107049 37 Rudra Joshi


Advance Java Programming 3160707

int stock = rs.getInt("p_stock");


out.println("<tr><td>" + name + "</td><td>" + price + "</td><td>" + stock + "</td></tr>");
}
out.println("</table>");

// 4. Close the result set, statement, and connection


rs.close();
stmt.close();
conn.close();
%>

OUTPUT:

Home Page

Add Item
Read Item

Update Item

CE-6th-A3-210130107049 38 Rudra Joshi


Advance Java Programming 3160707

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.

2. List and explain JSP implicit objects.


• page: This object represents the current JSP page.
• request: This object represents the HTTP request that was made to the JSP page.
• response: This object represents the HTTP response that will be sent to the
client.
• session: This object represents the user's session.
• application: This object represents the web application.

3. What is the difference between include directive and include action?


The difference between include directive and include action is that include directive is
used to include static content in a JSP page, while include action is used to include
dynamic content in a JSP page.

CE-6th-A3-210130107049 39 Rudra Joshi


Advance Java Programming 3160707

4. How can we forward a request from JSP to servlet?


To forward a request from JSP to servlet, you can use the <jsp:forward> tag. The
<jsp:forward> tag takes two attributes: page and url. The page attribute specifies the
path to the servlet that you want to forward the request to. The url attribute specifies
the URL of the servlet that you want to forward the request to.

Suggested Reference:
Complete Reference J2EE by James Keogh mcgraw publication
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley Publication

References used by the students:


https://www.geeksforgeeks.org/introduction-to-jsp/

Rubric wise marks obtained:


Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

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

CE-6th-A3-210130107049 40 Rudra Joshi


Advance Java Programming 3160707

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

Relevant CO: CO3

Objectives: (a) implement dynamic web-application using JSF framework.

Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Apache Tomcat Server,


Netbeans/eclipse, Oracle Xpress edition 11g, Type4 JDBC driver for Oracle, JSF2.2 jar file

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 −

• Providing reusable UI components


• Making easy data transfer between UI components
• Managing UI state across multiple server requests
• Enabling implementation of custom components
• Wiring client-side event to server-side application code
JSF Architecture

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

The faces-config.xml defines:

CE-6th-A3-210130107049 41 Rudra Joshi


Advance Java Programming 3160707

• 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

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 database for your project
2) Open netbeans and create a new project (web application with JSF)

CE-6th-A3-210130107049 42 Rudra Joshi


Advance Java Programming 3160707

CE-6th-A3-210130107049 43 Rudra Joshi


Advance Java Programming 3160707

CE-6th-A3-210130107049 44 Rudra Joshi


Advance Java Programming 3160707

CE-6th-A3-210130107049 45 Rudra Joshi


Advance Java Programming 3160707

3) Add or modify the code in files mentioned in above screenshot


4) Run the project.

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();
}

public List<Item> getItems() {


return Items;
}

public Item getNewItem() {


return newItem;
}

public Item getSelectedItem() {


return selectedItem;
}

public void setSelectedItem(Item selectedItem) {


this.selectedItem = selectedItem;
}

public void addItem() {


// Add the new Item to the database
try (Connection conn = getConnection()) {
String query = "INSERT INTO Items (Item_id, customer_id, route_id, customer_route,
booked_amount, booked_seat) " +

CE-6th-A3-210130107049 46 Rudra Joshi


Advance Java Programming 3160707

"VALUES (?, ?, ?, ?, ?, ?)";


PreparedStatement statement =
conn.prepareStatement(query);
statement.setString(1, newItem.getItemId());
statement.setString(2, newItem.getCustomerId());
statement.setString(3, newItem.getRouteId());
statement.setString(4, newItem.getCustomerRoute());
statement.setInt(5, newItem.getBookedAmount());
statement.setString(6, newItem.getBookedSeat());
statement.executeUpdate();
statement.close();
newItem = new Item(); // Reset the new Item form
loadItems(); // Refresh the Items list
} catch (SQLException e) {
e.printStackTrace();
}
}

public void updateItem() {


// Update the selected Item in the
database try (Connection conn =
getConnection()) {
String query = "UPDATE Items SET Item_id=?, customer_id=?, route_id=?,
customer_route=?, " + "booked_amount=?, booked_seat=? WHERE id=?";
PreparedStatement statement =
conn.prepareStatement(query);
statement.setString(1, selectedItem.getItemId());
statement.setString(2,
selectedItem.getCustomerId());
statement.setString(3, selectedItem.getRouteId());
statement.setString(4,
selectedItem.getCustomerRoute());
statement.setInt(5,
selectedItem.getBookedAmount());
statement.setString(6,
selectedItem.getBookedSeat()); statement.setInt(7,
selectedItem.getId()); statement.executeUpdate();
statement.close();
selectedItem = null; //
Deselect the Item
loadItems(); // Refresh the
Items list
} catch
(SQLExceptio
n e) {
e.printStackTr
ace();
}
}

CE-6th-A3-210130107049 47 Rudra Joshi


Advance Java Programming 3160707

public void deleteItem() {


// Delete the selected Item from
the database try (Connection conn
= getConnection()) {
String query = "DELETE FROM Items WHERE
id=?"; PreparedStatement statement =
conn.prepareStatement(query); statement.setInt(1,
selectedItem.getId()); statement.executeUpdate();
statement.close();
selectedItem = null; //
Deselect the Item
loadItems(); // Refresh the
Items list
} catch
(SQLExceptio
n e) {
e.printStackTr
ace();
}
}

private void loadItems() {


Items = new ArrayList<>();
try (Connection conn = getConnection()) {
String query = "SELECT * FROM
Items"; Statement statement =
conn.createStatement(); ResultSet
resultSet =
statement.executeQuery(query);

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");

Item Item = new Item(id, ItemId, customerId, routeId, customerRoute, bookedAmount,


bookedSeat);
Items.add(Item);
}

resultSet.close();

CE-6th-A3-210130107049 48 Rudra Joshi


Advance Java Programming 3160707

statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

private Connection getConnection() throws


SQLException { String url =
"jdbc:mysql://localhost:3306/sbtbsphp";
String user = "root";
String password = "password";
return DriverManager.getConnection(url, user, password);
}
}

//item
public class Item {
private Connection connection;
private String name;
private String id;
private int stock;
private int price;

public Connection getConnection() {


return connection;
}

public void setConnection(Connection connection) {


this.connection = connection;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public int getStock() {


return stock;

CE-6th-A3-210130107049 49 Rudra Joshi


Advance Java Programming 3160707

public void setStock(int stock) {


this.stock = stock;
}

public int getPrice() {


return price;
}

public void setPrice(int price) {


this.price = price;
}

public Item(){

//Output:

Home Page

Add Item

Read Item

CE-6th-A3-210130107049 50 Rudra Joshi


Advance Java Programming 3160707

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

2. Draw and Explain JSF life cycle.

Phase 1: Restore view


JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives
a request. During this phase, JSF builds the view, wires event handlers and validators to UI
components and saves the view in the FacesContext instance. The FacesContext instance
will now contain all the information required to process a request.
Phase 2: Apply request values
After the component tree is created/restored, each component in the component tree uses

CE-6th-A3-210130107049 51 Rudra Joshi


Advance Java Programming 3160707

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.

3. What is the significance of managed beans in Java Server Faces?


Managed beans in JSF are Java classes used to manage application data and perform
business logic. They act as a bridge between the UI components and the backend
application logic

4. List the advantages of using Facelet.

Improved templating and reuse of UI components


Support for creation of custom components
Improved performance due to reduced overhead and better caching mechanisms.

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

References used by the students:


https://www.tutorialspoint.com/jsf/index.htm

CE-6th-A3-210130107049 52 Rudra Joshi


Advance Java Programming 3160707

Rubric wise marks obtained:


Knowledge of Programming Team work (2) Communication Skill Ethics(2)
subject (2) Skill (2)

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

CE-6th-A3-210130107049 53 Rudra Joshi


Advance Java Programming 3160707

Experiment No: 6
Make custom tag for a component that will be able to add/view/delete/modifyRecords

Date:

Competency and PracticalSkills:programming and database commands

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.

Advantages of Custom Tags


The key advantages of Custom tags are as follows:

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.

Safety and necessary Precautions:


3) Make sure the database server is started before running the program
4) Make sure the Web Server is started before calling the jsp page.
5) Handle all necessary compile time Exception

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:

CE-6th-A3-210130107049 54 Rudra Joshi


Advance Java Programming 3160707

Custom Tag File:-


package com.JSF;

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;

public class MaterialTag extends TagSupport {

public class Item {


private Connection connection;
private String name;
private String id;
private int stock;
private int price;

public Connection getConnection() {


return connection;
}

public void setConnection(Connection


connection) { this.connection =
connection;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public int getStock() {


return stock;
}

public void setStock(int stock) {

CE-6th-A3-210130107049 55 Rudra Joshi


Advance Java Programming 3160707

this.stock = stock;
}

public int getPrice() {


return price;
}

public void setPrice(int price) {


this.price = price;
}

public Item(){

public String add() throws


ClassNotFoundException{ try {
Class.forName("com.mysql.jdbc.Driver");
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
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";
}
}
public int doStartTag() throws
JspException { try {
JspWriter out = pageContext.getOut();

Connection conn =
Practical_01_DataBase.getConnection();
Statement stmt = conn.createStatement();

// Perform the appropriate operation


based on the selected option if
(operation.equals("add")) {

Practical_01_DataBase.insertBookDetail(stmt, new Book(bid, title,


author, pages, publisher, year, language));
out.print("<h1>Material Added Successfully!</h1>");
}

CE-6th-A3-210130107049 56 Rudra Joshi


Advance Java Programming 3160707

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 Modified Successfully!</h1>");


} else if (operation.equals("delete")) {
Practical_01_DataBase.deleteBook
Detail( stmt, bid);

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;
}
}

TlD File for CustomTag :-


<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD
JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-
jsptaglibrary_1_2.dtd">

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

CE-6th-A3-210130107049 57 Rudra Joshi


Advance Java Programming 3160707

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

CustomTag of JSP File for Tag :-

<%@ page language="java"


contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/mylib.tld"
prefix="t" %> <%@ page
import="com.sarang.MaterialTag" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
// Get the parameter values
from the request String
BidStr =

CE-6th-A3-210130107049 58 Rudra Joshi


Advance Java Programming 3160707

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>

Servlet class File for Book :-

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;

CE-6th-A3-210130107049 59 Rudra Joshi


Advance Java Programming 3160707

public class Practical_04_MaterialServlet extends HttpServlet {


protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
request.getRequestDispatcher("/item.jsp").
forward(request, response);
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
RequestDispatcher rd =
request.getRequestDispatcher("/tag.js
p"); rd.forward(request, response);

} catch
(SQLException
e) {
e.printStackTrac
e();
}
}
}
}
CustomTag of jsp file for Book :-

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="UTF-8">
<title>Book Details</title>
</head>
<body>
<h2>Book Details</h2>
<form action="MaterialServlet2" method="post">
<label for="name">Name</label>
<input type="text" id="title" name="p_name"><br><br>

<label for="price">Stock</label>
<input type="text" id="author" name="p_price"><br><br>

<label for="stock">Price</label>

CE-6th-A3-210130107049 60 Rudra Joshi


Advance Java Programming 3160707

<input type="submit" value="Submit">


</form>
</body>
</html>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output:-

Form for Add ,delete,modify and View from Database:-

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

Types of Custom Tags:


• JSP Custom Tags - Used to extend JSP's capabilities
• Simple Tags - A newer, simpler way of defining custom tags in JSP.
• Tag Files - A way of defining tags as JSP files.

2) What are the methods of Tag interface? Explain their importance.


• doStartTag() - Used to begin the processing of the tag.

• doEndTag() - Used to complete the processing of the tag.

• doAfterBody() - Used to process the body of the tag after the doStartTag()
method has been called.

• setParent() - Used to set the parent tag of the current tag.

• setPageContext() - Used to set the page context object for the tag.

3) Write and Explain the TLD file structure and steps for creating it.

• <taglib> - The root element of the TLD file.

• <tlib-version> - Specifies the version of the tag library.

• <uri> - Specifies the URI of the tag library.

• <tag> - Defines a custom tag.

• <name> - Specifies the name of the custom tag.

• <tag-class> - Specifies the fully qualified name of the tag handler class.

• <body-content> - Specifies the type of body content expected by the tag.

• <attribute> - Defines an attribute of the custom tag.

a. Create a new XML file with a .tld extension.

b. Define the tag library using the <taglib> element.

c. Define the custom tags using the <tag> element.

d. Define the attributes of the custom tags using the <attribute> element.

e. Save the file in the WEB-INF directory of your web application.

Suggested Reference:
https://docs.oracle.com/cloud/latest/as111170/TAGLB/quickstart.htm

References used by the students:


CE-6th-A3-210130107049 61 Rudra Joshi
Advance Java Programming 3160707

https://docs.oracle.com/cloud/latest/as111170/TAGLB/quickstart.htm

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks

CE-6th-A3-210130107049 62 Rudra Joshi


Advance Java Programming 3160707

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:

Competency and PracticalSkills: programming and database commands

Relevant CO: CO4

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

Following are the advantages of hibernate framework:

1) Open Source and Lightweight

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.

3) Database Independent Query

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.

4) Automatic Table Creation

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.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status


CE-6th-A3-210130107049 63 Rudra Joshi
Advance Java Programming 3160707

Hibernate supports Query cache and provide statistics about query and database status.

Elements of Hibernate Architecture

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

It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is


optional.

TransactionFactory

It is a factory of Transaction. It is optional.

Safety and necessary Precautions:


3. Make sure the database server is up and running.
4. Make sure all the hibernet libraries are put in the classpath
5. Make sure the web server is up and running
6. Handle all necessary compile time Exception

Procedure:
For creating the first hibernate application, we need to follow the following steps:

1. Create the Persistent class


2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application by using command prompt

CE-6th-A3-210130107049 64 Rudra Joshi


Advance Java Programming 3160707

Observations:

Hibernate Configuration File :

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-
configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property
name="connection.url">jdbc:mysql://localhost/library_managment</property> <property
name="connection.username">root</property> <property
name="connection.password">Jatin@123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>

<!-- SQL dialect -->


<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

<!-- Disable the second-level cache -->


<property
name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->


<property name="show_sql">true</property>
<mapping class="com.javaProject.firstJavaProject.Data"/>

</session-factory>
</hibernate-configuration>

Pom.Xml Configuration file for Hibernate :-

Data File of Java :

package com.javaProject.firstJavaProject; import javax.persistence.Entity;


import javax.persistence.Table; import javax.persistence.*;

@Entity
@Table(name = "book1") public class Item {
private Connection connection;
private String name;
private String id;
private int stock;
private int price;

CE-6th-A3-210130107049 65 Rudra Joshi


Advance Java Programming 3160707

public Connection getConnection() {


return connection;
}

public void setConnection(Connection connection) {


this.connection = connection;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public int getStock() {


return stock;
}

public void setStock(int stock) {


this.stock = stock;
}

public int getPrice() {


return price;
}

public void setPrice(int price) {


this.price = price;
}

public Item(){

public String add() throws ClassNotFoundException{


try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
CE-6th-A3-210130107049 66 Rudra Joshi
Advance Java Programming 3160707

"");
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
}}

App.Java File For HQL Query :-

package com.javaProject.firstJavaProject; import java.util.*;

import org.hibernate.Query;
import org.hibernate.service.ServiceRegistryBuilder; import
org.hibernate.service.ServiceRegistry;

public class App


{
private static final SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();

public static void main( String[] args )


{

Configuration config = new Configuration().configure().addAnnotatedClass(Data.class);


ServiceRegistry registry = new
ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
SessionFactory sf = config.buildSessionFactory(registry);
Session session = sf.openSession(); session.beginTransaction();
Query q = session.createQuery("from Data");
List<Data> datas = q.list(); for(Data d : datas) {
System.out.println(d);
}

Sf.close();

CE-6th-A3-210130107049 67 Rudra Joshi


Advance Java Programming 3160707

OUTPUT:

(Add Data)

(Read Data)

(Update Data)

(Delete Data)

CE-6th-A3-210130107049 68 Rudra Joshi


Advance Java Programming 3160707

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?

• Relational mismatch refers to the differences between object-oriented


programming language and the relational database model. Hibernate is an
ORM framework that can be used to overcome this mismatch by providing a
mapping between Java objects and database tables.

2. What is HQL? How is it different? What are the advantages?

• HQL (Hibernate Query Language) is an object-oriented query language


provided by Hibernate, which is similar to SQL, but it works with
• Hibernate's persistent objects
• instead of database tables. HQL allows developers to express database queries in
an object-oriented way, making it more natural and intuitive for Java developers.
The advantages of using HQL include portability, security, and ease of use.

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:

• Create an XML file with a name like hibernate.cfg.xml


• Define the database connection properties, such as the JDBC driver,
database URL, username, and password.
• Specify the Hibernate dialect for your database.
• Define the mapping between your Java classes and database tables.
• Set any other configuration properties, such as caching or transaction
management.

Suggested Reference:
https://docs.oracle.com/cd/E11035_01/workshop102/ormworkbench/hibernate-
tutorial/tutHibernate1.html

References used by the students:


CE-6th-A3-210130107049 69 Rudra Joshi
Advance Java Programming 3160707

https://docs.oracle.com/cd/E11035_01/workshop102/ormworkbench/hibernatetutorial/tutHibernate1.html

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks

CE-6th-A3-210130107049 70 Rudra Joshi


Advance Java Programming 3160707

Experiment No: 8
Use Hibernet framework to replace JDBC calls and calculate the reduction in programming
efforts for the entire application
Date:

Competency and PracticalSkills: programming and database commands

Relevant CO: CO3

Objectives: (a) To be able implement the hibernet concepts in a project.


(b) To be able to implement the hibernet and HQL for complex SQL queries and
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.Hibernet
framework.

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

• publicintexecuteUpdate() is used to execute the update or delete query.


• public List list() returns the result of the ralation as a list.
• public Query setFirstResult(introwno) specifies the row number from where record will be
retrieved.
• public Query setMaxResult(introwno) specifies the no. of records to be retrieved from the
relation (table).
• public Query setParameter(int position, Object value) it sets the value to the JDBC style
query parameter.
• public Query setParameter(String name, Object value) it sets the value to a named query
parameter.

Safety and necessary Precautions:


1) Make sure the database server is started before running the program
2) Make sure the Web Server is started before calling the jsp page.
3) Make sure Hibernet libraries are put in the dependencies for compiling.
4) Handle all necessary compile time Exception
CE-6th-A3-210130107049 71 Rudra Joshi
Advance Java Programming 3160707

Procedure:
For creating the first hibernate application in Eclipse IDE, we need to follow the following steps:

1. Create the java project


2. Add jar files for hibernate
3. Create the Persistent class
4. Create the mapping file for Persistent class
5. Create the Configuration file
6. Create the class that retrieves or stores the persistent object
7. Run the application

Observations:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-
3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property
name="connection.url">jdbc:mysql://localhost/library_managment</property> <property
name="connection.username">root</property> <property
name="connection.password">Jatin@123</property>

<!-- JDBC connection pool (use the built-in) -->


<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

<!-- Disable the second-level cache -->


<property
name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</pr
operty>

<!-- Echo all executed SQL to stdout -->


<property name="show_sql">true</property>
<mapping class="com.javaProject.firstJavaProject.Data"/>

</session-factory>
</hibernate-configuration>

App.Java File For HQL Query :-

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();

static void insertBookDetail(Data newData) {


Session session =
sessionFactory.openSession();
Transaction transaction =
session.beginTransaction();
session.save(newData);
transaction.com
mit();
session.close();
}

static List<Data> searchData(String


searchString) { Session session =
sessionFactory.openSession(); String hql
= "from test d where ";
Map<String, Object> params = new HashMap<String, Object>();
hql += "d.p_name like :search or d.p_price like :search or d.p_name like :search ";

params.put("search", "%" + searchString

CE-6th-A3-210130107049 73 Rudra Joshi


Advance Java Programming 3160707

+ "%"); 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;
}

static void updateBookDetails(Data updatedData) {


Session session = sessionFactory.openSession();
Transaction transaction =
session.beginTransaction();
Data data = (Data) session.get(Data.class,
updatedData.getBid());
data.setTitle(updatedData.getTitle());

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.

HQL supports database independence by using the concept of Object-


Relational Mapping (ORM), where HQL queries are written in terms of entities
and their properties rather than specific SQL statements. For example, consider
the following HQL query:
● SELECT e FROM Employee e WHERE e.salary > 50000
This query is written in terms of the Employee entity and its salary property,
which are mapped to the corresponding database table and column. HQL
automatically generates the appropriate SQL statement for the underlying
database, thus providing database independence.

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:

● SELECT d FROM Department d WHERE d.name = 'Sales'


This query returns a list of Department objects, each of which may contain a
list of associated Employee objects. By using lazy loading, the Employee
objects are only loaded from the database when they are accessed by the
application, thus reducing the number of object queries.

3) Explain the difference between JPA and Hibernet .


JPA (Java Persistence API) is a standard interface for ORM frameworks that provides a
common set of APIs for managing persistent objects in Java applications. Hibernate is an
ORM framework that implements the JPA specification, as well as providing its own
additional features and APIs. In other words, JPA is a specification, while Hibernate is an
implementation of that specification.

CE-6th-A3-210130107049 75 Rudra Joshi


Advance Java Programming 3160707

Suggested Reference:
https://docs.oracle.com/cloud/latest/as111170/TAGLB/quickstart.htm

References used by the students:


https://docs.oracle.com/cloud/latest/as111170/TAGLB/quickstart.htm

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks

CE-6th-A3-210130107049 76 Rudra Joshi


Advance Java Programming 3160707

Experiment No: 9
Use Spring or any other MVC architecture and implement the Interface in that architecture
that supports multi-tier architecture.
Date:

Competency and PracticalSkills: programming and database commands

Relevant CO: CO5

Objectives: (a) To understand MVC architecture.


(b) To understand and use Spring as a reference MVC architecture for ease of
programming
(c) To assess the impact of using a framework instead of pure JSP file for
development, maintenance etc.
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse, Spring and
Hibernetframwork

Theory:

Spring is a lightweight framework. It can be thought of as a framework of frameworks because it


provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The
framework, in broader sense, can be defined as a structure where we find solution of the various
technical problems.

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.

Inversion Of Control (IOC) and Dependency Injection


These are the design patterns that are used to remove dependency from the programming code.
They make the code easier to test and maintain. Let's understand this with the following code:

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.

Advantage of Dependency Injection


• makes the code loosely coupled so easy to maintain
• makes the code easy to test

Advantages of Spring Framework


There are many advantages of Spring Framework. They are as follows:

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.

Safety and necessary Precautions:


1. Make sure the database server is up and running.
2. Make sure all the hibernet and spring libraries are put in the classpath
3. Make sure the web server is up and running
4. Handle all necessary compile time Exception

Procedure:
CE-6th-A3-210130107049 78 Rudra Joshi
Advance Java Programming 3160707

Spring MVC CRUD Example


CRUD (Create, Read, Update and Delete) application is the most important application for creating
any project. It provides an idea to develop a large project. In spring MVC, we can develop a simple
CRUD application.

Here, we are using JdbcTemplate for database interaction.

- Create a table

1. Add dependencies to pom.xml file.


2. Create the bean class
3. Create the controller class
4. Create the DAO class
5. Provide the entry of controller in the web.xml file
6. Define the bean in the xml file spring-servlet.xml
7. Create the requested page
8. Create the other view components

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;

CE-6th-A3-210130107049 79 Rudra Joshi


Advance Java Programming 3160707

public void addItem(item


item) { items.save(item);
}

public void removeItem(int


pId) { items.deleteById(pId);
}

public List<Book> searchItem(String name, int pId) {


return items.find(name, pId);
}

}
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:

CE-6th-A3-210130107049 80 Rudra Joshi


Advance Java Programming 3160707

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.

2. What is MVC? Why is it important?


MVC (Model-View-Controller) is a software design pattern used to separate
application logic into three interconnected components. It is important because it
promotes separation of concerns, making it easier to maintain, modify, and test code.

3. Explain the roles of MVC components for a web application.


MVC (Model-View-Controller) is a software design pattern used to separate
application logic into three interconnected components. It is important because it
promotes separation of concerns, making it easier to maintain, modify, and test code.

Suggested Reference:
https://spring.io/

References used by the students:


https://spring.io/

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks

CE-6th-A3-210130107049 82 Rudra Joshi


Advance Java Programming 3160707

Experiment No: 10
Compare and analyze the JSF with the Spring framework. Use JSF for creating a CRUD
operation.

Date:

Competency and PracticalSkills: programming and database commands

Relevant CO: CO5

Objectives: (a) To understand MVC architecture.


(b) To understand and use JSF to replace JSTL and custom tags for a JSP file.
(c) To assess the impact of using a framework instead of pure JSP file for
development, maintenance etc. and compare JSF with Spring.
.
Equipment/Instruments: Personal Computer, JDK 1.8 or advance, Netbeans/eclipse, JSF and
Hibernetframwork

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.

Benefits of JavaServer Faces


1) It provides clean and clear separation between behavior and presentation of web application. You
can write business logic and user interface separately.

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.

Safety and necessary Precautions:


1. Make sure the database server is up and running.
2. Make sure all the hibernet and JSF libraries are put in the classpath
CE-6th-A3-210130107049 83 Rudra Joshi
Advance Java Programming 3160707

3. Make sure the web server is up and running


4. Handle all necessary compile time Exception

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.

Create a New Project

- Go to file menu and select new Project.-> Select Category Java Web and Project Web
Application. -> Enter project name.

- Select Server and Java EE Version.

- Select JSF Framework

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

This project includes following files:

- index.xhtml: inside the Web Pages directory


- web.xml: inside the WEB-INF directory

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.

It requires the following steps in order to develop new application:

- Creating user interface


- Creating managed beans
- Configuring and managing FacesServlet

Observations:

Index.Xhtml :-

<?xml version="1.0" encoding="ISO-8859-1" ?>


CE-6th-A3-210130107049 84 Rudra Joshi
Advance Java Programming 3160707

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//E <html

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>

Item ID : <h:inputText value="#{crud.p_id}"></h:inputText>

<br></br>
<br></br>

Item Name : <h:inputText value="#{crud.p_name}"></h:inputText>

<br></br>
<br></br>

Item Stock : <h:inputText value="#{crud.p_stock}"></h:inputText>

<br></br>
<br></br>
Item Price : <h:inputText value="#{crud.p_price}"></h:inputText>

<h:commandButton id="cmdinsert" value="Submit"


action="myresponse"></h:commandButton>

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

CE-6th-A3-210130107049 85 Rudra Joshi


Advance Java Programming 3160707

<br></br>
<br></br>
<h:commandButton id="cmdinsert3" value="Update"
action="#{crud.update()}"></h:commandButton>

</h:form>
</h:body>
</html>
Crud.Java:-

public class Item {


private Connection connection;
private String name;
private String id;
private int stock;
private int price;

public Connection getConnection() {


return connection;
}

public void setConnection(Connection connection) {


this.connection = connection;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public int getStock() {


return stock;
}

public void setStock(int stock) {


this.stock = stock;
}

public int getPrice() {


CE-6th-A3-210130107049 86 Rudra Joshi
Advance Java Programming 3160707

return price;
}

public void setPrice(int price) {


this.price = price;
}

public Item(){

public String add() {


System.out.println("Data is added. ......................... ");
return "ok. ...................... ";
}

public String delete() {


System.out.println("Data is
deleted. ........................................................................ ");
return "ok. ...................... ";
}

public String update() {


System.out.println("Data is
updated. ........................................................................ ");
return "ok. ...................... ";
}

Output :

CE-6th-A3-210130107049 87 Rudra Joshi


Advance Java Programming 3160707

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

3. Explain the JSF lifecycle in detail.

Phase 1: Restore view


JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request.
During this phase, JSF builds the view, wires event handlers and validators to UI components and
saves the view in the FacesContext instance. The FacesContext instance will now contain all the
information required to process a request.
Phase 2: Apply request values
After the component tree is created/restored, each component in the component tree uses the
CE-6th-A3-210130107049 88 Rudra Joshi
Advance Java Programming 3160707

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

References used by the students:


https://www.oracle.com/java/technologies/javaserverfaces.html

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks

CE-6th-A3-210130107049 89 Rudra Joshi

You might also like