0% found this document useful (0 votes)
26 views11 pages

Assignment 7

Uploaded by

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

Assignment 7

Uploaded by

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

ASSIGNMENT 7

1. Role of Dev-Tool Dependency and Example Code


Role of Dev-Tool Dependency
Spring Boot’s spring-boot-devtools dependency helps developers by enabling
auto-restart and live reload during development. Any code changes are picked
up automatically without manually stopping and restarting the application,
thus improving productivity.
Steps to Implement the Web Controller with Auto-Reloading:
1. Add the devtools dependency in pom.xml:
xml
Copy code
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
2. MyController.java:
java
Copy code
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {
@GetMapping("/sayHello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello World");
return "hello";
}
}
3. Create the hello.html template in src/main/resources/templates:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>Response</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
4. Change Response: Update the controller:
java
Copy code
@GetMapping("/sayHello")
public String sayHello(Model model) {
model.addAttribute("message", "Hi World"); // Change response
return "hello";
}
Simply refresh the browser after changing the code to "Hi World" or "This is a
testing response" to see the changes without restarting the application.

2. Difference between @Controller and @RestController


• @Controller: Used to return views (HTML pages).
• @RestController: Combines @Controller and @ResponseBody to return
JSON or other responses directly.
Modified MyController using @RestController:
java
Copy code
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

@GetMapping("/sayHello")
public String sayHello() {
return "Hi World"; // Direct response without a view
}
}
Effect: The response is printed directly in the browser (plain text/JSON).

3. Sending Book Information Using REST API


1. Book.java:
java
Copy code
public class Book {
private int id;
private String name;
private String author;

public Book(int id, String name, String author) {


this.id = id;
this.name = name;
this.author = author;
}

// Getters and setters


}
2. BookController.java:
java
Copy code
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/books")
public class BookController {

@GetMapping("/getBook")
public Book getBook() {
return new Book(1, "JAVA The Complete Reference", "Herbert Schildt");
}
}
3. Fire a GET request using Postman at:
http://localhost:8080/api/books/getBook
Response in JSON:
json
Copy code
{
"id": 1,
"name": "JAVA The Complete Reference",
"author": "Herbert Schildt"
}

4. CRUD Operations with BookService and BookController


1. BookService.java:
java
Copy code
import java.util.ArrayList;
import java.util.List;

public class BookService {


private static final List<Book> books = new ArrayList<>();

static {
books.add(new Book(1, "Book1", "Author1"));
books.add(new Book(2, "Book2", "Author2"));
}

public List<Book> getBooks() {


return books;
}

public void addBook(Book book) {


books.add(book);
}

public void updateBook(int id, Book updatedBook) {


books.stream()
.filter(b -> b.getId() == id)
.findFirst()
.ifPresent(b -> {
b.setName(updatedBook.getName());
b.setAuthor(updatedBook.getAuthor());
});
}

public void deleteBook(int id) {


books.removeIf(b -> b.getId() == id);
}
}
2. BookController.java:
java
Copy code
@RestController
@RequestMapping("/api/books")
public class BookController {

private final BookService bookService = new BookService();

@GetMapping
public List<Book> getBooks() {
return bookService.getBooks();
}

@PostMapping
public void addBook(@RequestBody Book book) {
bookService.addBook(book);
}

@PutMapping("/{id}")
public void updateBook(@PathVariable int id, @RequestBody Book book) {
bookService.updateBook(id, book);
}

@DeleteMapping("/{id}")
public void deleteBook(@PathVariable int id) {
bookService.deleteBook(id);
}
}

5. Spring Boot with Database Integration


1. Employee.java:
java
Copy code
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String address;
private double salary;

// Getters and setters


}
2. EmpRepository.java:
java
Copy code
public interface EmpRepository extends JpaRepository<Employee, Integer> {
}
3. EmployeeController.java:
java
Copy code
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

@Autowired
private EmpRepository repository;

@PostMapping
public Employee createEmployee(@RequestBody Employee employee) {
return repository.save(employee);
}

@GetMapping("/{id}")
public Employee getEmployee(@PathVariable int id) {
return repository.findById(id).orElseThrow(() -> new
RuntimeException("Employee not found"));
}

@PutMapping("/{id}")
public Employee updateEmployee(@PathVariable int id, @RequestBody
Employee updatedEmployee) {
Employee employee = repository.findById(id).orElseThrow();
employee.setName(updatedEmployee.getName());
employee.setAddress(updatedEmployee.getAddress());
employee.setSalary(updatedEmployee.getSalary());
return repository.save(employee);
}
@DeleteMapping("/{id}")
public void deleteEmployee(@PathVariable int id) {
repository.deleteById(id);
}
}

6. One-to-One Mapping for Address


1. Address.java:
java
Copy code
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String street;
private String city;

// Getters and setters


}
2. Modify Employee.java:
java
Copy code
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
7. Handle Missing Employee Error
Modify the EmployeeController:
java
Copy code
@GetMapping("/{id}")
public Employee getEmployee(@PathVariable int id) {
return repository.findById(id)
.orElseThrow(() -> new
ResponseStatusException(HttpStatus.NOT_FOUND, "Employee not found"));
}
HTTP Response for Missing Employee:
json
Copy code
{
"timestamp": "2024-08-01T12:00:00",
"status": 404,
"error": "Not Found",
"message": "Employee not found",
"path": "/api/employees/5"
}
This returns a 404 Not Found response to Postman.

You might also like