0% found this document useful (0 votes)
2 views253 pages

Java Ee Pract

The document provides a comprehensive guide for implementing various EJB applications, including a Currency Converter, Room Reservation System, Shopping Cart, and a Servlet Hit Count demonstration using different types of EJBs such as Stateless, Stateful, and Singleton Session Beans. Each application includes steps for creating projects in Eclipse, writing necessary Java classes and servlets, and deploying them on EJB-compatible servers like GlassFish, Payara, or WildFly. Additionally, it includes explanations of important code segments and answers to common questions about EJB concepts.

Uploaded by

anaaz101303
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)
2 views253 pages

Java Ee Pract

The document provides a comprehensive guide for implementing various EJB applications, including a Currency Converter, Room Reservation System, Shopping Cart, and a Servlet Hit Count demonstration using different types of EJBs such as Stateless, Stateful, and Singleton Session Beans. Each application includes steps for creating projects in Eclipse, writing necessary Java classes and servlets, and deploying them on EJB-compatible servers like GlassFish, Payara, or WildFly. Additionally, it includes explanations of important code segments and answers to common questions about EJB concepts.

Uploaded by

anaaz101303
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

Module 2: 7.

Implement the following EJB Applications

Step 1: Create an EJB Project

Open Eclipse

File → New → EJB Project

Project Name:

CurrencyConverterEJB

Click Finish.

Step 2: Create a Stateless Session Bean

Right-click CurrencyConverterEJB

New → Session Bean

Bean Name:

CurrencyBean

Bean Type:

Stateless

Click Finish.

Step 3: Write [Link]

package [Link];
import [Link];

@Stateless

public class CurrencyBean {

public double convert(double usd) {

double rate = 83.50;

return usd * rate;

Step 4: Create Dynamic Web Project

File → New → Dynamic Web Project

Project Name

CurrencyConverterWeb

Click Finish.
Step 5: Add EJB Project to Web Project

Right Click

CurrencyConverterWeb

Properties

Deployment Assembly

Add

Project

Select

CurrencyConverterEJB

Finish

Step 6: Create HTML File

Create
[Link]

inside

src/main/webapp

[Link]

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Currency Converter</title>

</head>

<body>

<h2>Currency Converter</h2>

<form action="CurrencyServlet" method="post">

Enter Amount in USD

<input type="text"

name="usd"
required>

<br><br>

<input type="submit"

value="Convert">

</form>

</body>

</html>

Step 7: Create Servlet

Right Click

src/main/java

New → Servlet

Servlet Name

CurrencyServlet
Step 8: Write [Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/CurrencyServlet")

public class CurrencyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@EJB

CurrencyBean bean;
protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

double usd = [Link](

[Link]("usd"));

double inr = [Link](usd);

[Link]("<html><body>");

[Link]("<h2>Currency Converter</h2>");

[Link]("<h3>");

[Link](usd + " USD = " + inr + " INR");


[Link]("</h3>");

[Link]("</body></html>");

Project Structure

CurrencyConverterEJB

└── src

└── [Link]

└── [Link]

CurrencyConverterWeb

├── src

│ │
│ └── [Link]

│ │

│ └── [Link]

└── src/main/webapp

└── [Link]

Run the Project

1. Start GlassFish, Payara, or WildFly.

2. Deploy both CurrencyConverterEJB and CurrencyConverterWeb.

3. Open the browser:

[Link]

Sample Input

USD = 10

Click Convert.

Sample Output

Currency Converter
10 USD = 835.0 INR

Explanation of Important Code

1. @Stateless

@Stateless

Declares CurrencyBean as a Stateless Session Bean.

2. @EJB

@EJB

CurrencyBean bean;

Injects the EJB into the servlet.

3. Read User Input

double usd = [Link](

[Link]("usd"));

Reads the USD amount entered by the user.

4. Call EJB Method

double inr = [Link](usd);


Calls the business method in the EJB to convert USD into INR.

5. Display Result

[Link](usd + " USD = " + inr + " INR");

Displays the converted amount in the browser.

Viva Questions

Q1. What is EJB?


Answer: EJB (Enterprise JavaBeans) is a server-side technology used to
implement business logic in enterprise Java applications.

Q2. What is a Stateless Session Bean?


Answer: A Stateless Session Bean does not store client-specific data
between method calls. Each request is handled independently.

Q3. What is the purpose of @EJB?


Answer: @EJB injects an Enterprise JavaBean into another class so its
methods can be used without creating the object manually.

Q4. Can this EJB application run on Apache Tomcat?


Answer: No. Tomcat is a Servlet container and does not support EJB. To
run this application, use an EJB-compatible server such as GlassFish,
Payara, or WildFly
b. Develop a Simple Room Reservation System Application Using EJB

Aim: Develop a Simple Room Reservation System using EJB (Enterprise


JavaBeans).

Note: EJB applications cannot run on Apache Tomcat. Use an EJB-


supported server such as GlassFish, Payara, or WildFly.

Step 1: Create EJB Project

Open Eclipse.
File → New → EJB Project

Project Name:

RoomReservationEJB

Click Finish.

Step 2: Create Stateless Session Bean

Right Click RoomReservationEJB

New → Session Bean

Bean Name:

RoomReservationBean

Bean Type:

Stateless

Click Finish.

Step 3: Write [Link]

package [Link];

import [Link];

@Stateless
public class RoomReservationBean {

public String reserveRoom(String name, int roomNo) {

if(roomNo >= 101 && roomNo <= 110) {

return "Reservation Successful<br>"

+ "Customer Name : " + name

+ "<br>Room Number : " + roomNo;

else {

return "Room Not Available";

}
Step 4: Create Dynamic Web Project

File → New → Dynamic Web Project

Project Name:

RoomReservationWeb

Click Finish.

Step 5: Add EJB Project

Right Click

RoomReservationWeb

Properties

Deployment Assembly

Add

Project

Select
RoomReservationEJB

Finish

Step 6: Create HTML File

Create [Link] inside

src/main/webapp

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Room Reservation</title>

</head>

<body>

<h2>Room Reservation System</h2>

<form action="RoomServlet" method="post">


Customer Name

<input type="text"

name="name"

required>

<br><br>

Room Number

<input type="number"

name="roomNo"

required>

<br><br>

<input type="submit"

value="Reserve Room">

</form>
</body>

</html>

Step 7: Create Servlet

Right Click

src/main/java

New → Servlet

Servlet Name

RoomServlet

Click Finish.

Step 8: Write [Link]

package [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/RoomServlet")

public class RoomServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@EJB

RoomReservationBean bean;

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

String name = [Link]("name");

int roomNo = [Link](

[Link]("roomNo"));

String result =

[Link](name, roomNo);

[Link]("<html><body>");

[Link]("<h2>" + result + "</h2>");

[Link]("</body></html>");

}
Step 9: Project Structure

RoomReservationEJB

└── src

└── [Link]

└── RoomReserva [Link]

RoomReservationWeb

├── src

│ │

│ └── [Link]

│ │

│ └── [Link]

└── src/main/webapp


└── [Link]

Step 10: Run the Project

1. Start GlassFish, Payara, or WildFly.

2. Deploy RoomReservationEJB and RoomReservationWeb.

3. Open the browser:

[Link]

Output 1

Input

Customer Name : Ali

Room Number : 105

Output

Reservation Successful

Customer Name : Ali

Room Number : 105

Output 2
Input

Customer Name : Sara

Room Number : 120

Output

Room Not Available

Explanation of Important Lines

@Stateless

@Stateless

Declares the class as a Stateless Session Bean.

@EJB

@EJB

RoomReservationBean bean;

Injects the EJB into the Servlet.

Read Customer Name

String name = [Link]("name");

Reads the customer name from the HTML form.


Read Room Number

int roomNo = [Link](

[Link]("roomNo"));

Reads the room number and converts it from String to int.

Call the EJB Method

String result = [Link](name, roomNo);

Calls the business method in the EJB.

Display the Result

[Link]("<h2>" + result + "</h2>");

Displays the reservation status in the browser.

Viva Questions

Q1. What is EJB?


Answer: EJB (Enterprise JavaBeans) is a server-side technology used to
implement business logic in enterprise Java applications.

Q2. What is a Stateless Session Bean?


Answer: A Stateless Session Bean does not store client-specific
information. Every client request is handled independently.
Q3. Why is @EJB used?
Answer: @EJB injects an Enterprise JavaBean into another class,
allowing its business methods to be called directly.

Q4. Can an EJB application run on Tomcat?


Answer: No. Apache Tomcat supports Servlets and JSP only. EJB
applications require an EJB-compatible application server such as
GlassFish, Payara, or WildFly.
c. Develop simple shopping cart application using EJB [Stateful Session
Bean

Aim

Develop a Shopping Cart Application using EJB Stateful Session Bean.

A user can:

 Enter a product name.

 Add the product to the shopping cart.

 View all products added to the cart.

Note: A Stateful Session Bean remembers the cart items for the same
user across multiple requests.

Important: EJB applications cannot run on Apache Tomcat. Use


GlassFish, Payara, or WildFly.

Step 1: Create EJB Project

Open Eclipse

File → New → EJB Project

Project Name

ShoppingCartEJB

Click Finish.

Step 2: Create Stateful Session Bean


Right Click Project

New → Session Bean

Bean Name

ShoppingCartBean

Bean Type

Stateful

Click Finish.

Step 3: [Link]

package [Link];

import [Link];

import [Link];

import [Link];

@Stateful

public class ShoppingCartBean {

private List<String> cart = new ArrayList<>();


public void addItem(String item) {

[Link](item);

public List<String> getItems() {

return cart;

Step 4: Create Dynamic Web Project

File → New → Dynamic Web Project

Project Name

ShoppingCartWeb

Click Finish.
Step 5: Add EJB Project

Right Click

ShoppingCartWeb

Properties

Deployment Assembly

Add

Project

Select

ShoppingCartEJB

Click Finish.

Step 6: Create [Link]

Create [Link] inside

src/main/webapp
<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Shopping Cart</title>

</head>

<body>

<h2>Shopping Cart</h2>

<form action="ShoppingServlet" method="post">

Product Name

<input type="text"

name="product"

required>

<br><br>
<input type="submit"

value="Add To Cart">

</form>

</body>

</html>

Step 7: Create Servlet

Right Click

src/main/java

New → Servlet

Servlet Name

ShoppingServlet

Step 8: [Link]

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/ShoppingServlet")

public class ShoppingServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@EJB

ShoppingCartBean cart;

protected void doPost(HttpServletRequest request,


HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

String product =

[Link]("product");

[Link](product);

List<String> items = [Link]();

[Link]("<html><body>");

[Link]("<h2>Shopping Cart</h2>");

[Link]("<h3>Products in Cart</h3>");
[Link]("<ul>");

for(String item : items) {

[Link]("<li>" + item + "</li>");

[Link]("</ul>");

[Link]("<br><a href='[Link]'>Add More Products</a>");

[Link]("</body></html>");

Project Structure

ShoppingCartEJB

└── src

└── [Link]

└── [Link]

ShoppingCartWeb

├── src

│ │

│ └── [Link]

│ │

│ └── [Link]

└── src/main/webapp

└── [Link]
Run the Project

1. Start GlassFish, Payara, or WildFly.

2. Deploy ShoppingCartEJB and ShoppingCartWeb.

3. Open the browser:

[Link]

Sample Output

First Input

Product Name : Laptop

Output

Shopping Cart

Products in Cart

• Laptop

Second Input

Product Name : Mouse

Output

Shopping Cart
Products in Cart

• Laptop

• Mouse

Third Input

Product Name : Keyboard

Output

Shopping Cart

Products in Cart

• Laptop

• Mouse

• Keyboard

The cart keeps all products because the Stateful Session Bean
remembers the user's cart.

Explanation of Important Code


@Stateful

@Stateful

Marks the bean as a Stateful Session Bean, which stores client-specific


data between requests.

Create Cart

private List<String> cart = new ArrayList<>();

Creates a list to store products.

Add Product

[Link](item);

Adds a product to the shopping cart.

Return Cart

public List<String> getItems()

Returns all products stored in the cart.

Inject EJB

@EJB

ShoppingCartBean cart;
Injects the Stateful Session Bean into the servlet.

Read Product

String product =

[Link]("product");

Reads the product name entered by the user.

Add Product to Cart

[Link](product);

Stores the product in the shopping cart.

Display Cart Items

for(String item : items)

Loops through all products and displays them on the web page.

Viva Questions

Q1. What is a Stateful Session Bean?

Answer:
A Stateful Session Bean maintains client-specific state across multiple
requests. It remembers data for the same user.
Q2. What is the difference between Stateful and Stateless Session
Beans?

Stateful Session Bean Stateless Session Bean

Maintains client state Does not maintain client state

Stores user-specific
Does not store user-specific data
data

Suitable for shopping Suitable for currency conversion, room


carts reservation, etc.

Q3. Why is a Stateful Session Bean used in a Shopping Cart?

Answer:
Because it remembers the products added by a user during the session,
allowing the shopping cart contents to persist across multiple requests.

Q4. Can this application run on Tomcat?

Answer:
No. EJB applications require an EJB-compatible application server such
as GlassFish, Payara, or WildFly. Apache Tomcat supports Servlets and
JSP but not full EJB functionality.
8. Implement the following EJB applications with different types of
Beans

a. Develop simple EJB application to demonstrate Servlet Hit count


using Singleton Session Beans

Aim

Develop a simple EJB application to demonstrate Servlet Hit Count


using a Singleton Session Bean.

Concept
 A Singleton Session Bean has only one instance for the entire
application.

 Every time a user accesses the servlet, the hit count increases.

 Since there is only one bean instance, all users share the same hit
counter.

Note: This application cannot run on Tomcat. Use an EJB-supported


server such as GlassFish, Payara, or WildFly.

Step 1: Create EJB Project

Open Eclipse

File → New → EJB Project

Project Name

HitCounterEJB

Click Finish.

Step 2: Create Singleton Session Bean

Right Click Project

New → Session Bean

Bean Name

HitCounterBean

Bean Type
Singleton

Click Finish.

Step 3: Write [Link]

package [Link];

import [Link];

@Singleton

public class HitCounterBean {

private int hitCount = 0;

public int getHitCount() {

hitCount++;

return hitCount;

}
}

Step 4: Create Dynamic Web Project

File → New → Dynamic Web Project

Project Name

HitCounterWeb

Click Finish.

Step 5: Add EJB Project

Right Click

HitCounterWeb

Properties

Deployment Assembly

Add

Project

Select

HitCounterEJB

Click Finish.

Step 6: Create Servlet

Right Click

src/main/java

New → Servlet

Servlet Name

HitServlet

Step 7: Write [Link]

package [Link];

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/HitServlet")

public class HitServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@EJB

HitCounterBean bean;

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

int count = [Link]();

[Link]("<html><body>");

[Link]("<h2>Servlet Hit Counter</h2>");

[Link]("<h3>Total Hits : " + count + "</h3>");

[Link]("</body></html>");

Project Structure

HitCounterEJB

└── src


└── [Link]

└── [Link]

HitCounterWeb

├── src

│ │

│ └── [Link]

│ │

│ └── [Link]

└── src/main/webapp

Step 8: Run the Project

1. Start GlassFish, Payara, or WildFly.

2. Deploy both HitCounterEJB and HitCounterWeb.

3. Open the browser:

[Link]
Output

First Visit

Servlet Hit Counter

Total Hits : 1

Refresh the Page

Servlet Hit Counter

Total Hits : 2

Refresh Again

Servlet Hit Counter

Total Hits : 3

Every time the servlet is accessed, the hit count increases because the
Singleton Session Bean maintains a single shared counter.

Explanation of Important Code


@Singleton

@Singleton

Creates only one instance of the bean for the entire application.

Hit Counter Variable

private int hitCount = 0;

Stores the total number of servlet hits.

Increment Hit Count

hitCount++;

Increases the counter each time the servlet calls the bean.

Inject the EJB

@EJB

HitCounterBean bean;

Injects the Singleton Session Bean into the servlet.

Call the Bean Method

int count = [Link]();

Gets the updated hit count from the bean.


Viva Questions

Q1. What is a Singleton Session Bean?

Answer:
A Singleton Session Bean has only one instance for the entire
application. All users share the same bean instance.

Q2. Why is a Singleton Bean used for a hit counter?

Answer:
Because all users should share one common hit counter. A Singleton
Bean allows the application to maintain a single global count.

Q3. Which annotation is used to create a Singleton Session Bean?

@Singleton
b. Develop simple visitor Statistics application using Message Driven
Bean [Stateless Session Bean

Aim

Develop a Visitor Statistics Application using Message Driven Bean


(MDB) and a Stateless Session Bean.

Concept

 Every time a visitor accesses the application, a message is sent to


a JMS Queue.

 The Message Driven Bean (MDB) receives the message.

 A Stateless Session Bean processes the visitor information and


updates the visitor count.

Note: MDB applications require an EJB server such as GlassFish, Payara,


or WildFly. They cannot run on Apache Tomcat.
Step 1: Create EJB Project

Open Eclipse

File → New → EJB Project

Project Name

VisitorStatisticsEJB

Click Finish.

Step 2: Create Stateless Session Bean

Right Click Project

New → Session Bean

Bean Name

VisitorBean

Bean Type

Stateless

Click Finish.

Step 3: [Link]

package [Link];

import [Link];
@Stateless

public class VisitorBean {

private static int count = 0;

public int addVisitor() {

count++;

return count;

Step 4: Create Message Driven Bean

Right Click Project

New → Message Driven Bean

Bean Name
VisitorMDB

Click Finish.

Step 5: [Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@MessageDriven(

activationConfig = {

@ActivationConfigProperty(

propertyName = "destinationType",

propertyValue = "[Link]")

})

public class VisitorMDB implements MessageListener {


@EJB

VisitorBean bean;

@Override

public void onMessage(Message message) {

int count = [Link]();

[Link]("Total Visitors : " + count);

Step 6: Create Dynamic Web Project

File → New → Dynamic Web Project

Project Name

VisitorStatisticsWeb

Click Finish.
Step 7: Add EJB Project

Right Click

VisitorStatisticsWeb

Properties

Deployment Assembly

Add → Project

Select

VisitorStatisticsEJB

Finish.

Step 8: Create Servlet

Create a Servlet named

VisitorServlet

Step 9: [Link]

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/VisitorServlet")

public class VisitorServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@EJB

VisitorBean bean;

protected void doGet(HttpServletRequest request,

HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

int count = [Link]();

[Link]("<html><body>");

[Link]("<h2>Visitor Statistics</h2>");

[Link]("<h3>Total Visitors : " + count + "</h3>");

[Link]("</body></html>");

}
Project Structure

VisitorStatisticsEJB

└── src

└── [Link]

├── [Link]

└── [Link]

VisitorStatisticsWeb

├── src

│ │

│ └── [Link]

│ │

│ └── [Link]
Run the Project

1. Start GlassFish, Payara, or WildFly.

2. Deploy VisitorStatisticsEJB and VisitorStatisticsWeb.

3. Open the browser:

[Link]

Output

First Visit

Visitor Statistics

Total Visitors : 1

Refresh

Visitor Statistics

Total Visitors : 2

Refresh Again

Visitor Statistics
Total Visitors : 3

Explanation of Important Code

1. @Stateless

@Stateless

Creates a Stateless Session Bean that contains the business logic for
counting visitors.

2. @MessageDriven

@MessageDriven

Declares the class as a Message Driven Bean (MDB) that listens for
messages sent to a JMS Queue.

3. Inject Session Bean

@EJB

VisitorBean bean;

Injects the VisitorBean into the MDB and Servlet.

4. Increase Visitor Count

count++;
Increments the visitor count whenever a new visitor is processed.

5. Process Message

public void onMessage(Message message)

This method is automatically called whenever the MDB receives a


message from the queue.

Viva Questions

Q1. What is a Message Driven Bean (MDB)?

Answer:
A Message Driven Bean is an EJB component that processes messages
asynchronously from a JMS Queue or Topic.

Q2. What is the purpose of @MessageDriven?

Answer:
It marks a class as a Message Driven Bean that listens for JMS messages.

Q3. What is a Stateless Session Bean?

Answer:
A Stateless Session Bean does not maintain client-specific state. Each
request is handled independently.

Q4. What is JMS?


Answer:
JMS (Java Message Service) is a messaging API that allows applications
to send and receive messages asynchronously.

c. Develop simple Marks Entry Application to demonstrate accessing


Database using EJB

Aim

Develop a Marks Entry Application using EJB (Stateless Session Bean)


that stores student marks in a MySQL database.

Note: This application requires an EJB-supported server (GlassFish,


Payara, or WildFly). It cannot run on Tomcat.

Step 1: Create MySQL Database

Open MySQL Workbench and execute:

CREATE DATABASE college;

USE college;

CREATE TABLE marks(

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(50),

marks INT
);

Step 2: Create EJB Project

Open Eclipse

File → New → EJB Project

Project Name

MarksEntryEJB

Click Finish.

Step 3: Create Stateless Session Bean

Right Click MarksEntryEJB

New → Session Bean

Bean Name

MarksBean

Bean Type

Stateless

Click Finish.

Step 4: Add MySQL JDBC Driver

Download [Link]
Right Click Project

Build Path

→ Configure Build Path

→ Libraries

→ Add External JARs

Select

[Link]

Click Apply and Close.

Step 5: Write [Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@Stateless

public class MarksBean {


public String saveMarks(String name, int marks) {

try {

[Link]("[Link]");

Connection con =

[Link](

"jdbc:mysql://localhost:3306/college",

"root",

"root");

PreparedStatement ps =

[Link](

"insert into marks(name,marks) values(?,?)");

[Link](1, name);

[Link](2, marks);

[Link]();
[Link]();

return "Marks Saved Successfully";

} catch(Exception e) {

return [Link]();

Step 6: Create Dynamic Web Project

File → New → Dynamic Web Project

Project Name

MarksEntryWeb

Click Finish.
Step 7: Add EJB Project

Right Click

MarksEntryWeb

Properties

Deployment Assembly

Add

Project

Select

MarksEntryEJB

Click Finish.

Step 8: Create HTML File

Create [Link] inside

src/main/webapp
<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Marks Entry</title>

</head>

<body>

<h2>Marks Entry Form</h2>

<form action="MarksServlet" method="post">

Student Name

<input type="text"

name="name"

required>

<br><br>
Marks

<input type="number"

name="marks"

required>

<br><br>

<input type="submit"

value="Save">

</form>

</body>

</html>

Step 9: Create Servlet

Right Click

src/main/java


New → Servlet

Servlet Name

MarksServlet

Step 10: Write [Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/MarksServlet")

public class MarksServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

@EJB

MarksBean bean;

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

String name = [Link]("name");

int marks = [Link](

[Link]("marks"));

String result =

[Link](name, marks);
[Link]("<html><body>");

[Link]("<h2>" + result + "</h2>");

[Link]("</body></html>");

Project Structure

MarksEntryEJB

└── src

└── [Link]

└── [Link]

MarksEntryWeb

├── src
│ └── [Link]

│ └── [Link]

└── src/main/webapp

└── [Link]

Step 11: Run the Project

1. Start GlassFish, Payara, or WildFly.

2. Deploy MarksEntryEJB and MarksEntryWeb.

3. Open the browser:

[Link]

Sample Input

Student Name : Ali

Marks : 85

Click Save.

Output

Marks Saved Successfully


Database Output

After executing:

SELECT * FROM marks;

Example result:

id name marks

1 Ali 85

2 Sara 92

Explanation of Important Code

@Stateless

@Stateless

Creates a Stateless Session Bean to contain the business logic.

Load JDBC Driver

[Link]("[Link]");

Loads the MySQL JDBC driver.

Database Connection

Connection con =

[Link](
"jdbc:mysql://localhost:3306/college",

"root",

"root");

Connects the application to the MySQL database.

PreparedStatement

PreparedStatement ps =

[Link](

"insert into marks(name,marks) values(?,?)");

Creates an SQL statement with placeholders.

Set Values

[Link](1, name);

[Link](2, marks);

Assigns the form values to the SQL query.

Execute Query

[Link]();

Inserts the record into the database.


Inject EJB

@EJB

MarksBean bean;

Injects the MarksBean into the servlet so that its saveMarks() method
can be called.

Viva Questions

Q1. What is EJB?

Answer:
EJB (Enterprise JavaBeans) is a server-side technology used to
implement business logic in enterprise Java applications.

Q2. Why is @Stateless used?

Answer:
It creates a Stateless Session Bean, which does not maintain client-
specific state between requests.

Q3. Why is PreparedStatement preferred?

Answer:
It improves performance and helps prevent SQL injection attacks.

Q4. What is the purpose of executeUpdate()?

Answer:
It executes SQL statements such as INSERT, UPDATE, and DELETE,
returning the number of affected rows.
9. Implement the following JPA applications

a. Develop a simple Inventory Application Using JPA


Aim

Develop a Simple Inventory Application using JPA (Java Persistence


API) to store product details in a MySQL database.

The application will:

 Accept Product ID

 Accept Product Name

 Accept Quantity

 Accept Price

 Store the details in the database using JPA.

Step 1: Create MySQL Database

Open MySQL Workbench and execute:

CREATE DATABASE inventorydb;


USE inventorydb;

CREATE TABLE product(

id INT PRIMARY KEY,

name VARCHAR(50),

quantity INT,

price DOUBLE

);

Step 2: Create JPA Project

Open Eclipse

File → New → JPA Project

Project Name

InventoryJPA

Click Next.

Choose your Target Runtime (GlassFish/Payara/WildFly).

Click Finish.

Step 3: Add MySQL JDBC Driver


Download [Link]

Right Click Project

Build Path

→ Configure Build Path

→ Libraries

→ Add External JARs

Select

[Link]

Click Apply and Close.

Step 4: Create Entity Class

Create package

[Link]

Create class

[Link]

package [Link];

import [Link];

import [Link];

import [Link];
@Entity

@Table(name="product")

public class Product {

@Id

private int id;

private String name;

private int quantity;

private double price;

public Product() {

public int getId() {

return id;

}
public void setId(int id) {

[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public int getQuantity() {

return quantity;

public void setQuantity(int quantity) {

[Link] = quantity;

}
public double getPrice() {

return price;

public void setPrice(double price) {

[Link] = price;

Step 5: Configure [Link]

Create

META-INF → [Link]

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

<persistence version="3.0"

xmlns="[Link]

<persistence-unit name="InventoryPU">
<class>[Link]</class>

<properties>

<property name="[Link]"

value="[Link]"/>

<property name="[Link]"

value="jdbc:mysql://localhost:3306/inventorydb"/>

<property name="[Link]"

value="root"/>

<property name="[Link]"

value="root"/>

<property name="[Link]"

value="[Link].MySQL8Dialect"/>

</properties>
</persistence-unit>

</persistence>

Step 6: Create Main Class

Create

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

public class InventoryApp {

public static void main(String[] args) {

EntityManagerFactory emf =

[Link]("InventoryPU");
EntityManager em = [Link]();

Product p = new Product();

[Link](101);

[Link]("Laptop");

[Link](10);

[Link](55000);

[Link]().begin();

[Link](p);

[Link]().commit();

[Link]("Product Saved Successfully");

[Link]();
[Link]();

Project Structure

InventoryJPA

├── src

│ └── [Link]

│ ├── [Link]

│ └── [Link]

└── META-INF

└── [Link]

Run the Project

1. Right Click [Link]

2. Run As → Java Applica on

3. Console Output:
Product Saved Successfully

Database Output

Run the following query in MySQL:

SELECT * FROM product;

Example Output

id name quantity price

101 Laptop 10 55000

Explanation of Important Code

@Entity

@Entity

Marks the class as a JPA Entity that maps to a database table.

@Table

@Table(name="product")

Maps the entity class to the product table.

@Id

@Id
Specifies the primary key of the entity.

Create EntityManagerFactory

EntityManagerFactory emf =

[Link]("InventoryPU");

Creates a factory for obtaining EntityManager objects.

Create EntityManager

EntityManager em = [Link]();

Used to perform database operations.

Begin Transaction

[Link]().begin();

Starts the database transaction.

Persist Entity

[Link](p);

Inserts the product object into the database.

Commit Transaction
[Link]().commit();

Saves the changes permanently.

Viva Questions

Q1. What is JPA?


Answer: JPA (Java Persistence API) is a Java specification used to map
Java objects to database tables (ORM).

Q2. What is an Entity?


Answer: An Entity is a Java class that represents a database table.

Q3. What is the purpose of @Entity?


Answer: It tells JPA that the class should be mapped to a database
table.

Q4. What is EntityManager?


Answer: EntityManager is used to perform CRUD (Create, Read, Update,
Delete) operations on entities.

Q5. What is [Link]?


Answer: It is the JPA configuration file that contains the database
connection details and persistence unit configuration.
b. Develop a Guestbook Application Using JPA

Aim

Develop a Guestbook Application using JPA (Java Persistence API) to


store visitor details in a MySQL database.

The application will:

 Accept Guest Name

 Accept Message

 Store the details in the database using JPA.

Step 1: Create MySQL Database


Open MySQL Workbench and execute the following SQL:

CREATE DATABASE guestbookdb;

USE guestbookdb;

CREATE TABLE guest(

id INT PRIMARY KEY,

name VARCHAR(50),

message VARCHAR(200)

);

Step 2: Create JPA Project

Open Eclipse

File → New → JPA Project

Project Name

GuestbookJPA

Click Next → Select GlassFish/Payara/WildFly as Target Runtime →


Finish.

Step 3: Add MySQL JDBC Driver


Download [Link]

Right Click Project

Build Path

→ Configure Build Path

→ Libraries

→ Add External JARs

Select [Link].

Click Apply and Close.

Step 4: Create Entity Class

Create package

[Link]

Create class

[Link]

[Link]

package [Link];

import [Link];

import [Link];

import [Link];
@Entity

@Table(name="guest")

public class Guest {

@Id

private int id;

private String name;

private String message;

public Guest() {

public int getId() {

return id;

public void setId(int id) {


[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public String getMessage() {

return message;

public void setMessage(String message) {

[Link] = message;

}
Step 5: Configure [Link]

Create

META-INF

└── [Link]

[Link]

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

<persistence version="3.0"

xmlns="[Link]

<persistence-unit name="GuestbookPU">

<class>[Link]</class>

<properties>

<property name="[Link]"

value="[Link]"/>

<property name="[Link]"
value="jdbc:mysql://localhost:3306/guestbookdb"/>

<property name="[Link]"

value="root"/>

<property name="[Link]"

value="root"/>

<property name="[Link]"

value="[Link].MySQL8Dialect"/>

</properties>

</persistence-unit>

</persistence>

Step 6: Create Main Class

Create class

[Link]
[Link]

package [Link];

import [Link];

import [Link];

import [Link];

public class GuestbookApp {

public static void main(String[] args) {

EntityManagerFactory emf =

[Link]("GuestbookPU");

EntityManager em = [Link]();

Guest guest = new Guest();

[Link](1);

[Link]("Ali");
[Link]("Welcome to our Guestbook!");

[Link]().begin();

[Link](guest);

[Link]().commit();

[Link]("Guest Entry Saved Successfully");

[Link]();

[Link]();

Project Structure

GuestbookJPA

├── src

│ └── [Link]
│ ├── [Link]

│ └── [Link]

└── META-INF

└── [Link]

Run the Project

1. Right Click [Link]

2. Run As → Java Applica on

Console Output

Guest Entry Saved Successfully

Database Output

Run the following SQL query:

SELECT * FROM guest;

Example Output:

id name message

1 Ali Welcome to our Guestbook!


Explanation of Important Code

@Entity

@Entity

Marks the Guest class as a JPA entity.

@Table

@Table(name="guest")

Maps the entity to the guest table.

@Id

@Id

Specifies the primary key.

Create EntityManagerFactory

EntityManagerFactory emf =

[Link]("GuestbookPU");

Creates the JPA persistence context.

Create EntityManager

EntityManager em = [Link]();
Used to perform database operations.

Begin Transaction

[Link]().begin();

Starts a database transaction.

Save Entity

[Link](guest);

Stores the guest object in the database.

Commit Transaction

[Link]().commit();

Saves the data permanently.

Viva Questions

Q1. What is JPA?

Answer: JPA (Java Persistence API) is a Java specification used to map


Java objects to database tables using Object Relational Mapping (ORM).

Q2. What is an Entity?

Answer: An Entity is a Java class that represents a database table.


Q3. What is the purpose of @Entity?

Answer: It tells JPA that the class should be treated as a database entity.

Q4. What is EntityManager?

Answer: EntityManager is used to perform CRUD (Create, Read, Update,


Delete) operations on entities.

Q5. What is persist()?

Answer: The persist() method inserts a new entity object into the

c. Create simple JPA application to store and retrieve Book details


Develop a Simple JPA Application to store and retrieve book details
from a MySQL database.

The application will:

 Store Book ID

 Store Book Name

 Store Author Name

 Store Book Price

 Retrieve and display the stored book details.

Step 1: Create MySQL Database

Open MySQL Workbench and execute:

CREATE DATABASE librarydb;

USE librarydb;

CREATE TABLE book(

id INT PRIMARY KEY,

name VARCHAR(100),

author VARCHAR(100),

price DOUBLE
);

Step 2: Create JPA Project

Open Eclipse

File → New → JPA Project

Project Name

BookJPA

Click Next

Select Target Runtime

GlassFish / Payara / WildFly

Click Finish.

Step 3: Add MySQL JDBC Driver

Download [Link]

Right Click Project

Build Path

→ Configure Build Path

→ Libraries

→ Add External JARs

Select
[Link]

Click Apply and Close.

Step 4: Create Entity Class

Create Package

[Link]

Create Class

[Link]

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

@Entity

@Table(name="book")

public class Book {

@Id
private int id;

private String name;

private String author;

private double price;

public Book() {

public int getId() {

return id;

public void setId(int id) {

[Link] = id;

public String getName() {


return name;

public void setName(String name) {

[Link] = name;

public String getAuthor() {

return author;

public void setAuthor(String author) {

[Link] = author;

public double getPrice() {

return price;

public void setPrice(double price) {


[Link] = price;

Step 5: Configure [Link]

Create

META-INF

└── [Link]

[Link]

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

<persistence version="3.0"

xmlns="[Link]

<persistence-unit name="BookPU">

<class>[Link]</class>

<properties>
<property name="[Link]"

value="[Link]"/>

<property name="[Link]"

value="jdbc:mysql://localhost:3306/librarydb"/>

<property name="[Link]"

value="root"/>

<property name="[Link]"

value="root"/>

<property name="[Link]"

value="[Link].MySQL8Dialect"/>

</properties>

</persistence-unit>
</persistence>

Step 6: Create Main Class

Create class

[Link]

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

public class BookApp {

public static void main(String[] args) {

EntityManagerFactory emf =

[Link]("BookPU");

EntityManager em = [Link]();
// Store Book

Book b = new Book();

[Link](101);

[Link]("Java Programming");

[Link]("James Gosling");

[Link](550.00);

[Link]().begin();

[Link](b);

[Link]().commit();

[Link]("Book Saved Successfully");

// Retrieve Book
Book book = [Link]([Link], 101);

[Link]("Book Details");

[Link]("ID : " + [Link]());

[Link]("Name : " + [Link]());

[Link]("Author : " + [Link]());

[Link]("Price : " + [Link]());

[Link]();

[Link]();

}
Project Structure

BookJPA

├── src

│ │

│ └── [Link]

│ │

│ ├── [Link]

│ └── [Link]

└── META-INF

└── [Link]

Run the Project

1. Right Click [Link]

2. Select

Run As → Java Applica on

Console Output
Book Saved Successfully

Book Details

ID : 101

Name : Java Programming

Author : James Gosling

Price : 550.0

Database Output

Execute:

SELECT * FROM book;

Output

id name author price

101 Java Programming James Gosling 550.00

Explanation of Important Code


1. @Entity

@Entity

Marks the Book class as a JPA entity.

2. @Table

@Table(name="book")

Maps the entity to the book table.

3. @Id

@Id

Specifies the primary key of the entity.

4. Create EntityManagerFactory

EntityManagerFactory emf =

[Link]("BookPU");

Creates the persistence unit.

5. Create EntityManager

EntityManager em = [Link]();

Used to interact with the database.


6. Save Data

[Link](b);

Stores the book object in the database.

7. Retrieve Data

Book book = [Link]([Link], 101);

Retrieves the book whose primary key (id) is 101.

8. Commit Transaction

[Link]().commit();

Permanently saves the data.

Viva Questions

Q1. What is JPA?

Answer:
JPA (Java Persistence API) is a Java specification used for Object
Relational Mapping (ORM), allowing Java objects to be stored and
retrieved from a database.

Q2. What is an Entity?


Answer:
An Entity is a Java class that represents a table in the database.

Q3. What is the purpose of @Id?

Answer:
@Id identifies the primary key field of the entity.

Q4. What is the purpose of persist()?

Answer:
persist() stores a new entity object in the database.

Q5. What is the purpose of find()?

Answer:
find() retrieves an entity from the database using its primary key.
10. Implement the following JPA applications with ORM and Hibernate

To develop a JPA Application to demonstrate the use of ORM


Associations, you need the following software, libraries, database, and
project files.

Requirements List

1. Software Required

 Eclipse IDE (Enterprise Edition)

 JDK 17 or later

 MySQL Server

 MySQL Workbench

 GlassFish / Payara / WildFly (if using Jakarta EE Server)

2. Database

Create a MySQL database.

Example:

CREATE DATABASE ormdb;

3. JDBC Driver

Download and add

[Link]
to the project.

4. JPA Provider

You need a JPA implementation such as:

 Hibernate ORM (Most Common)

 EclipseLink

5. Required Libraries (JAR Files)

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

(If you are using Maven, these libraries are downloaded automatically.)

Project Structure

ORMAssociationProject

├── src
│ │

│ └── [Link]

│ │

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

├── META-INF

│ │

│ └── [Link]

└── Referenced Libraries

├── [Link]

├── [Link]

└── [Link]

Required Java Classes

Usually, this project contains:

1. Entity Class 1
[Link]

2. Entity Class 2

[Link]

3. Main Class

[Link]

4. Configuration File

[Link]

Database Tables

Depending on the association type, you need different tables.

Example (One-to-Many)

Student

id name

1 Ali

Course

id courseName student_id

101 Java 1

102 Python 1
JPA Annotations Required

For ORM Associations, you may use:

One-to-One

@OneToOne

One-to-Many

@OneToMany

Many-to-One

@ManyToOne

Many-to-Many

@ManyToMany

Primary Key

@Id

Entity

@Entity
Table

@Table

Join Column

@JoinColumn

Join Table (for Many-to-Many)

@JoinTable

Configuration File

You need

META-INF/[Link]

This file contains:

 Database URL

 Username

 Password

 JDBC Driver

 Hibernate Dialect

 Persistence Unit Name


Common ORM Association Types

 One-to-One

 One-to-Many

 Many-to-One

 Many-to-Many

Steps to Build the Project

1. Install JDK.

2. Install Eclipse IDE.

3. Install MySQL Server and MySQL Workbench.

4. Create the database (ormdb).

5. Create a JPA Project in Eclipse.

6. Add the MySQL JDBC driver.

7. Configure [Link].

8. Create the Entity classes (e.g., Student and Course).

9. Add the required JPA association annotations (@OneToMany,


@ManyToOne, etc.).

10. Create the [Link] class to save and retrieve data.

11. Run the application and verify the data in MySQL.


b. Develop a Hibernate application to store Feedback of Website Visitor
in MySQL Database

Aim

Develop a Hibernate Application to store Website Visitor Feedback in a


MySQL Database.

The application will:

 Accept Visitor ID

 Accept Visitor Name

 Accept Email
 Accept Feedback

 Store the details in MySQL using Hibernate ORM.

Software Required

 Eclipse IDE

 JDK 17 or above

 MySQL Server

 MySQL Workbench

 Hibernate ORM

 MySQL Connector/J

Required JAR Files

Add these JAR files to your project:

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

(If using Maven, these dependencies are downloaded automatically.)


Step 1: Create MySQL Database

Open MySQL Workbench and execute:

CREATE DATABASE feedbackdb;

USE feedbackdb;

CREATE TABLE feedback(

id INT PRIMARY KEY,

name VARCHAR(50),

email VARCHAR(100),

message VARCHAR(250)

);

Step 2: Create Java Project

Open Eclipse

File → New → Java Project

Project Name

FeedbackHibernate

Click Finish.
Step 3: Add Hibernate and MySQL JAR Files

Right Click Project

Build Path

→ Configure Build Path

→ Libraries

→ Add External JARs

Add all Hibernate and MySQL JAR files.

Step 4: Create Package

[Link]

Step 5: Create Entity Class

Create

[Link]

package [Link];

public class Feedback {

private int id;


private String name;

private String email;

private String message;

public Feedback() {

public int getId() {

return id;

public void setId(int id) {

[Link] = id;

public String getName() {

return name;

public void setName(String name) {


[Link] = name;

public String getEmail() {

return email;

public void setEmail(String email) {

[Link] = email;

public String getMessage() {

return message;

public void setMessage(String message) {

[Link] = message;

}
Step 6: Create Hibernate Configuration File

Create

[Link]

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

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"[Link]

<hibernate-configuration>

<session-factory>

<property name="[Link].driver_class">

[Link]

</property>

<property name="[Link]">

jdbc:mysql://localhost:3306/feedbackdb

</property>
<property name="[Link]">

root

</property>

<property name="[Link]">

root

</property>

<property name="[Link]">

[Link].MySQL8Dialect

</property>

<property name="[Link]">

update

</property>

<property name="show_sql">

true

</property>
<mapping resource="[Link]"/>

</session-factory>

</hibernate-configuration>

Step 7: Create Mapping File

Create

[Link]

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"[Link]

<hibernate-mapping>

<class name="[Link]"

table="feedback">
<id name="id">

<generator class="assigned"/>

</id>

<property name="name"/>

<property name="email"/>

<property name="message"/>

</class>

</hibernate-mapping>

Step 8: Create Main Class

Create

[Link]

package [Link];
import [Link];

import [Link];

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

Configuration cfg = new Configuration();

[Link]("[Link]");

SessionFactory factory =

[Link]();

Session session =

[Link]();

Transaction tx =
[Link]();

Feedback f = new Feedback();

[Link](1);

[Link]("Ali");

[Link]("ali@[Link]");

[Link]("Website is Excellent");

[Link](f);

[Link]();

[Link]();

[Link]();

[Link]("Feedback Saved Successfully");

}
Project Structure

FeedbackHibernate

├── src

│ │

│ └── [Link]

│ │

│ ├── [Link]

│ └── [Link]

├── [Link]

├── [Link]

└── Referenced Libraries

Run the Project

1. Right Click [Link]

2. Select
Run As → Java Applica on

Console Output

Hibernate: insert into feedback values(?,?,?,?)

Feedback Saved Successfully

Database Output

Execute:

SELECT * FROM feedback;

Example Output

id name email message

1 Ali ali@[Link] Website is Excellent

Explanation of Important Code

Create Configuration

Configuration cfg = new Configuration();

Creates the Hibernate configuration object.

Load Configuration File


[Link]("[Link]");

Loads the Hibernate configuration settings.

Build SessionFactory

SessionFactory factory =

[Link]();

Creates the SessionFactory, which is used to create database sessions.

Open Session

Session session =

[Link]();

Opens a session for database operations.

Begin Transaction

Transaction tx =

[Link]();

Starts a database transaction.

Save Object

[Link](f);
Stores the Feedback object in the database.

Commit Transaction

[Link]();

Permanently saves the data.

Viva Questions

Q1. What is Hibernate?

Answer: Hibernate is an Object Relational Mapping (ORM) framework


that maps Java objects to database tables.

Q2. What is ORM?

Answer: ORM (Object Relational Mapping) is a technique that maps


Java classes to database tables and Java objects to table records.

Q3. What is SessionFactory?

Answer: SessionFactory is a Hibernate object used to create Session


objects for interacting with the database.

Q4. What is a Session in Hibernate?

Answer: A Session is the main interface used to perform CRUD (Create,


Read, Update, Delete) operations on the database.

Q5. Why is Transaction used?


Answer: A Transaction ensures that database operations are completed
successfully as a single unit of work. It allows changes to be committed
or rolled back if an error occurs.

c. Develop a Hibernate application to store and retrieve employee


details in MySQL Database

Aim

Develop a Hibernate Application to store and retrieve employee details


from a MySQL Database.

The application will:

 Store Employee ID

 Store Employee Name

 Store Department

 Store Salary

 Retrieve and display employee details.

Software Required

 Eclipse IDE

 JDK 17 or above
 MySQL Server

 MySQL Workbench

 Hibernate ORM

 MySQL Connector/J

Required JAR Files

Add the following JAR files:

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

Step 1: Create MySQL Database

Open MySQL Workbench and execute:

CREATE DATABASE employeedb;

USE employeedb;
CREATE TABLE employee(

id INT PRIMARY KEY,

name VARCHAR(50),

department VARCHAR(50),

salary DOUBLE

);

Step 2: Create Java Project

Open Eclipse

File → New → Java Project

Project Name

EmployeeHibernate

Click Finish.

Step 3: Add Hibernate JAR Files

Right Click Project

Build Path

→ Configure Build Path

→ Libraries

→ Add External JARs


Add:

 Hibernate JAR files

 MySQL Connector JAR

Click Apply and Close.

Step 4: Create Package

[Link]

Step 5: Create Employee Class

Create

[Link]

package [Link];

public class Employee {

private int id;

private String name;

private String department;

private double salary;


public Employee() {

public int getId() {

return id;

public void setId(int id) {

[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public String getDepartment() {


return department;

public void setDepartment(String department) {

[Link] = department;

public double getSalary() {

return salary;

public void setSalary(double salary) {

[Link] = salary;

Step 6: Create Hibernate Configuration File

Create

[Link]

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


<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"[Link]

<hibernate-configuration>

<session-factory>

<property name="[Link].driver_class">

[Link]

</property>

<property name="[Link]">

jdbc:mysql://localhost:3306/employeedb

</property>

<property name="[Link]">

root

</property>
<property name="[Link]">

root

</property>

<property name="[Link]">

[Link].MySQL8Dialect

</property>

<property name="[Link]">

update

</property>

<property name="show_sql">

true

</property>

<mapping resource="[Link]"/>

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

Step 7: Create Mapping File

Create

[Link]

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"[Link]

<hibernate-mapping>

<class name="[Link]"

table="employee">

<id name="id">

<generator class="assigned"/>

</id>
<property name="name"/>

<property name="department"/>

<property name="salary"/>

</class>

</hibernate-mapping>

Step 8: Create Main Class

Create

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];
public class EmployeeApp {

public static void main(String[] args) {

Configuration cfg = new Configuration();

[Link]("[Link]");

SessionFactory factory =

[Link]();

Session session =

[Link]();

// Store Employee

Transaction tx =

[Link]();
Employee emp = new Employee();

[Link](101);

[Link]("Rahul");

[Link]("IT");

[Link](50000);

[Link](emp);

[Link]();

[Link]("Employee Saved Successfully");

// Retrieve Employee

Employee e = [Link]([Link], 101);

[Link]("\nEmployee Details");

[Link]("ID : " + [Link]());


[Link]("Name : " + [Link]());

[Link]("Department : " + [Link]());

[Link]("Salary : " + [Link]());

[Link]();

[Link]();

Project Structure

EmployeeHibernate

├── src

│ │

│ └── [Link]

│ │

│ ├── [Link]

│ └── [Link]


├── [Link]

├── [Link]

└── Referenced Libraries

Run the Project

1. Right Click [Link]

2. Select

Run As → Java Applica on

Console Output

Hibernate: insert into employee values(?,?,?,?)

Employee Saved Successfully

Employee Details

ID : 101

Name : Rahul
Department : IT

Salary : 50000.0

Database Output

Execute:

SELECT * FROM employee;

Example Output

id name department salary

101 Rahul IT 50000.0

Explanation of Important Code

Create Configuration

Configuration cfg = new Configuration();

Creates the Hibernate configuration object.

Load Configuration File

[Link]("[Link]");

Loads database and Hibernate settings.

Build SessionFactory
SessionFactory factory =

[Link]();

Creates a SessionFactory, which is used to open Hibernate sessions.

Open Session

Session session =

[Link]();

Opens a session for database operations.

Begin Transaction

Transaction tx =

[Link]();

Starts a transaction before saving data.

Save Employee

[Link](emp);

Stores the employee object in the database.

Retrieve Employee

Employee e =
[Link]([Link], 101);

Retrieves the employee whose ID is 101.

Commit Transaction

[Link]();

Permanently saves the changes in the database.

Viva Questions

Q1. What is Hibernate?

Answer:
Hibernate is an ORM (Object Relational Mapping) framework that maps
Java objects to database tables.

Q2. What is ORM?

Answer:
ORM (Object Relational Mapping) is a technique that maps Java classes
to database tables and Java objects to database records.

Q3. What is the purpose of SessionFactory?

Answer:
SessionFactory creates Session objects that interact with the database.

Q4. What is the purpose of [Link]()?

Answer:
[Link]() inserts a Java object as a new record into the database.
Q5. What is the purpose of [Link]()?

Answer:
[Link]() retrieves a record from the database using its primary key
and returns it as a Java object.

11. Implement the following Hibernate

a. Develop an application to demonstrate Hibernate One- To -One


Mapping Using Annotation

Aim
Develop a Hibernate Application to demonstrate One-to-One Mapping
using Annotations.

Example:

 One Employee has one Address.

 One Address belongs to one Employee.

Software Required

 Eclipse IDE

 JDK 17 or above

 MySQL Server

 MySQL Workbench

 Hibernate ORM

 MySQL Connector/J

Required JAR Files

Add the following JAR files:

 [Link]

 [Link]

 [Link]

 [Link]
 [Link]

 [Link]

Step 1: Create Database

Open MySQL Workbench and execute:

CREATE DATABASE hibernatedb;

USE hibernatedb;

Note: Since [Link]=update is used, Hibernate will


automatically create the required tables.

Step 2: Create Java Project

File → New → Java Project

Project Name

HibernateOneToOne

Click Finish.

Step 3: Add Hibernate JAR Files

Right Click Project

Build Path
→ Configure Build Path

→ Libraries

→ Add External JARs

Add all Hibernate and MySQL Connector JAR files.

Step 4: Create Package

[Link]

Step 5: Create [Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@Entity

public class Employee {


@Id

private int id;

private String name;

@OneToOne(cascade = [Link])

@JoinColumn(name="address_id")

private Address address;

public Employee() {

public int getId() {

return id;

public void setId(int id) {

[Link]=id;
}

public String getName() {

return name;

public void setName(String name) {

[Link]=name;

public Address getAddress() {

return address;

public void setAddress(Address address) {

[Link]=address;

}
Step 6: Create [Link]

package [Link];

import [Link];

import [Link];

@Entity

public class Address {

@Id

private int id;

private String city;

private String state;

public Address() {

public int getId() {


return id;

public void setId(int id) {

[Link]=id;

public String getCity() {

return city;

public void setCity(String city) {

[Link]=city;

public String getState() {

return state;

public void setState(String state) {


[Link]=state;

Step 7: Create [Link]

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

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"[Link]

<hibernate-configuration>

<session-factory>

<property name="[Link].driver_class">

[Link]

</property>
<property name="[Link]">

jdbc:mysql://localhost:3306/hibernatedb

</property>

<property name="[Link]">

root

</property>

<property name="[Link]">

root

</property>

<property name="[Link]">

[Link].MySQL8Dialect

</property>

<property name="[Link]">

update

</property>
<property name="show_sql">

true

</property>

<mapping class="[Link]"/>

<mapping class="[Link]"/>

</session-factory>

</hibernate-configuration>

Step 8: Create Main Class

Create

[Link]

package [Link];

import [Link];

import [Link];

import [Link];
import [Link];

public class MainApp {

public static void main(String[] args) {

Configuration cfg =

new Configuration().configure();

SessionFactory factory =

[Link]();

Session session =

[Link]();

Transaction tx =

[Link]();

Address address =

new Address();
[Link](1);

[Link]("Mumbai");

[Link]("Maharashtra");

Employee emp =

new Employee();

[Link](101);

[Link]("Rahul");

[Link](address);

[Link](emp);

[Link]();

[Link]();

[Link]();
[Link]("Employee and Address Saved Successfully");

Project Structure

HibernateOneToOne

├── src

│ │

│ └── [Link]

│ │

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

├── [Link]

└── Referenced Libraries


Run the Project

1. Right Click [Link]

2. Select

Run As → Java Applica on

Console Output

Hibernate:

insert into Address values(?,?,?)

Hibernate:

insert into Employee values(?,?,?)

Employee and Address Saved Successfully

Database Tables

Employee Table

id name address_id

101 Rahul 1

Address Table
id city state

1 Mumbai Maharashtra

Explanation of Important Annotations

@Entity

@Entity

Marks the class as a Hibernate entity.

@Id

@Id

Defines the primary key.

@OneToOne

@OneToOne

Creates a one-to-one relationship between Employee and Address.

@JoinColumn

@JoinColumn(name="address_id")

Creates the foreign key column address_id in the Employee table.


[Link]

cascade = [Link]

When an Employee is saved, the associated Address is also saved


automatically.

Viva Questions

Q1. What is One-to-One Mapping?

Answer:
One-to-One Mapping means one record in one table is associated with
exactly one record in another table.

Q2. Which annotation is used for One-to-One Mapping?

Answer:

@OneToOne

Q3. What is the purpose of @JoinColumn?

Answer:
It creates a foreign key column that links two tables.

Q4. What is [Link]?


Answer:
It performs all operations (save, update, delete, etc.) on the associated
object automatically.

Q5. Why is @Entity used?

Answer:
It tells Hibernate that the Java class should be mapped to a database
table.

b. Develop Hibernate application to enter and retrieve course details


with ORM Mapping

Aim

Develop a Hibernate Application to store and retrieve course details


from a MySQL Database using ORM Mapping.

The application will:

 Store Course ID

 Store Course Name

 Store Duration

 Store Fees
 Retrieve and display the course details.

Software Required

 Eclipse IDE

 JDK 17 or above

 MySQL Server

 MySQL Workbench

 Hibernate ORM

 MySQL Connector/J

Required JAR Files

Add the following JAR files:

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

 [Link]

Step 1: Create MySQL Database


Open MySQL Workbench and execute:

CREATE DATABASE coursedb;

USE coursedb;

CREATE TABLE course(

id INT PRIMARY KEY,

name VARCHAR(50),

duration VARCHAR(30),

fees DOUBLE

);

Step 2: Create Java Project

Open Eclipse

File → New → Java Project

Project Name

CourseHibernate

Click Finish.

Step 3: Add Hibernate JAR Files


Right Click Project

Build Path

→ Configure Build Path

→ Libraries

→ Add External JARs

Add:

 Hibernate JAR files

 MySQL Connector JAR

Click Apply and Close.

Step 4: Create Package

[Link]

Step 5: Create [Link]

package [Link];

public class Course {

private int id;

private String name;


private String duration;

private double fees;

public Course() {

public int getId() {

return id;

public void setId(int id) {

[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;
}

public String getDuration() {

return duration;

public void setDuration(String duration) {

[Link] = duration;

public double getFees() {

return fees;

public void setFees(double fees) {

[Link] = fees;

Step 6: Create Mapping File


Create [Link]

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"[Link]

<hibernate-mapping>

<class name="[Link]"

table="course">

<id name="id">

<generator class="assigned"/>

</id>

<property name="name"/>

<property name="duration"/>
<property name="fees"/>

</class>

</hibernate-mapping>

Step 7: Create [Link]

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

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"[Link]

<hibernate-configuration>

<session-factory>

<property name="[Link].driver_class">

[Link]

</property>
<property name="[Link]">

jdbc:mysql://localhost:3306/coursedb

</property>

<property name="[Link]">

root

</property>

<property name="[Link]">

root

</property>

<property name="[Link]">

[Link].MySQL8Dialect

</property>

<property name="[Link]">

update

</property>
<property name="show_sql">

true

</property>

<mapping resource="[Link]"/>

</session-factory>

</hibernate-configuration>

Step 8: Create Main Class

Create [Link]

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];
public class CourseApp {

public static void main(String[] args) {

Configuration cfg = new Configuration();

[Link]("[Link]");

SessionFactory factory =

[Link]();

Session session =

[Link]();

// Store Course

Transaction tx =

[Link]();

Course c = new Course();


[Link](101);

[Link]("Java Programming");

[Link]("3 Months");

[Link](15000);

[Link](c);

[Link]();

[Link]("Course Saved Successfully");

// Retrieve Course

Course course =

[Link]([Link], 101);

[Link]("\nCourse Details");

[Link]("Course ID : " + [Link]());


[Link]("Course Name : " + [Link]());

[Link]("Duration : " + [Link]());

[Link]("Fees : " + [Link]());

[Link]();

[Link]();

Project Structure

CourseHibernate

├── src

│ │

│ └── [Link]

│ │

│ ├── [Link]

│ └── [Link]


├── [Link]

├── [Link]

└── Referenced Libraries

Run the Project

1. Right Click [Link]

2. Select

Run As → Java Applica on

Console Output

Hibernate: insert into course values(?,?,?,?)

Course Saved Successfully

Course Details

Course ID : 101

Course Name : Java Programming


Duration : 3 Months

Fees : 15000.0

Database Output

Execute:

SELECT * FROM course;

Output:

id name duration fees

101 Java Programming 3 Months 15000.0

Explanation of Important Code

1. Create Configuration

Configuration cfg = new Configuration();

Creates the Hibernate configuration object.

2. Load Configuration File

[Link]("[Link]");

Loads the Hibernate configuration settings.

3. Build SessionFactory
SessionFactory factory =

[Link]();

Creates a SessionFactory object to manage Hibernate sessions.

4. Open Session

Session session =

[Link]();

Opens a session to interact with the database.

5. Begin Transaction

Transaction tx =

[Link]();

Starts a transaction before performing database operations.

6. Save Course

[Link](c);

Stores the Course object in the database.

7. Retrieve Course

Course course =
[Link]([Link], 101);

Retrieves the course record with ID 101 from the database.

8. Commit Transaction

[Link]();

Commits the transaction and permanently saves the data.

Viva Questions

Q1. What is Hibernate?

Answer: Hibernate is an ORM (Object Relational Mapping) framework


that maps Java objects to database tables.

Q2. What is ORM Mapping?

Answer: ORM (Object Relational Mapping) maps Java classes and


objects to relational database tables and records.

Q3. What is the purpose of [Link]?

Answer: It contains Hibernate configuration details such as database


URL, username, password, dialect, and mapping files.

Q4. What is the purpose of [Link]()?

Answer: It inserts a Java object into the database as a new record.

Q5. What is the purpose of [Link]()?

Answer: It retrieves an object from the database using its primary key.
c. Develop a five page web application site using any two or three Java
EE Technologies

Aim

Develop a Five-Page Web Application using Java EE Technologies.

Technologies Used

 HTML
 CSS

 Servlet

 JDBC

 MySQL

This project uses three Java EE technologies:

1. Servlet

2. JDBC

3. MySQL Database

Software Required

 Eclipse IDE (Enterprise Edition)

 JDK 17 or above

 Apache Tomcat 10/11

 MySQL Server

 MySQL Workbench

 MySQL Connector/J

Project Name

StudentPortal
Project Pages

Page File Name Purpose

1 [Link] Home Page

2 [Link] Registration Form

3 [Link] Login Form

4 WelcomeServlet Welcome Page

5 [Link] About Page

Project Structure

StudentPortal

├── src

│ └── [Link]

│ ├── [Link]

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

├── WebContent
│ ├── [Link]

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

└── [Link]

Database

Create Database

CREATE DATABASE studentdb;

USE studentdb;

CREATE TABLE users(

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50),

password VARCHAR(50),

email VARCHAR(50)

);
Page 1 : [Link]

<!DOCTYPE html>

<html>

<head>

<title>Home</title>

</head>

<body>

<h1>Student Portal</h1>

<a href="[Link]">Register</a>

<br><br>

<a href="[Link]">Login</a>

<br><br>

<a href="[Link]">About</a>
</body>

</html>

Page 2 : [Link]

<!DOCTYPE html>

<html>

<head>

<title>Register</title>

</head>

<body>

<h2>Registration Form</h2>

<form action="RegisterServlet" method="post">

Username

<input type="text"
name="username"

required>

<br><br>

Password

<input type="password"

name="password"

required>

<br><br>

Email

<input type="email"

name="email"

required>

<br><br>
<input type="submit"

value="Register">

</form>

</body>

</html>

Page 3 : [Link]

<!DOCTYPE html>

<html>

<head>

<title>Login</title>

</head>

<body>

<h2>Login</h2>
<form action="LoginServlet" method="post">

Username

<input type="text"

name="username"

required>

<br><br>

Password

<input type="password"

name="password"

required>

<br><br>

<input type="submit"

value="Login">
</form>

</body>

</html>

Page 4 : [Link]

<!DOCTYPE html>

<html>

<head>

<title>About</title>

</head>

<body>

<h2>About Website</h2>

<p>

This website is developed using


HTML,

Servlet,

JDBC

and

MySQL.

</p>

<a href="[Link]">

Home

</a>

</body>
</html>

[Link]

package [Link];

import [Link];

import [Link];

public class DBConnection {

public static Connection getConnection() {

Connection con = null;

try {

[Link]("[Link]");

con = [Link](
"jdbc:mysql://localhost:3306/studentdb",

"root",

"root");

catch(Exception e) {

[Link]();

return con;

}
[Link]

package [Link];

import [Link].*;

import [Link].*;

import [Link].*;

import [Link];

import [Link].*;

@WebServlet("/RegisterServlet")

public class RegisterServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

String username=[Link]("username");
String password=[Link]("password");

String email=[Link]("email");

try{

Connection con=[Link]();

PreparedStatement ps=[Link](

"insert into users(username,password,email) values(?,?,?)");

[Link](1,username);

[Link](2,password);

[Link](3,email);

[Link]();
[Link]("[Link]");

catch(Exception e){

[Link]();

[Link]

package [Link];

import [Link].*;

import [Link].*;
import [Link].*;

import [Link];

import [Link].*;

@WebServlet("/LoginServlet")

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out=[Link]();

String username=[Link]("username");
String password=[Link]("password");

try{

Connection con=[Link]();

PreparedStatement ps=[Link](

"select * from users where username=? and password=?");

[Link](1,username);

[Link](2,password);

ResultSet rs=[Link]();

if([Link]()){

[Link]("username",username);
RequestDispatcher
rd=[Link]("WelcomeServlet");

[Link](request,response);

else{

[Link]("<h2>Login Failed</h2>");

catch(Exception e){

[Link]();

}
}

[Link]

package [Link];

import [Link].*;

import [Link].*;

import [Link];

import [Link].*;

@WebServlet("/WelcomeServlet")

public class WelcomeServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,

HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");

PrintWriter out=[Link]();

String user=(String)

[Link]("username");

[Link]("<h1>Welcome "+user+"</h1>");

[Link]("<a href='[Link]'>About</a>");

Run the Project


1. Start Apache Tomcat in Eclipse.

2. Right-click the project.

3. Select Run As → Run on Server.

4. Choose Apache Tomcat.

5. Click Finish.

6. Open:

[Link]

Project Flow

Home Page


Registration Page


Data Stored in MySQL


Login Page



LoginServlet


WelcomeServlet


About Page

Output

Home Page

Student Portal

Register

Login

About

Registration

Username : Rahul
Password : 12345

Email : rahul@[Link]

After clicking Register, the data is saved in the MySQL database.

Login

Username : Rahul

Password : 12345

Welcome Page

Welcome Rahul

About

Viva Questions

Q1. Which Java EE technologies are used in this project?


Answer: HTML, Servlet, JDBC, and MySQL.

Q2. What is the role of [Link]?


Answer: It creates and returns a connection to the MySQL database.
Q3. Why is PreparedStatement used?
Answer: It executes parameterized SQL queries and helps prevent SQL
injection.

Q4. What is the purpose of RequestDispatcher?


Answer: It forwards the request from one servlet to another while
preserving the request data.

Q5. How many pages are included in this project?


Answer: Five pages: Home, Registration, Login, Welcome, and About.
12. Implement the following using Spring Concept

a. Build web application in Java with spring boot3

Aim

Develop a Simple Web Application using Spring Boot 3 that displays a


welcome message.

This application demonstrates:

 Spring Boot 3

 Spring MVC

 Embedded Tomcat

 HTML View

Software Required

 Eclipse IDE (Spring Tools Suite preferred)

 JDK 17 or above

 Spring Boot 3

 Maven

 Web Browser

Dependencies Required
While creating the project, select:

 Spring Web

 Thymeleaf

Step 1: Create Spring Boot Project

Open Eclipse

File → New → Spring Starter Project

Project Name

SpringBootWebApp

Group

[Link]

Artifact

SpringBootWebApp

Packaging

Jar

Java Version

17

Click Next.

Select Dependencies

Spring Web
Thymeleaf

Click Finish.

Project Structure

SpringBootWebApp

├── src/main/java

│ │

│ └── [Link]

│ │

│ ├── [Link]

│ └── [Link]

├── src/main/resources

│ │

│ ├── static

│ │

│ ├── templates

│ │ └── [Link]

│ │
│ └── applica [Link] es

└── [Link]

Step 2: Main Class

Create

[Link]

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class SpringBootWebAppApplication {

public static void main(String[] args) {

[Link](

[Link],

args);
}

Step 3: Create Controller

Create

[Link]

package [Link];

import [Link];

import [Link];

import [Link];

@Controller

public class HomeController {

@GetMapping("/")

public String home(Model model) {


[Link]("message",

"Welcome to Spring Boot 3");

return "index";

Step 4: Create HTML Page

Create

src/main/resources/templates/[Link]

<!DOCTYPE html>

<html xmlns:th="[Link]

<head>

<meta charset="UTF-8">
<title>Spring Boot</title>

</head>

<body>

<h1 th:text="${message}"></h1>

<p>

This is a simple Spring Boot 3 Web Application.

</p>

</body>

</html>

Step 5: [Link]

Create
src/main/resources/[Link]

[Link]=SpringBootWebApp

[Link]=8080

Step 6: [Link]

<dependencies>

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

</dependencies>

Run the Project

1. Right Click [Link]

2. Select

Run As → Spring Boot App

3. Open Browser

[Link]

Output

Welcome to Spring Boot 3

This is a simple Spring Boot 3 Web Application.

Explanation of Important Code

@SpringBootApplication
@SpringBootApplication

Marks the main class as a Spring Boot application. It enables auto-


configuration and component scanning.

[Link]()

[Link](

[Link],

args);

Starts the Spring Boot application and the embedded Tomcat server.

@Controller

@Controller

Marks the class as a Spring MVC Controller.

@GetMapping("/")

@GetMapping("/")

Maps the root URL (/) to the home() method.

Model

[Link]("message",
"Welcome to Spring Boot 3");

Sends data from the controller to the HTML page.

th:text

<h1 th:text="${message}"></h1>

Displays the value of the message attribute using Thymeleaf.

Viva Questions

Q1. What is Spring Boot?

Answer:
Spring Boot is a framework built on the Spring Framework that
simplifies the development of Java applications by providing auto-
configuration, embedded servers, and production-ready features.

Q2. What is the purpose of @SpringBootApplication?

Answer:
It combines @Configuration, @EnableAutoConfiguration, and
@ComponentScan to configure and start the application automatically.

Q3. What is a Controller in Spring Boot?


Answer:
A Controller handles incoming HTTP requests and returns a response or
view to the client.

Q4. What is Thymeleaf?

Answer:
Thymeleaf is a server-side Java template engine used to create dynamic
HTML pages in Spring Boot applications.

Q5. Does Spring Boot require an external Tomcat server?

Answer:
No. Spring Boot includes an embedded Tomcat server by default, so
you can run the application directly without installing or configuring
Tomcat separately.
b. Develop application using Spring Framework, Lightweight

Aim

Develop a simple Spring Framework (Lightweight) application using


Spring IoC (Inversion of Control) and Dependency Injection (DI).

The application demonstrates how Spring creates and manages Java


objects (Beans).

Software Required

 Eclipse IDE

 JDK 17 or above

 Spring Framework Libraries

 Maven (Recommended)
Technologies Used

 Spring Core

 Spring Context

 Java

Step 1: Create Maven Project

Open Eclipse

File → New → Maven Project

Project Name

SpringLightweightApp

Group Id

[Link]

Artifact Id

SpringLightweightApp

Click Finish.

Step 2: Add Spring Dependency

Open [Link]

<dependencies>
<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-context</artifactId>

<version>6.1.8</version>

</dependency>

</dependencies>

Save the file. Maven will automatically download the required libraries.

Step 3: Project Structure

SpringLightweightApp

├── src/main/java

│ │

│ └── [Link]

│ │

│ ├── [Link]

│ ├── [Link]

│ └── [Link]


└── [Link]

Step 4: Create [Link]

package [Link];

public class Student {

public void display() {

[Link]("Welcome to Spring Framework");

Step 5: Create [Link]

package [Link];

import [Link];

import [Link];
@Configuration

public class AppConfig {

@Bean

public Student student() {

return new Student();

Step 6: Create [Link]

package [Link];

import [Link];

import
[Link]
ontext;
public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new AnnotationConfigApplicationContext([Link]);

Student student = [Link]([Link]);

[Link]();

Project Structure

SpringLightweightApp

├── src/main/java
│ │

│ └── [Link]

│ │

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

└── [Link]

Run the Project

1. Right-click [Link]

2. Select Run As → Java Applica on

Console Output

Welcome to Spring Framework

Explanation of Important Code

@Configuration

@Configuration

 Marks the class as a Spring configuration class.


 It contains bean definitions.

@Bean

@Bean

public Student student() {

return new Student();

 Creates a Spring Bean.

 Spring manages the object's lifecycle.

ApplicationContext

ApplicationContext context =

new AnnotationConfigApplicationContext([Link]);

 Loads the Spring container.

 Reads the configuration class.

getBean()

Student student = [Link]([Link]);

 Retrieves the Student object from the Spring container.


display()

[Link]();

 Calls the method of the Spring-managed bean.

Advantages of Spring Framework (Lightweight)

 Lightweight and fast

 Supports Dependency Injection (DI)

 Easy to maintain

 Loose coupling between objects

 Easy integration with Hibernate, JDBC, JPA, and Spring Boot

Viva Questions

Q1. What is the Spring Framework?

Answer:
Spring Framework is a lightweight Java framework used to develop
enterprise applications. It provides features like Dependency Injection
(DI) and Inversion of Control (IoC).

Q2. Why is Spring called a lightweight framework?


Answer:
It uses only the required modules, consumes fewer resources, and does
not require a heavy application server.

Q3. What is IoC (Inversion of Control)?

Answer:
IoC means the Spring container creates and manages objects instead of
the programmer creating them using the new keyword.

Q4. What is Dependency Injection (DI)?

Answer:
Dependency Injection is a technique where Spring automatically
provides the required objects (dependencies) to a class.

Q5. What is ApplicationContext?

Answer:
ApplicationContext is the Spring container that creates, configures, and
manages Spring beans.

Q6. What is a Bean in Spring?

Answer:
A Bean is a Java object that is created, configured, and managed by the
Spring container.
c. Containers and Dependency Injection with Spring

Aim

Develop a simple application to demonstrate Spring IoC Container and


Dependency Injection (DI).

The application will:

 Create a Student object.

 Inject an Address object into Student using Spring.

 Display the student details.

Software Required

 Eclipse IDE

 JDK 17 or above

 Maven

 Spring Framework (Spring Context)

Technologies Used

 Spring Core

 Spring Container (IoC)

 Dependency Injection (DI)

 Java
Step 1: Create Maven Project

Open Eclipse

File → New → Maven Project

Project Name

SpringCDIApp

Group Id

[Link]

Artifact Id

SpringCDIApp

Click Finish.

Step 2: Add Spring Dependency

Open [Link]

<dependencies>

<dependency>

<groupId>[Link]</groupId>

<artifactId>spring-context</artifactId>

<version>6.1.8</version>
</dependency>

</dependencies>

Save the project.

Step 3: Project Structure

SpringCDIApp

├── src/main/java

│ └── [Link]

│ ├── [Link]

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

└── [Link]

Step 4: Create [Link]


package [Link];

public class Address {

private String city;

public Address() {

city = "Mumbai";

public String getCity() {

return city;

Step 5: Create [Link]

package [Link];

import [Link];
public class Student {

@Autowired

private Address address;

public void display() {

[Link]("Student Address : "

+ [Link]());

Step 6: Create [Link]

package [Link];

import [Link];
import [Link];

import [Link];

@Configuration

@ComponentScan(basePackages="[Link]")

public class AppConfig {

@Bean

public Address address() {

return new Address();

@Bean

public Student student() {

return new Student();


}

Step 7: Create [Link]

package [Link];

import [Link];

import
[Link]
nContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new AnnotationConfigApplicationContext([Link]);
Student student =

[Link]([Link]);

[Link]();

Project Structure

SpringCDIApp

├── src/main/java

│ └── [Link]

│ │

│ ├── [Link]

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

└── [Link]

Run the Project

1. Right-click [Link]

2. Select Run As → Java Applica on

Console Output

Student Address : Mumbai

Explanation of Important Code

@Configuration

@Configuration

Marks the class as a Spring configuration class.

@Bean

@Bean

public Address address() {

return new Address();

}
Creates a Spring-managed bean.

@Autowired

@Autowired

private Address address;

Automatically injects the Address object into the Student class.

ApplicationContext

ApplicationContext context =

new AnnotationConfigApplicationContext([Link]);

Loads the Spring IoC Container and manages the beans.

getBean()

Student student = [Link]([Link]);

Retrieves the Student bean from the Spring container.

What is Spring IoC Container?

The IoC (Inversion of Control) Container is the core of the Spring


Framework. It:

 Creates Java objects (Beans).


 Manages their lifecycle.

 Injects dependencies automatically.

What is Dependency Injection (DI)?

Dependency Injection (DI) is a design pattern where the Spring


container automatically provides the required objects (dependencies)
to a class instead of the class creating them itself.

Example:

 Student depends on Address.

 Spring automatically injects the Address object into the Student


object using @Autowired.

Advantages

 Loose coupling between classes.

 Easy to maintain and test.

 Better code reusability.

 Spring manages object creation automatically.

 Simplifies application development.

Viva Questions

Q1. What is the Spring IoC Container?


Answer: The Spring IoC Container creates, configures, and manages
Spring beans and their lifecycle.

Q2. What is Dependency Injection?

Answer: Dependency Injection is a technique in which Spring


automatically provides the required objects (dependencies) to a class.

Q3. What is @Autowired?

Answer: @Autowired is an annotation used to automatically inject a


bean into another bean.

Q4. What is ApplicationContext?

Answer: ApplicationContext is the Spring container that manages


beans and provides configuration information.

Q5. What is a Spring Bean?

Answer: A Spring Bean is a Java object that is created, configured, and


managed by the Spring IoC Container.

You might also like