Ep Practical Codes
Ep Practical Codes
Ep Practical Codes
<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>
import javax.xml.parsers.*;
import java.io.File;
try {
document.getDocumentElement().normalize();
if (node.getNodeType() == Node.ELEMENT_NODE) {
String id = employee.getElementsByTagName("id").item(0).getTextContent();
String department =
employee.getElementsByTagName("department").item(0).getTextContent();
System.out.println("\nEmployee:");
} catch (Exception e) {
e.printStackTrace();
}
Exp-2: Implementing XSL Style Sheet to the XML Document
Create the XML File:
<catalog>
<book>
<author>J.K. Rowling</author>
<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>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<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>
In the src folder, right-click and create a new Class named XSLTTransformer.
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.*;
try {
// Create a source for the XML document
transformer.transform(xmlSource, result);
} catch (Exception e) {
e.printStackTrace();
}
Exp-3: Handling form data submitted through HTTP POST requests
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Submission</title>
</head>
<body>
<label for="name">Name:</label>
<label for="email">Email:</label>
<button type="submit">Submit</button>
</form>
</body>
</html>
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;
@WebServlet("/submitForm")
response.setContentType("text/html");
<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
USE ExampleDB;
name VARCHAR(100),
email VARCHAR(100)
);
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 String USER = "root"; // Update with your MySQL username
private static final String PASSWORD = "password"; // Update with your MySQL password
// JDBC variables
@Override
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
@Override
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
} catch (Exception e) {
@Override
response.setContentType("text/html");
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("</table>");
} catch (Exception e) {
@Override
if (connection != null) {
connection.close();
} catch (Exception e) {
e.printStackTrace();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Form</title>
</head>
<body>
<label for="name">Name:</label>
<label for="email">Email:</label>
</form>
<br>
</body>
</html>
EXP-5: Create a JSP page that displays a simple login form
login.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: white;
.login-container {
width: 300px;
padding: 30px;
background-color: white;
border-radius: 8px;
h2 {
text-align: center;
.form-group {
margin-bottom: 15px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 10px;
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>
</div>
<div class="form-group">
<label for="password">Password</label>
</div>
<div class="form-group">
</div>
</form>
<div class="error-message">
</div>
</div>
</body>
</html>
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Simple validation (You can replace this with actual authentication logic)
// Successful login
response.sendRedirect("welcome.jsp");
} else {
// Invalid login
dispatcher.forward(request, response);
If the login is successful, you should redirect the user to a welcome page.
welcome.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
</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.
USE company;
first_name VARCHAR(100),
last_name VARCHAR(100),
email VARCHAR(100)
);
JDBC Setup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Employee List</title>
<style>
table {
width: 80%;
border-collapse: collapse;
margin: 25px 0;
table, th, td {
th, td {
padding: 10px;
text-align: left;
th {
background-color: #f2f2f2;
</style>
</head>
<body>
<h2>Employee List</h2>
<%
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
// 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>
</tr>
<%
%>
</tbody>
</table>
<%
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
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
import javax.ejb.Remote;
@Remote
import javax.ejb.Local;
@Local
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.EJB;
@EJB
@Override
out.println("<html><body>");
EXP-8: Build a session bean that implements a complex business logic for a banking
application
Define the Account Entity
import java.io.Serializable;
this.accountId = accountId;
this.balance = balance;
return accountId;
this.accountId = accountId;
}
public double getBalance() {
return balance;
this.balance = balance;
import javax.ejb.Stateless;
import java.util.HashMap;
import java.util.Map;
@Stateless
static {
return account.getBalance();
if (amount <= 0) {
if (account == null) {
account.setBalance(account.getBalance() + amount);
if (amount <= 0) {
if (account == null) {
account.setBalance(account.getBalance() - amount);
}
if (amount <= 0) {
if (fromAccount == null) {
if (toAccount == null) {
fromAccount.setBalance(fromAccount.getBalance() - amount);
toAccount.setBalance(toAccount.getBalance() + amount);
Example: BankingServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.EJB;
import java.io.*;
@EJB
@Override
try {
if ("deposit".equals(action)) {
bankingService.deposit(accountId, amount);
} else if ("withdraw".equals(action)) {
bankingService.withdraw(accountId, amount);
} else if ("transfer".equals(action)) {
} catch (Exception e) {
response.setContentType("text/html");
out.println("<html><body>");
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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
package com.example.bookservice.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
return id;
this.id = id;
return title;
this.title = title;
return author;
}
public void setAuthor(String author) {
this.author = author;
return 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;
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")
@Autowired
@GetMapping
return bookRepository.findAll();
// Search by title
@GetMapping("/search/title")
return bookRepository.findByTitleContainingIgnoreCase(title);
// Search by author
@GetMapping("/search/author")
return bookRepository.findByAuthorContainingIgnoreCase(author);
}
// Search by ISBN
@GetMapping("/search/isbn")
return bookRepository.findByIsbn(isbn);
@PostMapping
return bookRepository.save(book);
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
package com.example.bookservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
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>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.2.8.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.4.0.Final</version>
</dependency>
</dependencies>
<persistence-unit name="jpa-crud">
<class>com.example.model.Book</class>
<properties>
<property name="jakarta.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/exampledb" />
</properties>
</persistence-unit>
</persistence>
package com.example.model;
import jakarta.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
return id;
this.id = id;
return title;
this.title = title;
return author;
return price;
this.price = price;
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 BookService() {
this.em = emf.createEntityManager();
}
// Create a Book
em.getTransaction().begin();
em.persist(book);
em.getTransaction().commit();
// Read a Book by ID
// Update a Book
public void updateBook(Long id, String title, String author, Double price) {
if (book != null) {
em.getTransaction().begin();
book.setTitle(title);
book.setAuthor(author);
book.setPrice(price);
em.getTransaction().commit();
// Delete a Book
if (book != null) {
em.getTransaction().begin();
em.remove(book);
em.getTransaction().commit();
}
em.close();
package com.example.main;
import com.example.model.Book;
import com.example.service.BookService;
import java.util.List;
book1.setTitle("Effective Java");
book1.setAuthor("Joshua Bloch");
book1.setPrice(45.0);
service.addBook(book1);
// List all books
System.out.println("Books:");
// Update a book
// Delete a book
service.deleteBook(1L);
service.close();
}
Exp-11: Write a RESTful web service that provides the information retrieved from the
database table.
Add Dependencies in pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
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
USE exampledb;
);
package com.example.demo.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
return id;
this.id = id;
return title;
this.title = title;
return author;
this.author = author;
return price;
Create a Repository
package com.example.demo.repository;
import com.example.demo.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
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")
@Autowired
return bookRepository.findAll();
// Retrieve a book by ID
@GetMapping("/{id}")
return bookRepository.findById(id).orElse(null);
@PostMapping
return bookRepository.save(book);
@PutMapping("/{id}")
book.setTitle(updatedBook.getTitle());
book.setAuthor(updatedBook.getAuthor());
book.setPrice(updatedBook.getPrice());
return bookRepository.save(book);
}).orElse(null);
// Delete a book
@DeleteMapping("/{id}")
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
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
USE exampledb;
);
package com.example.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
return id;
this.id = id;
return title;
this.title = title;
return author;
this.author = author;
return price;
package com.example.repository;
import com.example.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
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")
@Autowired
// Update a Book
@PutMapping("/{id}")
if (optionalBook.isPresent()) {
book.setTitle(updatedBook.getTitle());
book.setAuthor(updatedBook.getAuthor());
book.setPrice(updatedBook.getPrice());
bookRepository.save(book);
} else {
// Delete a Book
@DeleteMapping("/{id}")
if (bookRepository.existsById(id)) {
bookRepository.deleteById(id);
} else {
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(DemoApplication.class, args);