AI Hints
Home›Spring Boot Tutorial›Project: The Controller, Validation and Errors and Security
Spring Boot · Lesson 115 of 120

Project: The Controller

The HTTP layer.

⏱ 2 min read▶ Video at 2:33:11🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

The controller is the front door of our API. It turns HTTP requests into service calls, and service results into JSON.

  • The front door
  • Requests → service calls
  • Results → JSON

Reading books

The controller only talks to the service. List takes an optional author parameter. And one reads a single book, by its id. Run it. Searching for Austen returns two books, as JSON. And book one is Dune.

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

    private final BookService service;
    public BookController(BookService service) { this.service = service; }

    @GetMapping
    public List<BookResponse> list(@RequestParam(required = false) String author) {
        return service.search(author);
    }

    @GetMapping("/{id}")
    public BookResponse one(@PathVariable long id) { return service.byId(id); }
}
Output
$ curl localhost:8080/books?author=austen
[
  {"id":7,"title":"Emma","author":"Jane Austen","price":6.99},
  {"id":8,"title":"Persuasion","author":"Jane Austen","price":7.49}
]
$ curl localhost:8080/books/1
{"id":1,"title":"Dune","author":"Frank Herbert","price":9.99}
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}
    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCase(String author);
}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses NewPrice.java
public record NewPrice(@Positive double price) {}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true
Also uses BookService.java
@Service
@Transactional
public class BookService {

    private final BookRepository books;

    public BookService(BookRepository books) { this.books = books; }

    @Transactional(readOnly = true)
    public List<BookResponse> search(String author) {
        List<Book> found = author == null ? books.findAll()
                                          : books.findByAuthorContainingIgnoreCase(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @Transactional(readOnly = true)
    public BookResponse byId(long id) { return BookResponse.from(find(id)); }

    public BookResponse create(CreateBook req) {
        Book saved = books.save(new Book(req.title(), req.author(), req.price()));
        return BookResponse.from(saved);
    }

    public BookResponse changePrice(long id, double price) {
        Book book = find(id);
        book.setPrice(price);
        return BookResponse.from(book);
    }

    public void delete(long id) { books.delete(find(id)); }

    private Book find(long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}
Also uses _curl.sh
curl localhost:8080/books?author=austen
curl localhost:8080/books/1

The writes

POST adds a book, and answers two oh one, created. PUT changes only the price, with its own small record. And DELETE answers two oh four, no content.

BookController.javajava
    ...
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public BookResponse add(@Valid @RequestBody CreateBook req) {
        return service.create(req);
    }

    @PutMapping("/{id}/price")
    public BookResponse price(@PathVariable long id, @Valid @RequestBody NewPrice p) {
        return service.changePrice(id, p.price());
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable long id) { service.delete(id); }
}

Trying the writes

These requests add a book, change a price, and delete a book. Run it. Beloved is added, with id nine. Emma now costs five ninety nine. The delete answers two oh four. And book eight is gone, so reading it gives four oh four.

requests.shbash
curl --json '{"title":"Beloved","author":"Toni Morrison","price":9.5}' localhost:8080/books
curl -X PUT --json '{"price":5.99}' localhost:8080/books/7/price
curl -i -X DELETE localhost:8080/books/8 | head -1
curl -i localhost:8080/books/8 | head -1
Output
$ curl --json '{"title":"Beloved","author":"Toni Morrison","price":9.5}'
localhost:8080/books
{"id":9,"title":"Beloved","author":"Toni Morrison","price":9.5}
$ curl -X PUT --json '{"price":5.99}' localhost:8080/books/7/price
{"id":7,"title":"Emma","author":"Jane Austen","price":5.99}
$ curl -i -X DELETE localhost:8080/books/8 | head -1
HTTP/1.1 204
$ curl -i localhost:8080/books/8 | head -1
HTTP/1.1 404
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}
    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCase(String author);
}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses NewPrice.java
public record NewPrice(@Positive double price) {}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true
Also uses BookService.java
@Service
@Transactional
public class BookService {

    private final BookRepository books;

    public BookService(BookRepository books) { this.books = books; }

    @Transactional(readOnly = true)
    public List<BookResponse> search(String author) {
        List<Book> found = author == null ? books.findAll()
                                          : books.findByAuthorContainingIgnoreCase(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @Transactional(readOnly = true)
    public BookResponse byId(long id) { return BookResponse.from(find(id)); }

    public BookResponse create(CreateBook req) {
        Book saved = books.save(new Book(req.title(), req.author(), req.price()));
        return BookResponse.from(saved);
    }

    public BookResponse changePrice(long id, double price) {
        Book book = find(id);
        book.setPrice(price);
        return BookResponse.from(book);
    }

    public void delete(long id) { books.delete(find(id)); }

    private Book find(long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}
Also uses BookController.java
@RestController
@RequestMapping("/books")
public class BookController {

    private final BookService service;
    public BookController(BookService service) { this.service = service; }

    @GetMapping
    public List<BookResponse> list(@RequestParam(required = false) String author) {
        return service.search(author);
    }

    @GetMapping("/{id}")
    public BookResponse one(@PathVariable long id) { return service.byId(id); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public BookResponse add(@Valid @RequestBody CreateBook req) {
        return service.create(req);
    }

    @PutMapping("/{id}/price")
    public BookResponse price(@PathVariable long id, @Valid @RequestBody NewPrice p) {
        return service.changePrice(id, p.price());
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable long id) { service.delete(id); }
}
Also uses _curl.sh
curl --json '{"title":"Beloved","author":"Toni Morrison","price":9.5}' localhost:8080/books
curl -X PUT --json '{"price":5.99}' localhost:8080/books/7/price
curl -i -X DELETE localhost:8080/books/8 | head -1
curl -i localhost:8080/books/8 | head -1

Summary

The controller maps five endpoints to service calls, with the right status codes. Next, validation, and clean errors.

Key takeaways
  • @RequestParam(required = false)
  • 201 Created
  • 204 No Content
Next up: Project: Validation and Errors — clean answers for bad input