JavaRush /Java Blog /Random EN /Spring is not scary. Controlling our REST
Павел
Level 11

Spring is not scary. Controlling our REST

Published in the Random EN group
CONTENTS OF THE ARTICLE CYCLE Reusing someone else's work is a sacred thing for any developer 😌 To move on, you need to understand the basics of a computer network, here is a series of articles . Pay attention to the main points: the principle of HTTP, what is GET, POST, PUT, response statuses, MVC, read about JSON and serialization separately . It will be useful to implement the proposed example with servlets, this will help you fall in love with spring-boot with all your heart. The sample spring-boot application from this series is quite simple, but it will help you understand the essence of MVC. Below is a link to a more interesting project. For an introduction to REST and how to use it in Spring, read these three articles . In the first article, read what REST is. The second article talks about requests and responses, be sure to read and take note of Comrade Fidel's comment. The third article will offer a practical example of implementation in Spring, the approach to creating an application is not much different (it is useful to look and compare), implement it. Pay attention to the place where it says about HttpStatus, ResponseEntity <?> (if <?> introduces into a stupor, then read chapter 13. Generalizations from "Java. Beginner's Guide", Herbert Schildt), in the same article read about POSTMAN ( more short video about it ) install POSTMAN, you don't need all the features, see how to create various requests. The example contains ternary operatorsRefresh your memory if you forgot. Pay attention to how the example article implements bean injection using @Autowired
@RestController
public class ClientController {

   private final ClientService clientService;

   @Autowired
   public ClientController(ClientService clientService) {
       this.clientService = clientService;
   }
}
Be aware that starting with Spring 4.3, the @Autowired annotation can be omitted if the class has only one constructor. The framework itself will guess that it is necessary to implement a bean in the constructor. You can read more in this source . And if you are careful, then you should have a question about the structure of the service package , namely: why are there interface ClientService and public class ClientServiceImpl - this is the correct practice, later, we will talk about why it is needed and we will use it. Everything with articles. Before reading, let's write. As the saying goes: "Not a day without a code!" For starters, let's create a simple GET request. Last time we wrote an application for speculation in vegetables, git clone https://FromJava@bitbucket.org/FromJava/speculation.git git clone git@bitbucket.org:FromJava/speculation.git MVC pattern). Create a class public class ProductController
@RestController
@RequestMapping("/speculation")
public class ProductController {

}
The @RestController annotation tells Spring that this is a rest controller. @RequestMapping - All controller methods will receive requests with a URI that starts with the string specified in the annotation brackets ("/speculation"). We write the following method in the class
@GetMapping("/simple")
public String simple(){
    return "Легкий GET requestик";
}
We start the project, in the browser we type: http://localhost:8080/speculation/simple We get the answer: Easy GET request A few explanations: 1. We created a class that marked @RestController as a controller, specified the path to it @RequestMapping ("/ speculation") - this annotation is optional, without it the path will start with "/". 2. We created a method that, when executed, returns a string (Easy GET request), marked it with the @GetMapping annotation (that this method is for GET requests) and indicated the path to the method ("/simple") 3. Launched the project (server) on port 8080, and made a GET request to the address: server/controller/method (http://localhost:8080/speculation/simple) 4. The public String simple(){ return " 5. The result of the method was returned to the browser as a string "Easy GET request". Well, it's a start! Exciting stories await you. Mastering the material proposed above will take more than one day, there is no need to rush here, this topic is very important and you need to understand it, “eat the elephant in parts”. For practice (after mastering the material): Complete the application controller with speculation . Create methods: 1) Search for a product by id Use the productService.findById() method; Output example
{
        "id": 1,
        "name": "Картофель",
        "purchasePrice": 20,
        "packaging": null,
        "salePrice": null
 }
After implementing the rest of the controller methods, think: "Why are the last two fields null? What needs to be done so that there would be some values ​​there?" 2) Viewing all products in the storefront: To find all products, use the productService.findAll() method; To fill in the packaging and markup fields, use productService.pack(); productService.makeMoney(); the output should be an array of JSONs with a list of goods, an example:
[
    {
        "id": 1,
        "name": "Картофель",
        "purchasePrice": 20,
        "packaging": "Упаковано в лучшем виде",
        "salePrice": 100
    },
    {
        "id": 2,
        "name": "Морковь",
        "purchasePrice": 14,
        "packaging": "Упаковано в лучшем виде",
        "salePrice": 70
    }
]
3) Adding a new product to the database (add product: cabbage and wholesale price) Use: productService.save(); The method should return the appropriate Http status. 4) Deleting a product by id To do this, first implement a method in ProductService that contains productRepository.deleteById(); And then, use it in the controller. The controller method should return the appropriate Http status. 5) Changes of goods by id (change of the wholesale price of the goods and the name of the goods) This operation will be more complicated than the previous ones. First we need to find the product we want to change by id Use productService.findById(); Then, in the found product (object), replace the value of the fields with the value of the fields of the object received in the body of the Put request (object_json) This can be done like this:
найденный_товар = productService.findById(id);
найденный_товар.setName(an object_json.getName);
найденный_товар.setPurchasePrice(an object_json.getPurchasePrice);
After that, the modified product must be saved productService.save(found_product); The method should return the appropriate Http status. If there are problems with this method, then you can google “put request java”, no one has canceled the Internet yet) Work with controllers does not end there, there are still many topics ahead ...
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION