Assignment 7
Assignment 7
@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.
@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).
@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"
}
static {
books.add(new Book(1, "Book1", "Author1"));
books.add(new Book(2, "Book2", "Author2"));
}
@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);
}
}
@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);
}
}