Professional Documents
Culture Documents
Webframeworks Lab Manual
Webframeworks Lab Manual
Submitted by
Name:……….…………………..……………..
Register No :………….……………….………
Academic Year:………….……………….…….
SRI KRISHNA COLLEGE OF ENGINEERING AND TECHNOLOGY
(AN AUTONOMOUS INSTITUTION,
AFFILIATED TO ANNAUNIVERSITY, CHENNAI)
COIMBATORE–641008
Continuous Assessment
Record
Submitted by
BONAFIDE CERTIFICATE
This is to certify that this record is the bonafide record of work done by Mr./Ms.
during the academic year 2022–2023.
Record of laboratory
Range of Marks
Criteria Below
Excellent Good Average
Average
Aim & Algorithm
(20 marks)
19-20 17-18 15-16 0-14
Components EX1 EX2 EX3 EX4 EX5 EX6 EX7 EX8 EX9 EX10 EX11 EX12
TOTAL
Consolidated Marks(100) _
Faculty Signature __
Ex.no: 1 Developing a News API Web Application with Pagination and Sorting
Date: Functionalities
AIM:
To create a web application that fetches the object from the NewsAPI based on specific categories
or keywords. The application should allow users to search for news articles using JPQL (Java Persistence
Query Language), implement pagination and sorting functionalities for efficient article retrieval, and ensure
transactional behavior when interacting with the NewsAPI.
Algorithm:
1. Create ApiController class to handle API requests.
2. Develop NewsService class to interact with the NewsAPI.
3. Implement READ operations for accessing news articles.
4. Configure endpoints for retrieving news articles based on categories, sources, pagination, and sorting.
5. Fetch news articles using the NewsAPI by making HTTP requests.
Program:
1. ApiController.java:
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
private NewsService newsService;
@GetMapping("/news/source/{source}")
public ResponseEntity<?> getNewsBySource(@PathVariable String source) {
List<Article> articles = newsService.getNewsBySource(source);
return ResponseEntity.ok().body(articles);
}
@GetMapping("/country/{country}/category/{category}")
public ResponseEntity<?> getNewsByCountryAndCategory(@PathVariable String country, @PathVariable String
category) {
List<Article> articles = newsService.getNewsByCountryAndCategory(country, category);
return ResponseEntity.ok().body(articles);
}
@GetMapping("/country/{country}/category/{category}/{pageNumber}/{pageSize}/{sortField}")
public ResponseEntity<?> getNewsByCountryAndCategoryWithPaginationAndSorting(
@PathVariable String country,
@PathVariable String category,
@PathVariable int pageNumber,
@PathVariable int pageSize,
@PathVariable String sortField
){
Page<Article> articlesPage = newsService.getNewsByCountryAndCategoryWithPaginationAndSorting(
country, category, pageNumber, pageSize, sortField);
return ResponseEntity.ok().body(articlesPage);
}
}
1
2. NewsService.java:
@Service
public class NewsService {
@Value("${newsapi.apikey}")
private String apiKey;
3. Article.java:
@Data
public class Article {
private String author;
private String title;
private String description;
private String url;
private String urlToImage;
private String publishedAt;
private String content;
}
4. NewsResponse.java:
@Data
public class NewsResponse {
private String status;
private int totalResults;
private List<Article> articles;
}
5. Make sure to configure your application.properties file to include the NewsAPI key:
newsapi.apikey=YOUR_API_KEY
2
Output:
Result :
The program compiled and executed successfully.
3
Ex.no: 2
Date:
Chuck Norris Joke Fetcher Web Application
AIM:
The aim of this web application is to fetch Chuck Norris jokes from the Chuck Norris API based on specific
categories or keywords. It should provide users with the ability to search for jokes using JPQL (Java
Persistence Query Language), implement pagination and sorting functionalities for efficient joke retrieval,
and ensure transactional behavior when interacting with the Chuck Norris API.
Algorithm:
1. Start a new Spring Boot project.
2. Create an "ApiController.java" file in the "Controller" folder to handle API requests.
3. Develop a "JokeService.java" file in the "Service" folder to interact with the Chuck Norris API and
implement reading operations for fetching jokes.
4. Integrate Chuck Norris API (https://api.chucknorris.io) to fetch jokes.
5. Define API endpoints:
• Fetch all categories: /api/jokes/categories
• Fetch joke by category: /api/jokes/random?category={category}
• Free text search: /api/jokes/search?query={query}
• Fetch by ID: /api/jokes/randomById?query={id}
• Fetch Exclude: /api/jokes/random?exclude={category1,category2}
• Fetch Include: /api/jokes/random?include={category1,category2}
6. Add pagination and sorting for efficient joke retrieval.
7. Thoroughly test the application, covering different scenarios including invalid inputs.
8. Document API endpoints and their usage.
9. Deploy the application to a production environment, ensuring proper configuration.
Program:
1. Define Controller class:
@RestController
@RequestMapping("/api/jokes")
public class ApiController {
@Autowired
private JokeService jokeService;
@GetMapping("/categories")
public List<String> getCategories() {
return jokeService.getCategories();
}
@GetMapping("/random")
public Joke getByCategory(@RequestParam String[] category) {
return jokeService.getRandomJoke(category);
}
@GetMapping("/randomById")
4
public Joke getById(@RequestParam String query) {
return jokeService.getRandomJokeById(query);
}
@GetMapping("/randomExclude")
public Joke exclude(@RequestParam String[] exclude) {
return jokeService.getRandomJokeExclude(exclude);
}
@GetMapping("/randomInclude")
public Joke include(@RequestParam String[] include) {
return jokeService.getRandomJokeInclude(include);
}
}
2. Define Service class :
@Service
public class JokeService {
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.chucknorris.io/jokes";
public List<String> getCategories() {
String[] categories = restTemplate.getForObject(url+"/categories",
String[].class);
return Arrays.asList(categories);
}
public Joke getRandomJoke(String[] categories) {
String s = String.join(",", categories);
System.out.println(s);
return restTemplate.getForObject(url+"/random?category="+s, Joke.class);
}
public Joke getRandomJokeById(String id){
return restTemplate.getForObject(url + "/random?query=" + id, Joke.class);
}
public Joke getRandomJokeExclude(String[] categories)
{
String s = String.join(",", categories);
System.out.println(s);
return restTemplate.getForObject(url+"/random?exclude="+s, Joke.class);
}
public Joke getRandomJokeInclude(String[] categories)
{
String s = String.join(",", categories);
return restTemplate.getForObject(url+"/random?include="+s, Joke.class);
} }
3. Create Joke Class to handle the object:
5
@Component
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Joke {
private String[] categories;
private String created_at;
private String icon_url;
private String id;
private String updated_at;
private String url;
private String value;
}
Output:
Result :
The program compiled and executed successfully.
6
Ex.no: 3 Employee Management System with Spring Boot:
Date: Setter Injection and RESTful API
AIM:
The aim of this Web Application is to create a simple Spring Application and inject the literal values by
setter injection. So, create a simple class Employee having three attributes ID, Name, and Designation.
Create setter methods for these attributes and a simple method to print the details of the employee.
Algorithm:
1. Create a new Spring Boot project with OpenJDK 11.
2. Set up the folder structure:
3. Create "Controller", "Models", "Repository", and "Service" folders inside the "src" directory.
4. In the "Models" folder, create an "Employee.java" file with attributes: id (int), name (String), and
designation (String). Implement setter methods for these attributes.
5. In the "Repository" folder, create an "EmployeeRepo.java" file to manage CRUD operations for the
Employee entity.
6. In the "Service" folder, create an "EmployeeService.java" file. Implement business logic for getting
employee details and other functionalities.
7. In the "Controller" folder, create an "ApiController.java" file. Implement RESTful API endpoints for
interacting with employee data:
• POST "/" --> true/false
• GET "/{id}" --> List of employee objects
• GET "/" --> List of employee objects
• GET "/employees/groupBy" --> Returns grouped employee data by designation, salary;
• GET "/employees/findByDesignation?value={value}" --> Returns employee data filtered
• GET "/employees/salaryRange?minSalary={minSalary}&maxSalary={maxSalary}" --> Returns
employee data within the specified salary range
8. Configure “ application.properties” file with the provided database connection and Hibernate
configurations.
9. Test each API endpoint using tools like Postman to ensure functionality.
10. Deploy the application to a server environment, ensuring proper configuration.
Program:
1. Define Controller class:
@RestController
public class ApiController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/")
public Boolean saveEmployee(@RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}
@GetMapping("/")
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
7
}
@GetMapping("/{id}")
public Employee getEmployee(@PathVariable int id) {
return employeeService.getEmployye(id);
}
@GetMapping("/employees/groupBy")
public List<Employee> groupBy() {
return employeeService.groupBy();
}
@GetMapping("/employees/findByDesignation")
public Employee findBy(@RequestParam String value) {
return employeeService.findByDesignation(value);
}
@GetMapping("/employees/salaryRange")
public List<Employee> getEmployeesBetween(@RequestParam int minSalary,
@RequestParam int maxSalary) {
return employeeService.getEmployeesBetween(minSalary, maxSalary);
}
}
2. Define Service class :
@Service
public class EmployeeService {
@Autowired
private EmployeeRepo employeeRepo;
public boolean saveEmployee(Employee employee){
try{
employeeRepo.save(employee);
return true;
}
catch(Exception e) {
return false;
}
}
public List<Employee> getAllEmployees(){
return employeeRepo.findAll();
}
public Employee getEmployye (int id){
return employeeRepo.findById(id).orElse(null);
}
public List<Employee> groupBy(){
return employeeRepo.groupBy();
}
8
public Employee findByDesignation(String value){
return employeeRepo.findByDesignation(value);
}
public List<Employee> getEmployeesBetween(int min, int max){
return employeeRepo.getEmployeesBetween(min, max);
}
}
3. Create Repository interface to implement JPQL Queries:
@Repository
public interface EmployeeRepo extends JpaRepository<Employee, Integer> {
@Query(value = "Select * from employee group by designation,salary,id",
nativeQuery = true)
public List<Employee> groupBy();
@Query("Select e from Employee e where e.designation = ?1")
public Employee findByDesignation(String value);
@Query(value = "Select * from employee where salary between ?1 and ?2",
nativeQuery = true)
public List<Employee> getEmployeesBetween(int min, int max);
}
4. Create a Model class:
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
@Id
private int id;
private String name;
private String designation;
private int salary;
}
9
Output:
10
Result :
The program compiled and executed successfully.
11
Ex.no: 4 Employee Payroll Management System with Spring Boot: JPA, CRUD
Date: Operations, and RESTful API
AIM:
The Aim of the application is to develop a basic Employee Payroll Management System using Spring Boot.
This system will allow users to perform CRUD operations on employee records and retrieve specific
employee information through RESTful API endpoints.
Algorithm:
1. Begin by setting up a new Spring Boot project.
2. Create the project structure as Inside the "src" directory, establish the following folders: "Controller",
"Models", "Service", and "Repository".
3. Implement API endpoints in the "ApiController.java" file:
a. POST "/" to add a new employee record to the database.
b. GET "/{id}" to retrieve employee information by id.
c. GET "/" to fetch the list of all employees.
d. GET "/employee/first-three-characters-of-first-name" to return the first three characters of the
first name of all employees.
e. GET "/employees/hired/{hire_date}" to fetch employees hired on a specified date.
4. Configure the application.properties file with database connection settings provided.
5. Test API endpoints using tools like Postman to ensure functionality.
6. Run the application using 'mvn spring-boot:run' command.
7. Monitor application performance and handle any encountered issues.
8. Document API endpoints for future reference.
9. The Employee Payroll Management System is now operational, providing basic functionalities to
manage employee records.
Program:
1. Define Controller class:
@RestController
@RequestMapping("/")
public class ApiController {
@Autowired
private EmployeeService employeeService;
@PostMapping("/")
public boolean addEmployee(@RequestBody Employee employee) {
return employeeService.addEmployee(employee);
}
@GetMapping("/{id}")
public Employee getEmployeeById(@PathVariable("id") int id) {
return employeeService.getEmployeeById(id);
}
@GetMapping("/")
12
public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
@GetMapping("/employees/first-three-characters-of-first-name")
public List<String> getFirstThreeCharactersOfFirstName() {
return employeeService.getFirstThreeCharactersOfFirstName();
}
@GetMapping("/employees/hired/{hireDate}")
public List<Employee> getEmployeesHiredOnDate(@PathVariable("hireDate")
LocalDate hireDate) {
return employeeService.getEmployeesHiredOnDate(hireDate);
}
}
2. Define Service class :
@Service
public class EmployeeService {
@Autowired
private EmployeeRepo employeeRepo;
public boolean addEmployee(Employee employee) {
try{
employeeRepo.save(employee);
return true;
}
catch(Exception e){
return false;
}
}
public Employee getEmployeeById(int id) {
return employeeRepo.findById(id).orElse(null);
}
public List<Employee> getAllEmployees() {
return employeeRepo.findAll();
}
public List<String> getFirstThreeCharactersOfFirstName() {
List<Employee> employees = employeeRepo.findAll();
return employees.stream()
.map(employee -> employee.getName().substring(0,
Math.min(employee.getName().length(), 3)))
.collect(Collectors.toList());
}
public List<Employee> getEmployeesHiredOnDate(LocalDate hireDate) {
return employeeRepo.findByHireDate(hireDate);
13
}
}
3. Create a Repository to handle the connectivity:
@Repository
public interface EmployeeRepo extends JpaRepository<Employee, Integer> {
List<Employee> findByHireDate(LocalDate hire_date);
}
Output:
14
Result :
The program compiled and executed successfully.
15
Ex.no: 5 Employee Payroll Management System Wit Spring Boot: LIKE Queries
Date: and RESTful API OVERVIEW.
Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee data by
storing it in a database and providing CRUD operations via RESTful API endpoints.
Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.
Program:
1.Define controller class
@RestController
public class ApiController {
@Autowired
public EmployeeService employeeService;
@PostMapping("/")
public Boolean postData(@RequestBody Employee employee) {
return employeeService.postData(employee);
}
@GetMapping("/getstart/{name}")
public List<Employee> getStartWith(@PathVariable String name){
return employeeService.getByStartWith(name);
}
@GetMapping("/getends/{name}")
public List<Employee> getEndsWith(@PathVariable String name){
return employeeService.getByEndsWith(name);
}
@GetMapping("/getcontains/{name}")
public List<Employee> getContains(@PathVariable String name){
return employeeService.getByContains(name);
}
@GetMapping("/getcontaining/{name}")
public List<Employee> getContaining(@PathVariable String name){
return employeeService.getByContaining(name);
}
@GetMapping("/getIscontaining/{name}")
public List<Employee> getIsContaining(@PathVariable String name){
return employeeService.getByIsContaining(name);
}
}
16
2.Model class
public class Employee {
@Id
private int id;
private String name;
private String designation;
public Employee(int id, String name, String designation) {
this.id = id;
this.name = name;
this.designation = designation;
}
}
3.Service Class
@Service
public class EmployeeService {
@Autowired
public EmployeeRepo employeeRepo;
17
Output:
18
Result:
The program compiled and executed successfully.
19
Ex.no: 6 Employee Payroll Management System with Spring Boot:
Date: NOT LIKE Queries and RESTful API
Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee
data by storing it in a database and providing CRUD operations via RESTful API endpoints.
Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.
Program:
1.Define controller class
@Autowired
public EmployeeService employeeService;
@PostMapping("/")
public Boolean postData(@RequestBody Employee employee) {
return employeeService.postData(employee);
}
@GetMapping("/getnotcontains/{name}")
public List<Employee> getNotContains(@PathVariable String name) {
return employeeService.getNotContains(name);
}
@GetMapping("/getnotcontaining/{name}")
public List<Employee> getNotContaining(@PathVariable String name) {
return employeeService.getNotContaining(name);
}
@GetMapping("/getnotLike/{name}")
public List<Employee> getNotLike(@PathVariable String name) {
return employeeService.getNotLike(name);
}
2.Model class
20
private String designation;
public Employee(int id, String name, String designation) {
this.id = id;
this.name = name;
this.designation = designation;
}
}
3.Service Class
@Service
public class EmployeeService {
@Autowired
public EmployeeRepo employeeRepo;
4 .Repository Class
@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
public List<Employee> findAllByNameNotLike(String name);
public List<Employee> findAllByNameNotContains(String name);
public List<Employee> findAllByNameNotContaining(String name);
}
21
Output:
Result:
The program compiled and executed successfully.
22
Ex.no: 7 Employee Payroll Management System with Spring Boot:
Date: NOT LIKE Queries and RESTful API
Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee
data by storing it in a database and providing CRUD operations via RESTful API endpoints.
Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.
Program:
1.Define controller class
@Autowired
public StudentService studentService;
@PostMapping("/")
public boolean postStudent(@RequestBody Student student){
return studentService.PostData(student);
}
@PutMapping("/put/{id}")
public Student putStudent(@RequestBody Student student,@PathVariable int id){
return studentService.putData(id, student);
}
@GetMapping("/get")
public List<Student> getAll(){
return studentService.getAll();
}
@GetMapping("/get/id/{id}")
public Student getById(@PathVariable int id) {
return studentService.getById(id);
}
@DeleteMapping("/del/{id}")
public void deleteById(@PathVariable int id){
studentService.delData(id);
}
@GetMapping("/get/field/{field}")
public List<Student> getBySort(@PathVariable String field)
{
return studentService.getBySort(field);
}
23
@GetMapping("/get/{min}/{max}")
public List<Student> getByBetween(@PathVariable int min,@PathVariable int max) {
return studentService.getByBetween(min, max);
}
2.Model class
@Data
@Entity
public class Employee {
@Id
private int id;
private String Name;
private int Age;
private String Address;
private String Department;
}
3.Service Class
@Service
public class EmployeeService {
@Autowired
public StudentRepo studentRepo;
24
public List<Student> getBySort(String field){
return studentRepo.findAll(Sort.by(Sort.Direction.ASC, field));
}
public List<Student> getByBetween(int minage,int maxage){
return studentRepo.findAllByAgeBetween(minage, maxage);
}
}
4 .Repository Class
@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
@Query("SELECT s FROM Student s WHERE s.Age BETWEEN ?1 AND ?2")
public List<Student> findAllByAgeBetween(int age1,int age2);
}
Output:
25
Result:
The program compiled and executed successfully.
26
Ex.no: 8 Employee Payroll Management System with Spring Boot:
Date: NOT LIKE Queries and RESTful API
Aim:
The aim of this project is to develop a simple payroll service using Spring Boot, which manages employee
data by storing it in a database and providing CRUD operations via RESTful API endpoints.
Algorithm:
1. Set up project structure with folders for Controllers, Models, Services, and Repositories.
2. Define Employee model with necessary attributes.
3. Implement EmployeeRepo interface extending JpaRepository<Employee, Long> for CRUD operations.
4. Implement EmployeeService interface with business logic for CRUD operations.
5. Create ApiController class for RESTful endpoints.
6. Implement API endpoints for adding, retrieving, and filtering employee data.
7. Configure database connection in application.properties.
8. Test endpoints using tools like Postman or unit tests.
9. Run application using 'mvn spring-boot:run' command.
Program:
1.Define controller class
@Autowired
public DonorService donorService;
@PostMapping("/")
public boolean postStudent(@RequestBody Donor donor) {
return donorService.PostData(donor);
}
@PutMapping("/put/{id}")
public Donor putStudent(@RequestBody Donor donor,@PathVariable int id) {
return donorService.putData(id, donor);
}
@GetMapping("/get")
public List<Donor> getAll() {
return donorService.getAll();
}
@GetMapping("/get/id/{id}")
public Donor getById(@PathVariable int id) {
return donorService.getById(id);
}
@DeleteMapping("/del/{id}")
public void deleteById(@PathVariable int id) {
27
donorService.delData(id);
}
@GetMapping("/get/field/{field}")
public List<Donor> getBySort(@PathVariable String field) {
return donorService.getBySort(field);
}
@GetMapping("/get/{min}/{max}")
public List<Donor> getByBetween(@PathVariable int min,@PathVariable int max) {
return donorService.getByBetween(min, max);
}
2.Model class
@Data
@Entity
public class Employee {
@ Id
private int id;
private String Name;
private int Age;
private String Address;
private String Bloodgroup;
}
3.Service Class
@Autowired
public DonorRepo donorRepo;
28
if (getById(id) != null) {
return donorRepo.save(donor);
}
return null;
}
4 .Repository Class
@Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer> {
@Query("SELECT d FROM Donor d WHERE d.Age BETWEEN ?1 AND ?2")
public List<Donor> findAllByAgeBetween(int age1,int age2);
}
Output:
29
Result:
The program compiled and executed successfully.
30
Ex.no: 9
Date:
Personal Finance Management System
AIM:
To develop a Spring Boot REST API for managing personal finances, allowing users to track their income,
expenses, and budget goals. Implement a one-to-many relationship between users and transactions,
enabling users to view their transaction history and financial summaries.
Algorithm:
1. Define User entity with attributes: id, username, email.
2. Define Transaction entity with attributes: id, type, amount, description.
3. Implement one-to-many mapping between User and Transaction entities.
4. Create UserRepository and TransactionRepository interfaces using Spring Data JPA.
5. Develop FinanceService class to handle business logic.
6. Create FinanceController class to handle API requests.
7. Implement RESTful API endpoints for user and transaction management.
Program:
1. Define User entity:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String email;
@Entity
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String type;
private double amount;
private String description;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
3. Create UserRepository and TransactionRepository interfaces:
31
public interface UserRepository extends JpaRepository<User, Integer> {}
@Service
public class FinanceService {
@Autowired
private UserRepo userRepo;
@Autowired
private TransactionRepo transactionRepo;
if (existingUser.isEmpty()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(userRepo.save(user));
}
32
}
if (existingTransaction.isEmpty()) {
return ResponseEntity.notFound().build();
}
@RestController
@RequestMapping("/api")
public class FinanceController {
@Autowired
private FinanceService financeService;
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
return financeService.createUser(user);
}
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable int id) {
33
return financeService.getUserById(id);
}
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User
user) {
return financeService.updateUser(id, user);
}
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable int id) {
return financeService.deleteUser(id);
}
@PostMapping("/transactions")
public ResponseEntity<Transaction> createTransaction(@RequestBody Transaction
transaction) {
return financeService.createTransaction(transaction);
}
@GetMapping("/transactions/{id}")
public ResponseEntity<Transaction> getTransactionById(@PathVariable int id) {
return financeService.getTransactionById(id);
}
@GetMapping("/transactions/user/{userId}")
public ResponseEntity<List<Transaction>> getTransactionsByUserId(@PathVariable int
userId) {
return financeService.getTransactionsByUserId(userId);
}
@PutMapping("/transactions/{id}")
public ResponseEntity<Transaction> updateTransaction(@PathVariable int id,
@RequestBody Transaction transaction) {
return financeService.updateTransaction(id, transaction);
}
@DeleteMapping("/transactions/{id}")
public ResponseEntity<Void> deleteTransaction(@PathVariable int id) {
financeService.deleteTransaction(id);
return ResponseEntity.noContent().build();
}
}
34
Output:
35
Result:
The program compiled and executed successfully.
36
Ex.no: 10
Date:
Smart Home Automation API with Device Control
AIM:
To create a Spring Boot REST API for smart home automation that allows users to control various IoT
devices in their home. Implement a one-to-many relationship between users and devices, enabling users to
manage multiple devices and perform actions such as turning them on/off or adjusting settings remotely.
Algorithm:
1. Create User entity with attributes: id, name, email.
2. Create Device entity with attributes: id, name, type, status, settings.
3. Implement one-to-many mapping between User and Device entities.
4. Create UserRepository and DeviceRepository interfaces using Spring Data JPA.
5. Develop HomeController class to handle API requests.
6. Implement RESTful API endpoints for user and device management.
Program:
1. Define User entity:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String email;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
37
public interface DeviceRepository extends JpaRepository<Device, Integer> {
List<Device> findByUserId(int userId);
}
package com.practicals.ex_10.controller;
@RestController
@RequestMapping("/api")
public class HomeController {
@Autowired
private UserRepo userRepo;
@Autowired
private DeviceRepo deviceRepo;
// User Endpoints
@PostMapping("/users")
public ResponseEntity<User> createUser(@RequestBody User user) {
return new ResponseEntity<>(userRepo.save(user), HttpStatus.CREATED);
}
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable int id) {
return ResponseEntity.ok(userRepo.findById(id).orElse(null));
}
@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(userRepo.findAll());
}
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(@PathVariable int id, @RequestBody User
user) {
Optional<User> existingUser = userRepo.findById(id);
if (!existingUser.isPresent()) {
return ResponseEntity.notFound().build();
}
38
userRepo.save(updatedUser);
return ResponseEntity.ok(updatedUser);
}
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable int id) {
userRepo.deleteById(id);
return ResponseEntity.noContent().build();
}
// Device Endpoints
@PostMapping("/devices")
public ResponseEntity<Device> createDevice(@RequestBody Device device) {
return new ResponseEntity<>(deviceRepo.save(device), HttpStatus.CREATED);
}
@GetMapping("/devices/{id}")
public ResponseEntity<Device> getDeviceById(@PathVariable int id) {
return ResponseEntity.ok(deviceRepo.findById(id).orElse(null));
}
@GetMapping("/devices")
public ResponseEntity<List<Device>> getAllDevices() {
return ResponseEntity.ok(deviceRepo.findAll());
}
@PutMapping("/devices/{id}")
public ResponseEntity<Device> updateDevice(@PathVariable int id, @RequestBody
Device device) {
Optional<Device> existingDevice = deviceRepo.findById(id);
if (!existingDevice.isPresent()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(updatedDevice);
}
39
@DeleteMapping("/devices/{id}")
public ResponseEntity<Void> deleteDevice(@PathVariable int id) {
deviceRepo.deleteById(id);
return ResponseEntity.noContent().build();
}
@PutMapping("/devices/{id}/toggle")
public ResponseEntity<Device> toggleDeviceStatus(@PathVariable int id) {
Optional<Device> existingDevice = deviceRepo.findById(id);
if (!existingDevice.isPresent()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(updatedDevice);
}
@PutMapping("/devices/{id}/settings")
public ResponseEntity<Device> updateDeviceSettings(@PathVariable int id,
@RequestBody Map<String, String> settings) {
Optional<Device> existingDevice = deviceRepo.findById(id);
if (!existingDevice.isPresent()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(updatedDevice);
}
@GetMapping("/devices/user/{userId}")
public ResponseEntity<List<Device>> getDevicesByUserId(@PathVariable int userId) {
return ResponseEntity.ok(deviceRepo.findByUserId(userId));
}
40
Output:
41
42
Result:
The program compiled and executed successfully.
43
Ex.no: 11
Date:
Library Membership Management API
AIM:
To develop a Spring Boot REST API for managing library memberships. Each library member is
associated with a unique membership card, and each membership card is linked to only one member.
Users should be able to create, retrieve, update, and delete member and membership card information
through the API.
Algorithm:
1. Create Member entity with attributes: id, name, email.
2. Create MembershipCard entity with attributes: id, cardNumber, expirationDate.
3. Implement one-to-one mapping between Member and MembershipCard entities.
4. Create MemberRepository and MembershipCardRepository interfaces using Spring Data JPA.
5. Develop LibraryMembershipController class to handle API requests.
6. Implement RESTful API endpoints for member and membership card management.
Program:
1. Define Member entity:
@Entity
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String email;
@OneToOne
@JoinColumn(name = "member_id")
private Member member;
44
public interface MemberRepository extends JpaRepository<Member, Integer> {
}
@RestController
@RequestMapping("/api")
public class LibraryMembershipController {
@Autowired
private MemberRepo memberRepo;
@Autowired
private MembershipCardRepo membershipCardRepo;
@PostMapping("/members")
public ResponseEntity<Member> createMember(@RequestBody Member member) {
return new ResponseEntity<>(memberRepo.save(member), HttpStatus.CREATED);
}
@GetMapping("/members/{id}")
public ResponseEntity<Member> getMemberById(@PathVariable int id) {
return ResponseEntity.ok(memberRepo.findById(id).orElse(null));
}
@PutMapping("/members/{id}")
public ResponseEntity<Member> updateMember(@PathVariable int id, @RequestBody
Member member) {
Optional<Member> existingMember = memberRepo.findById(id);
if (!existingMember.isPresent()) {
return ResponseEntity.notFound().build();
}
updatedMember.setName(member.getName());
updatedMember.setEmail(member.getEmail());
memberRepo.save(updatedMember);
return ResponseEntity.ok(updatedMember);
}
@DeleteMapping("/members/{id}")
45
public ResponseEntity<Void> deleteMember(@PathVariable int id) {
memberRepo.deleteById(id);
return ResponseEntity.noContent().build();
}
@PostMapping("/membership-cards")
public ResponseEntity<MembershipCard> createMembershipCard(@RequestBody
MembershipCard membershipCard) {
MembershipCard createdCard = membershipCardRepo.save(membershipCard);
return new ResponseEntity<>(createdCard, HttpStatus.CREATED);
}
@GetMapping("/membership-cards/{id}")
public ResponseEntity<MembershipCard> getMembershipCardById(@PathVariable int id)
{
MembershipCard card = membershipCardRepo.findById(id).orElse(null);
return ResponseEntity.ok().body(card);
}
@PutMapping("/membership-cards/{id}")
public ResponseEntity<MembershipCard> updateMembershipCard(@PathVariable int id,
@RequestBody MembershipCard membershipCard) {
Optional<MembershipCard> existingCard = membershipCardRepo.findById(id);
if (!existingCard.isPresent()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(updatedCard);
}
@DeleteMapping("/membership-cards/{id}")
public ResponseEntity<Void> deleteMembershipCard(@PathVariable int id) {
membershipCardRepo.deleteById(id);
return ResponseEntity.noContent().build();
}
46
Output:
47
Result:
The program compiled and executed successfully.
48
Ex.no: 12
Date:
Asset Tracking System with Ownership Details
AIM:
To develop a Spring Boot REST API for managing assets and tracking their ownership
details. Implement a bidirectional one-to-one relationship between assets and their
respective owners, enabling users to view asset information along with the details of the
owner and vice versa.
Algorithm:
1. 1.Define owner entity with attributes id,name,email,address.
2. 2.Define asset entity with attributes id,name,description,value.
3. 3.Implement one to one relation between owner and asset.
4. 4.create OwnerRepository and AssetRepository interfaces.
5. 5.Develop AssetService for business logics.
6. 6.create AssetController to handle API requests.
Program:
1. Define owner entity:
@Entity
@Setter
@Getter
@NoArgsConstructor
public class Owner {
@Id
private int id;
private String name;
private String email;
private String address;
@JsonBackReference
@OneToOne(mappedBy = "owner",cascade = CascadeType.ALL)
private Asset asset;
49
@JsonManagedReference
@OneToOne(cascade = CascadeType.ALL)
private Owner owner;
}
@Repository
public interface OwnerRepository extends JpaRepository<Owner,Integer>{
}
@Autowired
private OwnerRepository ownerRepository;
50
public boolean saveOwner(Owner owner) {
try {
ownerRepository.save(owner);
} catch(Exception e) {
return false;
}
return true;
}
@PostMapping("/assets")
public ResponseEntity<Asset> postMethodName(@RequestBody Asset asset) {
if(assetService.saveAsset(asset)) {
return new ResponseEntity<>(asset,HttpStatus.CREATED);
}
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/assets/{id}")
public ResponseEntity<Asset> getAsset(@PathVariable("id") int id) {
Asset asset = assetService.getAssetById(id);
if(asset==null) {
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(asset,HttpStatus.OK);
}
51
@PutMapping("/assets/{id}")
public ResponseEntity<Asset> putAsset(@PathVariable int id, @RequestBody Asset asset) {
if(assetService.updateAsset(id,asset) == true) {
return new ResponseEntity<>(asset,HttpStatus.OK);
}
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
@DeleteMapping("/assets/{id}")
public ResponseEntity<Asset> deleteAsset(@PathVariable("id") int id) {
if(assetService.deleteAsset(id)==true) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@PostMapping("/owners")
public ResponseEntity<Owner> postMethod(@RequestBody Owner owner) {
if(assetService.saveOwner(owner)) {
return new ResponseEntity<>(owner,HttpStatus.CREATED);
}
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/owners/{id}")
public ResponseEntity<Owner> getOwner(@PathVariable("id") int id) {
Owner owner = assetService.getOwnerById(id);
if(owner==null) {
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(owner,HttpStatus.OK);
}
@PutMapping("/owners/{id}")
public ResponseEntity<Owner> putAsset(@PathVariable int id, @RequestBody Owner owner) {
if (assetService.updateOwner(id,owner) == true) {
return new ResponseEntity<>(owner,HttpStatus.OK);
}
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
@DeleteMapping("/owners/{id}")
public ResponseEntity<Asset> deleteOwner(@PathVariable("id") int id) {
if(assetService.deleteOwner(id)==true) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
52
Output:
Result:
The program compiled and executed successfully.
53