0% found this document useful (0 votes)
30 views51 pages

Ep Practical Codes

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

Ep Practical Codes

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

Exp-1: Implement program on XML-DOM parser

 Create an XML file, Example sample.xml:

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

<company>

<employee>

<id>101</id>

<name>John Doe</name>

<department>Engineering</department>

</employee>

<employee>

<id>102</id>

<name>Jane Smith</name>

<department>HR</department>

</employee>

</company>

Example Java code:


import org.w3c.dom.*;

import javax.xml.parsers.*;

import java.io.File;

public class XMLDOMParserExample {

public static void main(String[] args) {

try {

File xmlFile = new File("sample.xml");

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document document = builder.parse(xmlFile);

document.getDocumentElement().normalize();

Element root = document.getDocumentElement();

System.out.println("Root Element: " + root.getNodeName());


NodeList nodeList = document.getElementsByTagName("employee");

// Iterate through the list of nodes

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {

Element employee = (Element) node;

// Get and print each element's data

String id = employee.getElementsByTagName("id").item(0).getTextContent();

String name = employee.getElementsByTagName("name").item(0).getTextContent();

String department =
employee.getElementsByTagName("department").item(0).getTextContent();

System.out.println("\nEmployee:");

System.out.println("ID: " + id);

System.out.println("Name: " + name);

System.out.println("Department: " + department);

} catch (Exception e) {

e.printStackTrace();

}
Exp-2: Implementing XSL Style Sheet to the XML Document
Create the XML File:

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

<catalog>

<book>

<author>J.K. Rowling</author>

<title>Harry Potter and the Sorcerer's Stone</title>

<year>1997</year>

<price>29.99</price>

</book>

<book>

<author>George Orwell</author>

<title>1984</title>

<year>1949</year>

<price>19.99</price>

</book>

</catalog>

Create the XSLT File:

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

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

version="1.0">

<xsl:output method="html" indent="yes"/>

<!-- Template for transforming the catalog -->

<xsl:template match="/">

<html>

<head>

<title>Book Catalog</title>

</head>

<body>

<h1>Book Catalog</h1>
<table border="1">

<tr>

<th>Author</th>

<th>Title</th>

<th>Year</th>

<th>Price</th>

</tr>

<xsl:for-each select="catalog/book">

<tr>

<td><xsl:value-of select="author"/></td>

<td><xsl:value-of select="title"/></td>

<td><xsl:value-of select="year"/></td>

<td><xsl:value-of select="price"/></td>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

Write Java Code to Apply the XSLT Transformation

Create a Java Class to Perform the Transformation:

In the src folder, right-click and create a new Class named XSLTTransformer.

Add the following Java code to apply the XSLT transformation:

import javax.xml.transform.*;

import javax.xml.transform.stream.*;

import java.io.*;

public class XSLTTransformer {

public static void main(String[] args) {

try {
// Create a source for the XML document

File xmlFile = new File("input.xml");

StreamSource xmlSource = new StreamSource(xmlFile);

// Create a source for the XSLT stylesheet

File xsltFile = new File("transform.xsl");

StreamSource xsltSource = new StreamSource(xsltFile);

// Create a transformer factory

TransformerFactory transformerFactory = TransformerFactory.newInstance();

Transformer transformer = transformerFactory.newTransformer(xsltSource);

// Set up the output stream (for HTML output)

File outputFile = new File("output.html");

StreamResult result = new StreamResult(outputFile);

// Perform the transformation

transformer.transform(xmlSource, result);

// Print success message

System.out.println("Transformation successful. Output written to output.html");

} catch (Exception e) {

e.printStackTrace();

}
Exp-3: Handling form data submitted through HTTP POST requests

Create the HTML Form

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Form Submission</title>

</head>

<body>

<h1>Submit Your Details</h1>

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

<label for="name">Name:</label>

<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br><br>

<button type="submit">Submit</button>

</form>

</body>

</html>

Create the Servlet

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

// Map the servlet to the URL

@WebServlet("/submitForm")

public class FormServlet extends HttpServlet {


private static final long serialVersionUID = 1L;

// Handle POST requests

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Get form data

String name = request.getParameter("name");

String email = request.getParameter("email");

// Respond back to the client

response.setContentType("text/html");

response.getWriter().println("<h1>Form Submitted Successfully!</h1>");

response.getWriter().println("<p>Name: " + name + "</p>");

response.getWriter().println("<p>Email: " + email + "</p>");

Configure web.xml (Optional)

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">

<servlet>

<servlet-name>FormServlet</servlet-name>

<servlet-class>FormServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>FormServlet</servlet-name>

<url-pattern>/submitForm</url-pattern>

</servlet-mapping>

</web-app>
Exp-4: Reading and writing data to and from a database using Servlets and JDBC
Create a Database and Table

CREATE DATABASE ExampleDB;

USE ExampleDB;

CREATE TABLE Users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

email VARCHAR(100)

);

Create the Eclipse Project

1. Create a Dynamic Web Project in Eclipse.

2. Add the database driver JAR (e.g., mysql-connector-java-X.X.X.jar) to the project's


WEB-INF/lib folder.

Write the Servlet Code

Create a Servlet

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// JDBC URL, username, and password of MySQL server

private static final String URL = "jdbc:mysql://localhost:3306/ExampleDB";

private static final String USER = "root"; // Update with your MySQL username

private static final String PASSWORD = "password"; // Update with your MySQL password

// JDBC variables

private Connection connection;

@Override

public void init() throws ServletException {

try {

// Initialize JDBC connection

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

connection = DriverManager.getConnection(URL, USER, PASSWORD);

} catch (Exception e) {

throw new ServletException("Database connection failed", e);

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Handle writing data to the database

String name = request.getParameter("name");

String email = request.getParameter("email");

try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO Users (name, email)


VALUES (?, ?)")) {

stmt.setString(1, name);
stmt.setString(2, email);

stmt.executeUpdate();

response.getWriter().println("User added successfully!");

} catch (Exception e) {

response.getWriter().println("Error: " + e.getMessage());

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Handle reading data from the database

response.setContentType("text/html");

PrintWriter out = response.getWriter();

try (PreparedStatement stmt = connection.prepareStatement("SELECT * FROM Users");

ResultSet rs = stmt.executeQuery()) {

out.println("<h1>Users List</h1>");

out.println("<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th></tr>");

while (rs.next()) {

out.println("<tr><td>" + rs.getInt("id") + "</td><td>" +

rs.getString("name") + "</td><td>" + rs.getString("email") + "</td></tr>");

out.println("</table>");

} catch (Exception e) {

out.println("Error: " + e.getMessage());

@Override

public void destroy() {


try {

if (connection != null) {

connection.close();

} catch (Exception e) {

e.printStackTrace();

Create an HTML Form

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>User Form</title>

</head>

<body>

<h1>Add a New User</h1>

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

<label for="name">Name:</label>

<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br><br>

<button type="submit">Add User</button>

</form>

<br>

<a href="UserServlet">View All Users</a>

</body>

</html>
EXP-5: Create a JSP page that displays a simple login form

login.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java" %>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Login Form</title>

<style>

body {

font-family: Arial, sans-serif;

display: flex;

justify-content: center;

align-items: center;

height: 100vh;

margin: 0;

background-color: white;

.login-container {

width: 300px;

padding: 30px;

background-color: white;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

border-radius: 8px;

h2 {

text-align: center;

.form-group {

margin-bottom: 15px;
}

input[type="text"], input[type="password"] {

width: 100%;

padding: 10px;

border: 1px solid #ddd;

border-radius: 4px;

box-sizing: border-box;

input[type="submit"] {

width: 100%;

padding: 10px;

background-color: #4CAF50;

color: white;

border: none;

border-radius: 4px;

cursor: pointer;

input[type="submit"]:hover {

background-color: #45a049;

.error-message {

color: red;

font-size: 14px;

margin-top: 10px;

</style>

</head>

<body>

<div class="login-container">

<h2>Login</h2>
<form action="loginServlet" method="POST">

<div class="form-group">

<label for="username">Username</label>

<input type="text" id="username" name="username" placeholder="Enter your username"


required />

</div>

<div class="form-group">

<label for="password">Password</label>

<input type="password" id="password" name="password" placeholder="Enter your


password" required />

</div>

<div class="form-group">

<input type="submit" value="Login" />

</div>

</form>

<div class="error-message">

<!-- This will be populated by the login validation if necessary -->

<%= request.getAttribute("errorMessage") != null ? request.getAttribute("errorMessage") : ""


%>

</div>

</div>

</body>

</html>

Create the Servlet to Handle Login Logic

LoginServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

// Get form parameters

String username = request.getParameter("username");

String password = request.getParameter("password");

// Simple validation (You can replace this with actual authentication logic)

if ("admin".equals(username) && "password123".equals(password)) {

// Successful login

response.sendRedirect("welcome.jsp");

} else {

// Invalid login

request.setAttribute("errorMessage", "Invalid username or password.");

RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");

dispatcher.forward(request, response);

Create a Welcome Page

If the login is successful, you should redirect the user to a welcome page.

welcome.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java" %>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Welcome</title>

</head>

<body>

<h2>Welcome, you have logged in successfully!</h2>


<p><a href="login.jsp">Logout</a></p>

</body>

</html>

EXP-6: Write a JSP page that displays a table of data retrieved from a database
Set up the Database:

First, you need a database and table. Below is an example for a simple employees table in MySQL.

CREATE DATABASE company;

USE company;

CREATE TABLE employees (

id INT PRIMARY KEY AUTO_INCREMENT,

first_name VARCHAR(100),

last_name VARCHAR(100),

email VARCHAR(100)

);

INSERT INTO employees (first_name, last_name, email) VALUES

('John', 'Doe', '[email protected]'),

('Jane', 'Smith', '[email protected]'),

('Alice', 'Johnson', '[email protected]');

JDBC Setup:

Create the JSP Page to Display Data:

Example JSP Page: employees.jsp

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

<%@ page contentType="text/html; charset=UTF-8" language="java" %>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Employee List</title>

<style>

table {

width: 80%;

border-collapse: collapse;

margin: 25px 0;

table, th, td {

border: 1px solid black;

th, td {

padding: 10px;

text-align: left;

th {

background-color: #f2f2f2;

</style>

</head>

<body>

<h2>Employee List</h2>

<%

// Database connection parameters

String jdbcUrl = "jdbc:mysql://localhost:3306/company";

String dbUser = "root"; // Your database username


String dbPassword = "password"; // Your database password

// SQL Query to fetch employee data

String query = "SELECT * FROM employees";

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

// Load the JDBC driver

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

// Establish connection

conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);

// Create statement

stmt = conn.createStatement();

// Execute query

rs = stmt.executeQuery(query);

%>

<table>

<thead>

<tr>

<th>ID</th>

<th>First Name</th>

<th>Last Name</th>

<th>Email</th>

</tr>

</thead>
<tbody>

<%

// Loop through the result set and display data in table rows

while (rs.next()) {

%>

<tr>

<td><%= rs.getInt("id") %></td>

<td><%= rs.getString("first_name") %></td>

<td><%= rs.getString("last_name") %></td>

<td><%= rs.getString("email") %></td>

</tr>

<%

%>

</tbody>

</table>

<%

} catch (Exception e) {

out.println("<p>Error: " + e.getMessage() + "</p>");

e.printStackTrace();

} finally {

try {

if (rs != null) rs.close();

if (stmt != null) stmt.close();

if (conn != null) conn.close();

} catch (SQLException se) {

se.printStackTrace();

%>
</body>

</html>

EXP-7: Create a session bean that provides a method for adding two numbers and
returning the result.
Example: CalculatorBean.java (Session Bean)

import javax.ejb.Stateless;

@Stateless

public class CalculatorBean {

// Method to add two numbers

public int addNumbers(int num1, int num2) {

return num1 + num2;

Create a Remote Interface (Optional for Remote Access)

Create the Remote Interface: CalculatorBeanRemote.java

import javax.ejb.Remote;

@Remote

public interface CalculatorBeanRemote {

int addNumbers(int num1, int num2);

For local access, you can create a local interface instead:

import javax.ejb.Local;

@Local

public interface CalculatorBeanLocal {


int addNumbers(int num1, int num2);

Deploy and Test the EJB

Example: CalculatorServlet.java (Using the EJB)

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.ejb.EJB;

public class CalculatorServlet extends HttpServlet {

@EJB

private CalculatorBean calculatorBean; // Inject the session bean

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Retrieve the numbers from the request

String num1Str = request.getParameter("num1");

String num2Str = request.getParameter("num2");

int num1 = Integer.parseInt(num1Str);

int num2 = Integer.parseInt(num2Str);

// Call the EJB method to add the numbers

int result = calculatorBean.addNumbers(num1, num2);

// Display the result

PrintWriter out = response.getWriter();

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

out.println("<h3>Result of Addition: " + result + "</h3>");


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

EXP-8: Build a session bean that implements a complex business logic for a banking
application
Define the Account Entity

import java.io.Serializable;

public class Account implements Serializable {

private static final long serialVersionUID = 1L;

private int accountId;

private double balance;

public Account(int accountId, double balance) {

this.accountId = accountId;

this.balance = balance;

public int getAccountId() {

return accountId;

public void setAccountId(int accountId) {

this.accountId = accountId;

}
public double getBalance() {

return balance;

public void setBalance(double balance) {

this.balance = balance;

Create the Session Bean (BankingServiceBean)

BankingServiceBean.java (Stateless Session Bean)

import javax.ejb.Stateless;

import java.util.HashMap;

import java.util.Map;

@Stateless

public class BankingServiceBean {

// Simulated in-memory database for accounts

private static Map<Integer, Account> accountDatabase = new HashMap<>();

static {

// Adding some sample accounts

accountDatabase.put(101, new Account(101, 5000.0)); // Account 101 with $5000

accountDatabase.put(102, new Account(102, 3000.0)); // Account 102 with $3000

accountDatabase.put(103, new Account(103, 10000.0)); // Account 103 with $10000

// Check account balance

public double checkBalance(int accountId) {

Account account = accountDatabase.get(accountId);


if (account == null) {

throw new IllegalArgumentException("Account not found.");

return account.getBalance();

// Deposit money into an account

public void deposit(int accountId, double amount) {

if (amount <= 0) {

throw new IllegalArgumentException("Deposit amount must be positive.");

Account account = accountDatabase.get(accountId);

if (account == null) {

throw new IllegalArgumentException("Account not found.");

account.setBalance(account.getBalance() + amount);

// Withdraw money from an account

public void withdraw(int accountId, double amount) {

if (amount <= 0) {

throw new IllegalArgumentException("Withdrawal amount must be positive.");

Account account = accountDatabase.get(accountId);

if (account == null) {

throw new IllegalArgumentException("Account not found.");

if (account.getBalance() < amount) {

throw new IllegalArgumentException("Insufficient funds.");

account.setBalance(account.getBalance() - amount);
}

// Transfer money from one account to another

public void transfer(int fromAccountId, int toAccountId, double amount) {

if (amount <= 0) {

throw new IllegalArgumentException("Transfer amount must be positive.");

Account fromAccount = accountDatabase.get(fromAccountId);

Account toAccount = accountDatabase.get(toAccountId);

if (fromAccount == null) {

throw new IllegalArgumentException("From account not found.");

if (toAccount == null) {

throw new IllegalArgumentException("To account not found.");

if (fromAccount.getBalance() < amount) {

throw new IllegalArgumentException("Insufficient funds in the source account.");

// Perform the transfer

fromAccount.setBalance(fromAccount.getBalance() - amount);

toAccount.setBalance(toAccount.getBalance() + amount);

Testing the Business Logic with a Servlet

Example: BankingServlet.java

import javax.servlet.*;

import javax.servlet.http.*;

import javax.ejb.EJB;
import java.io.*;

public class BankingServlet extends HttpServlet {

@EJB

private BankingServiceBean bankingService; // Injecting the session bean

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

String action = request.getParameter("action");

String message = "";

try {

if ("deposit".equals(action)) {

int accountId = Integer.parseInt(request.getParameter("accountId"));

double amount = Double.parseDouble(request.getParameter("amount"));

bankingService.deposit(accountId, amount);

message = "Deposit successful! New balance: " + bankingService.checkBalance(accountId);

} else if ("withdraw".equals(action)) {

int accountId = Integer.parseInt(request.getParameter("accountId"));

double amount = Double.parseDouble(request.getParameter("amount"));

bankingService.withdraw(accountId, amount);

message = "Withdrawal successful! New balance: " +


bankingService.checkBalance(accountId);

} else if ("transfer".equals(action)) {

int fromAccountId = Integer.parseInt(request.getParameter("fromAccountId"));

int toAccountId = Integer.parseInt(request.getParameter("toAccountId"));

double amount = Double.parseDouble(request.getParameter("amount"));

bankingService.transfer(fromAccountId, toAccountId, amount);

message = "Transfer successful! New balance of " + fromAccountId + ": " +


bankingService.checkBalance(fromAccountId);
} else if ("balance".equals(action)) {

int accountId = Integer.parseInt(request.getParameter("accountId"));

message = "Account balance: " + bankingService.checkBalance(accountId);

} catch (Exception e) {

message = "Error: " + e.getMessage();

// Output the result message

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.println("<h3>" + message + "</h3>");

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

}
Exp-9: Create a RESTful web service that allows users to search for books by title, author,
or ISBN number
Configure Dependencies

<dependencies>

<!-- Spring Boot Starter for Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

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

</dependency>

<!-- Spring Boot Starter for JPA -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<!-- H2 Database (In-memory for testing) -->

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency>

</dependencies>

Run Maven > Update Project to download dependencies.

Define the Entity

package com.example.bookservice.model;

import jakarta.persistence.Entity;

import jakarta.persistence.GeneratedValue;

import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity

public class Book {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String title;

private String author;

private String isbn;

// Getters and Setters

public Long getId() {

return id;

public void setId(Long id) {

this.id = id;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

public String getAuthor() {

return author;

}
public void setAuthor(String author) {

this.author = author;

public String getIsbn() {

return isbn;

public void setIsbn(String isbn) {

this.isbn = isbn;

Create a Repository

package com.example.bookservice.repository;

import com.example.bookservice.model.Book;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface BookRepository extends JpaRepository<Book, Long> {

List<Book> findByTitleContainingIgnoreCase(String title);

List<Book> findByAuthorContainingIgnoreCase(String author);

Book findByIsbn(String isbn);

Create a REST Controller

package com.example.bookservice.controller;
import com.example.bookservice.model.Book;

import com.example.bookservice.repository.BookRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/api/books")

public class BookController {

@Autowired

private BookRepository bookRepository;

// Get all books

@GetMapping

public List<Book> getAllBooks() {

return bookRepository.findAll();

// Search by title

@GetMapping("/search/title")

public List<Book> searchByTitle(@RequestParam String title) {

return bookRepository.findByTitleContainingIgnoreCase(title);

// Search by author

@GetMapping("/search/author")

public List<Book> searchByAuthor(@RequestParam String author) {

return bookRepository.findByAuthorContainingIgnoreCase(author);

}
// Search by ISBN

@GetMapping("/search/isbn")

public Book searchByIsbn(@RequestParam String isbn) {

return bookRepository.findByIsbn(isbn);

// Add a new book

@PostMapping

public Book addBook(@RequestBody Book book) {

return bookRepository.save(book);

Configure the Application

Application Properties

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driver-class-name=org.h2.Driver

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.h2.console.enabled=true

Spring Boot Main Class

package com.example.bookservice;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class BookServiceApplication {

public static void main(String[] args) {

SpringApplication.run(BookServiceApplication.class, args);

}
Exp-10: Create a Maven Project and implement CRUD Operations using Java Persistence
API (JPA)
Add Dependencies to pom.xml

<dependencies>

<!-- JPA and Hibernate -->

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-core</artifactId>

<version>6.2.8.Final</version>

</dependency>

<!-- MySQL Connector -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.33</version>

</dependency>

<!-- JPA API -->

<dependency>

<groupId>jakarta.persistence</groupId>

<artifactId>jakarta.persistence-api</artifactId>

<version>3.1.0</version>

</dependency>

<!-- Logging -->

<dependency>

<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>

<version>3.4.0.Final</version>

</dependency>

</dependencies>

Configure the persistence.xml

<persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.0">

<persistence-unit name="jpa-crud">

<class>com.example.model.Book</class>

<properties>

<!-- Database Configuration -->

<property name="jakarta.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/exampledb" />

<property name="jakarta.persistence.jdbc.user" value="root" />

<property name="jakarta.persistence.jdbc.password" value="password" />

<property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />

<!-- Hibernate Configuration -->

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />

<property name="hibernate.hbm2ddl.auto" value="update" />

<property name="hibernate.show_sql" value="true" />

</properties>

</persistence-unit>

</persistence>

Create the Entity Class

package com.example.model;

import jakarta.persistence.*;

@Entity
public class Book {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String title;

private String author;

private Double price;

// Getters and Setters

public Long getId() {

return id;

public void setId(Long id) {

this.id = id;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

public String getAuthor() {

return author;

public void setAuthor(String author) {


this.author = author;

public Double getPrice() {

return price;

public void setPrice(Double price) {

this.price = price;

Implement CRUD Operations

package com.example.service;

import com.example.model.Book;

import jakarta.persistence.EntityManager;

import jakarta.persistence.EntityManagerFactory;

import jakarta.persistence.Persistence;

import java.util.List;

public class BookService {

private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-


crud");

private final EntityManager em;

public BookService() {

this.em = emf.createEntityManager();

}
// Create a Book

public void addBook(Book book) {

em.getTransaction().begin();

em.persist(book);

em.getTransaction().commit();

// Read a Book by ID

public Book getBook(Long id) {

return em.find(Book.class, id);

// Update a Book

public void updateBook(Long id, String title, String author, Double price) {

Book book = em.find(Book.class, id);

if (book != null) {

em.getTransaction().begin();

book.setTitle(title);

book.setAuthor(author);

book.setPrice(price);

em.getTransaction().commit();

// Delete a Book

public void deleteBook(Long id) {

Book book = em.find(Book.class, id);

if (book != null) {

em.getTransaction().begin();

em.remove(book);

em.getTransaction().commit();
}

// List All Books

public List<Book> listBooks() {

return em.createQuery("SELECT b FROM Book b", Book.class).getResultList();

public void close() {

em.close();

Write the Main Class

package com.example.main;

import com.example.model.Book;

import com.example.service.BookService;

import java.util.List;

public class Main {

public static void main(String[] args) {

BookService service = new BookService();

// Add a new book

Book book1 = new Book();

book1.setTitle("Effective Java");

book1.setAuthor("Joshua Bloch");

book1.setPrice(45.0);

service.addBook(book1);
// List all books

List<Book> books = service.listBooks();

System.out.println("Books:");

for (Book b : books) {

System.out.println(b.getId() + ": " + b.getTitle() + " by " + b.getAuthor());

// Update a book

service.updateBook(1L, "Effective Java", "Joshua Bloch", 50.0);

// Get a single book

Book singleBook = service.getBook(1L);

System.out.println("Updated Book: " + singleBook.getTitle() + " - $" + singleBook.getPrice());

// Delete a book

service.deleteBook(1L);

// Close the service

service.close();

}
Exp-11: Write a RESTful web service that provides the information retrieved from the
database table.
Add Dependencies in pom.xml

<dependencies>

<!-- Spring Boot Starter for Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

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

</dependency>

<!-- Spring Boot Starter for JPA -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<!-- MySQL Connector -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.33</version>

</dependency>

</dependencies>

Run Maven → Update Project to download the dependencies.

Configure the Database

spring.datasource.url=jdbc:mysql://localhost:3306/exampledb

spring.datasource.username=root

spring.datasource.password=yourpassword

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

Create a Database Table

CREATE DATABASE exampledb;

USE exampledb;

CREATE TABLE Book (

id INT AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(255) NOT NULL,

author VARCHAR(255) NOT NULL,

price DECIMAL(10, 2) NOT NULL

);

Define the Entity Class

package com.example.demo.model;

import jakarta.persistence.Entity;

import jakarta.persistence.GeneratedValue;

import jakarta.persistence.GenerationType;

import jakarta.persistence.Id;

@Entity

public class Book {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String title;

private String author;

private Double price;


// Getters and Setters

public Long getId() {

return id;

public void setId(Long id) {

this.id = id;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

public String getAuthor() {

return author;

public void setAuthor(String author) {

this.author = author;

public Double getPrice() {

return price;

public void setPrice(Double price) {


this.price = price;

Create a Repository

package com.example.demo.repository;

import com.example.demo.model.Book;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {

Create the REST Controller

package com.example.demo.controller;

import com.example.demo.model.Book;

import com.example.demo.repository.BookRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/api/books")

public class BookController {

@Autowired

private BookRepository bookRepository;

// Retrieve all books


@GetMapping

public List<Book> getAllBooks() {

return bookRepository.findAll();

// Retrieve a book by ID

@GetMapping("/{id}")

public Book getBookById(@PathVariable Long id) {

return bookRepository.findById(id).orElse(null);

// Add a new book

@PostMapping

public Book addBook(@RequestBody Book book) {

return bookRepository.save(book);

// Update an existing book

@PutMapping("/{id}")

public Book updateBook(@PathVariable Long id, @RequestBody Book updatedBook) {

return bookRepository.findById(id).map(book -> {

book.setTitle(updatedBook.getTitle());

book.setAuthor(updatedBook.getAuthor());

book.setPrice(updatedBook.getPrice());

return bookRepository.save(book);

}).orElse(null);

// Delete a book

@DeleteMapping("/{id}")

public void deleteBook(@PathVariable Long id) {


bookRepository.deleteById(id);

Main Application Class

package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}
Exp-12: Write a RESTful web service that update and delete the data from the database
table using JPA.
Add Dependencies to pom.xml

<dependencies>

<!-- Spring Boot Starter for Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

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

</dependency>

<!-- Spring Boot Starter for JPA -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<!-- MySQL Connector -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.33</version>

</dependency>

</dependencies>

Run Maven > Update Project to download the dependencies.

Configure Database Properties

spring.datasource.url=jdbc:mysql://localhost:3306/exampledb

spring.datasource.username=root

spring.datasource.password=yourpassword

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

Create the Database Table

CREATE DATABASE exampledb;

USE exampledb;

CREATE TABLE Book (

id INT AUTO_INCREMENT PRIMARY KEY,

title VARCHAR(255) NOT NULL,

author VARCHAR(255) NOT NULL,

price DECIMAL(10, 2) NOT NULL

);

Define the Entity Class

package com.example.model;

import jakarta.persistence.Entity;

import jakarta.persistence.GeneratedValue;

import jakarta.persistence.GenerationType;

import jakarta.persistence.Id;

@Entity

public class Book {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

private String title;

private String author;

private Double price;


// Getters and Setters

public Long getId() {

return id;

public void setId(Long id) {

this.id = id;

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

public String getAuthor() {

return author;

public void setAuthor(String author) {

this.author = author;

public Double getPrice() {

return price;

public void setPrice(Double price) {


this.price = price;

Create the Repository Interface

package com.example.repository;

import com.example.model.Book;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {

Create the REST Controller

package com.example.controller;

import com.example.model.Book;

import com.example.repository.BookRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController

@RequestMapping("/api/books")

public class BookController {

@Autowired

private BookRepository bookRepository;

// Update a Book
@PutMapping("/{id}")

public String updateBook(@PathVariable Long id, @RequestBody Book updatedBook) {

Optional<Book> optionalBook = bookRepository.findById(id);

if (optionalBook.isPresent()) {

Book book = optionalBook.get();

book.setTitle(updatedBook.getTitle());

book.setAuthor(updatedBook.getAuthor());

book.setPrice(updatedBook.getPrice());

bookRepository.save(book);

return "Book updated successfully.";

} else {

return "Book not found.";

// Delete a Book

@DeleteMapping("/{id}")

public String deleteBook(@PathVariable Long id) {

if (bookRepository.existsById(id)) {

bookRepository.deleteById(id);

return "Book deleted successfully.";

} else {

return "Book not found.";

Main Application Class

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

You might also like