What is a REST controller & Write a simple REST controller in Spring boot 3.xx
What is REST controller?
REST stands for REpresentation State Transfer.
A web controller is a logical component that is responsible for navigation of all operations related to a resource.
If you have a ProductController in your application, this ProductController will be responsible for: -
1. Creating new product
2. Updating existing product
3. Deleting a product
4. Getting a product
5. Getting all products
Write Product class
package wealthManager.models;
import java.io.Serializable;
public class Product implements Serializable {
private final String name;
private int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public void setPrice(int price){
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
Write ProductController class
package wealthManager.rest;
import jakarta.annotation.PostConstruct;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wealthManager.models.Product;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/product")
public class ProductController {
private List<Product> productList = new ArrayList<>();
@PostConstruct
public void init() {
productList.add(new Product("iPhone", 1000));
productList.add(new Product("iPad", 500));
productList.add(new Product("Macbook", 2000));
}
@GetMapping
public List<Product> getProducts(){
return productList;
}
@GetMapping("/{name}")
public Product getProduct(@PathVariable("name") String name) {
return productList.stream().filter(product -> product.getName().equals(name)).findFirst().orElse(null);
}
@DeleteMapping("/{name}")
public Product deleteProduct(@PathVariable("name") String name) {
Product product = getProduct(name);
productList.removeIf(allProducts -> allProducts.getName().equals(name));
return product;
}
@PostMapping("/{name}/{price}")
public Product createProduct(@PathVariable("name") String name,
@PathVariable("price") int price) {
Product product = new Product(name, price);
productList.add(product);
return product;
}
@PatchMapping("/{name}/{price}")
public Product updateProduct(@PathVariable("name") String name,
@PathVariable("price") int price) {
Product product = getProduct(name);
product.setPrice(price);
return product;
}
}
Comments
Post a Comment
Share your thoughts here...