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

Spring is not scary. Controlling your REST

Published in the Random EN group
CONTENTS OF THE CYCLE OF ARTICLES Reusing someone else's work is a sacred matter 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: how HTTP works, what GET, POST, PUT are, response statuses, MVC, read separately about JSON and serialization . It will be useful to implement the proposed example with servlets, this will help you love spring-boot with all your heart. The example spring-boot application from this series is quite simple, but it will help you understand the essence of MVC. Below there will be a link to a more interesting project. To become familiar with REST and its use in Spring, read these three articles . In the first article you will 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’s useful to look and compare), implement it. Pay attention to the place where they talk about HttpStatus, ResponseEntity <?> (if <?> is confusing, then read Chapter 13. Generalizations from "Java. A Beginner's Guide", Herbert Shildt), in the same article read about POSTMAN ( additionally short video about it ) install POSTMAN, you don’t need all the features, see how to create various queries. There are ternary operators in the example, refresh 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;
   }
}
You should 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 figure out that a bean needs to be implemented 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 is there an interface ClientService and public class ClientServiceImpl - this is correct practice, later, we will talk about why it is needed and we will use it. That's all with the articles. Before reading, let's write. As they say: “Not a day without a code!” As a starting point, let's create a simple GET request. Last time we wrote an application for vegetable speculation, git clone https://FromJava@bitbucket.org/FromJava/speculation.git git clone git@bitbucket.org:FromJava/speculation.git Open the application, and in the ru.java package. rush we will create a controllers package (controllers from the MVC pattern will be located here). Create a class public class ProductController
@RestController
@RequestMapping("/speculation")
public class ProductController {

}
The @RestController annotation indicates to Spring that this is a rest controller. @RequestMapping - All controller methods will receive requests with a URI that will begin 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 launch the project, type in the browser line: http://localhost:8080/speculation/simple We receive the answer: Easy GET request A few explanations: 1. We created a class that marked @RestController as a controller, indicated 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 (Light GET request), marked it with the @GetMapping annotation (that this method is specifically for GET requests) and indicated the path to the method ("/simple") 3. We 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 "Easy GET requester" method worked for this request; } 5. The result of the method was returned to the browser in the form of the string “Easy GET request”. Well, it's a start! The most fascinating articles 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 needs to be understood, “eat the elephant in parts.” For training (after mastering the material): Complete the speculation application controller . Create methods: 1) Search for a product by id Use the productService.findById() method; Example output
{
        "id": 1,
        "name": "Картофель",
        "purchasePrice": 20,
        "packaging": null,
        "salePrice": null
 }
After implementing the remaining controller methods, think: “Why are the last two fields null? What needs to be done so that there are some values ​​there?” 2) View all products on the storefront: To search for all products, use the productService.findAll() method; To fill in the packaging and markup fields, use productService.pack(); productService.makeMoney(); The output should contain a JSON array listing products, 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 purchase price) Use: productService.save(); The method should return the corresponding Http status. 4) Deleting a product by id To do this, first implement in ProductService a method containing productRepository.deleteById(); And then, use it in the controller. The controller method must return the appropriate Http status. 5) Changes in product by id (change in the wholesale price of the product and product name) 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 (json_object). This can be done something like this:
найденный_товар = productService.findById(id);
найденный_товар.setName(an object_json.getName);
найденный_товар.setPurchasePrice(an object_json.getPurchasePrice);
After this, the changed product must be saved productService.save(found_product); The method should return the corresponding Http status. If you have problems with this method, you can google “put request java”, no one has canceled the Internet yet) Working 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