JavaRush /Java Blog /Random EN /Spring is not scary. Cookies & Headers
Павел
Level 11

Spring is not scary. Cookies & Headers

Published in the Random EN group
CONTENTS OF THE CYCLE OF ARTICLES Repetition is the mother of learning! Therefore, based on previous articles, let's create a new web spring-boot project: MobilePhonePayment Connect h2, Lombok. Create an entity layer: BalancePhoneEntity Integer id; Integer numberPhone; String nameCustomer; Integer balance; Create a layer of services with methods: - Search for all records in the database - Search for a record by id - Search for a record by phone number - Search for a record by user name (should return a sheet of records, the names may be the same)
public List<BalanceEntity> findByNameCustomer(String nameCustomer){
    return balanceRepository.findAllByNameCustomer(nameCustomer);
}
- Adding a record to the database - Removing a record from the database by id - Business method: Top up phone balance - the method must take a phone number, an amount (Integer type) and increase the balance of the corresponding number by the specified amount.
public void addingMoneyToBalance(Integer phoneNumber, Integer sum) {
    BalanceDto byPhoneNumber = findByPhoneNumber(phoneNumber);
    byPhoneNumber.setBalance(byPhoneNumber.getBalance() + sum);
    save(byPhoneNumber);//метод save() – добавление, реализован в сервисе
}
Don't forget to implement mapping from DTO to Entity and back. Dto will be similar to Entity: BalancePhoneDto Integer id; Integer numberPhone; String nameCustomer; Integer balance; Create a DTO layer, create the InitiateUtils class and fill the database with data: id 1, numberPhone 555000, balance 100, customer Ivan id 2, numberPhone 444000, balance 250, customer Marya id 3, numberPhone 111000, balance 60, customer Ivan Create a rest controller, but don't rush to fill it with methods. If you follow the previous article, then the method for displaying all records should have turned out something like this (I recommend now looking in the comments to the article - specifically at the comment by Vasily Babin):
//поиск записи по id - старая version
@GetMapping(value = "/find-phone/{id}")
public ResponseEntity<BalanceDto> findPhone(@PathVariable Integer id) {
    BalanceDto balanceDto = balanceService.findById(id);
    return balanceDto != null
            ? new ResponseEntity<>(balanceDto, HttpStatus.OK)
            : new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
There is another way to use ResponseEntity, without using a constructor. We will continue to use it. ResponseEntity exposes two nested builder interfaces: HeadersBuilder and its subinterface, BodyBuilder. Therefore, we can access their capabilities through ResponseEntity's static methods. You can read more in this article . The rest controller methods can be implemented as follows: 1) Displaying a record by id
//поиск записи по id
@GetMapping(value = "/find-number-phoneById/{id}")
public ResponseEntity<?> findNumberPhoneById(@PathVariable Integer id) {
    BalanceDto balanceDto = balanceService.findById(id);
    return balanceDto != null
            ? ResponseEntity.ok(balanceDto)
            : ResponseEntity.ok().body(HttpStatus.NOT_FOUND);
}
We test in Postman (We talked about it in the previous article, here is another small guide on this program ). We launch, select the GET request type, write in the URL line: http://localhost:8080/find-number-phoneById/1 – we passed the id parameter in the query line, in the output we will receive an entry with id equal to 1. After adding the new code, don’t forget to restart the project😇 2) Display records by name
//поиск записи по имени пользователя
@GetMapping(value = "/find-number-phoneByName/{name}")
public ResponseEntity<?> findNumberPhone(@PathVariable String name) {
    List<BalanceDto> balanceDto = balanceService.findByNameCustomer(name);
    return balanceDto != null &&  !balanceDto.isEmpty()
            ? ResponseEntity.ok(balanceDto)
            : ResponseEntity.ok().body(HttpStatus.NOT_FOUND);
}
Let's create a new request, select the GET request type, write in the URL line: http://localhost:8080/ find-number-phoneByName/Ivan - we passed the name parameter in the query line, and in the output we will get a list of records with nameCustomer equal to Ivan. Perhaps in the output you will get something similar to this: %D1%8D%D1%82%D0%BE%20%D0%BD%D0%B5%20%D0%BE%D1%88%D0%B8%D0% B1%D0%BA%D0%B0 This is not an error - these are features of request encoding, read about it . And here it is written how to configure Postman so that this does not happen. 3) Output of all records:
//поиск всех записей
@GetMapping(value = "/findAll")
public ResponseEntity<?> findAll() {
    List<BalanceDto> balanceDto = balanceService.findAll();
    return balanceDto != null &&  !balanceDto.isEmpty()
            ? ResponseEntity.ok(balanceDto)
            : ResponseEntity.ok().body(HttpStatus.NOT_FOUND);
}
We create a new request, select the GET request type, write in the URL line: http://localhost:8080/findAll - we do not pass any parameters here. 4) Adding a new entry:
//добавление новой записи
@PostMapping(value = "/entry")
public ResponseEntity<?> entryNumber(@RequestBody BalanceDto dto){
    balanceService.save(dto);
    return ResponseEntity.ok().body(HttpStatus.CREATED);
}
We create a new request, select the POST request type, and write in the URL line: http://localhost:8080/entry. In this request we need to pass an object in JSON format. In the request window, go to the Body tab, set the flag to raw, click the arrow next to Text and select JSON. Copy the following JSON into the window:
{
        "numberPhone": 767676,
        "nameCustomer": "Sasha",
        "balance": 100
}
When we click execute the request, the response status is CREATED. Now query findAll again and make sure a new entry appears. 5) Deleting an entry by id
//удаление записи по id
@DeleteMapping(value = "/delete-phoneById/{id}")
public ResponseEntity<?> delete(@PathVariable Integer id) {
    balanceService.delete(id);
    return ResponseEntity.ok().body(HttpStatus.OK);
}
We create a new request, select the DELETE request type, write in the URL line: http://localhost:8080/delete-phoneById/4 – we passed the id parameter in the request line, We get the OK status in the output. Now make another request to findAll and make sure that Sasha is missing. 6) Changing the number by id
//изменение номера телефона по id
@PutMapping(value = "/change")
public ResponseEntity<?> changeNumberPhone(
//можно добавлять несколько параметров в request
        @RequestParam(value = "id") Integer id, //добавor один параметр
        @RequestParam(value = "phoneNumber") Integer phoneNumber) //добавor второй параметр
 {
    BalanceDto byId = balanceService.findById(id);
    byId.setNumberPhone(phoneNumber);
    balanceService.save(byId);
    return ResponseEntity.ok().body(HttpStatus.OK);
}
We create a new request, select the PUT request type, and write in the URL line: http://localhost:8080/change. There are several parameters in this request, and as you can see, we do not pass them in the query line as before. The @RequestParam annotation is used for parameters in a method. To transfer parameters via Postman, you need to go to the Params tab in the request window, indicate the name of the parameter (id) in the Key column, and indicate the value (1) in the Value column. We do the same with the second parameter, Key = phoneNumber, Value = 888000. Pay attention to the query string, Postman changed it to pass the parameters correctly. The output will show the status OK. Now query findAll again and make sure that the phone number for the first entry has changed. 7) Top up your phone balance
@PutMapping(value = "/add")
public ResponseEntity<?> addingMoney(
        //можно добавлять несколько параемров в request
        @RequestParam(value = "phoneNumber") Integer phoneNumber,//добавor один параметр
        @RequestParam(value = "sum") Integer sum) //добавor второй параметр
{
    balanceService.addingMoneyToBalance(phoneNumber, sum);
    return ResponseEntity.ok().body(HttpStatus.OK);
}
We create a new request, select the PUT request type, and write in the URL line: http://localhost:8080/add. We set the phoneNumber value to 888000, sum to 130. The output will show the OK status. Now run the findAll request again and make sure that the balance of the first record has changed. 8) PUT through the request body - it is preferable to do this so as not to open the transmitted data
@PutMapping(value = "/add")
public ResponseEntity<?> addingMoney(@RequestBody BalanceDto dto){
    balanceService.addingMoneyToBalance(dto.getPhoneNumber, dto.getSum);
    return ResponseEntity.ok().body(HttpStatus.OK);
}
We send JSON
{
        "numberPhone": 888000,
       //  "nameCustomer" можно вообще не указывать
        "balance": 130
}
Finally we move on to Cookie. What is Cookie ? Simply put: Cookies store data received once by the browser from an application, which can then be used repeatedly on the site. You need to know two basic things: how to write and how to read a Cookie. How to write: The entire Spring Web MVC is implemented on top of the Servlet API, which is built around two objects - the request from the client is wrapped in an HttpSerlvetRequest, and the response is generated from the HttpServletResponse filled with your code. By having access to these objects, you have full control over the entire HTTP session. Spring web allows you to access these objects directly. Usually Cookie, let's create a method in the controller
//записать куки
 @GetMapping(value = "/set-cookie")
public ResponseEntity<?> setCookie(HttpServletResponse response) throws IOException {
     Cookie cookie = new Cookie("data", "Come_to_the_dark_side");//создаем an object Cookie,
     //в конструкторе указываем значения для name и value
     cookie.setPath("/");//устанавливаем путь
     cookie.setMaxAge(86400);//здесь устанавливается время жизни куки
     response.addCookie(cookie);//добавляем Cookie в request
     response.setContentType("text/plain");//устанавливаем контекст
     return ResponseEntity.ok().body(HttpStatus.OK);//получилось How бы два раза статус ответа установor, выбирайте Howой вариант лучше
 }
Let's make a GET request in Postman at the address: http://localhost:8080/set-cookie and the output will be OK. Above the window, find the inscription Cookie(1), by clicking on it you will see the Cookies that we sent. Name: data, value: Come_to_the_dark_side. Information on the main features of the Cookie class in java. How to read: Even easier to read
//прочитать куки
@GetMapping(value = "/get-cookie")
public ResponseEntity<?> readCookie(@CookieValue(value = "data") String data) {
    return ResponseEntity.ok().body(data);
}
In @CookieValue we indicate the name of the Cookie whose value we will read, and display the read value in the response. Come_to_the_dark_side Now the finest hour has come Header ( headers , don’t look at the article about PHP, it’s quite useful to read): First, let’s see how you can read the headers:
//прочитать заголовки
@GetMapping(value = "/get-headers")
public ResponseEntity<?> getHeaders(@RequestHeader Map<String, String> headers){//представляет заголовки ввиде мапы,
    //где ключ это наименование заголовка, а meaning мапы - это meaning заголовка
    return ResponseEntity.ok(headers);
}
The main work is done by @RequestHeader Map<String, String> , it represents headers in the form of a map, where the key is the name of the header, and the value of the map is the value of the header. It is more interesting to test this method using a browser, open the browser, type http://localhost:8080/get-headers in the search bar, and as a result we get an extensive list of headers. Google each heading to understand why they are needed. Wikipedia also offers a list of titles. “If someone read something, then someone wrote it down” is an old programming saying. Let's write down the title
//записать заголовок
@GetMapping(value = "/set-header")
public ResponseEntity<?> setHeader(){
    return ResponseEntity.ok().header("name-header","value-header").body(HttpStatus.OK);
}
Here we have used a special header method of the ResponseEntity class . Where "name-header" is the name of the header, and "value-header" is the value of the header. There are other options for working with headers
//еще варианты работы с заголовками
@GetMapping(value = "/set-headers")
public ResponseEntity<?> setHeaders() {
    HttpHeaders httpHeaders = new HttpHeaders();//создаем an object
    //который имплементирует мапу MultiValueMap<String, String>
    //наполняем ее парами ключ-meaning
    //можно наполнить своими заголовками через метод add
    httpHeaders.add("customer-header", "value-header1");
    //HttpHeaders так же предлагает большой выбор стандартных заголовков
    //Посмотрите на них набрав в IDEA HttpHeaders.
    httpHeaders.add(HttpHeaders.FROM, "russia");
    //можно изменить существующий заголовок, вызвав для него сет-метод
    httpHeaders.setDate(0);
    //or получить meaning конкретного заголовка
    Long date = httpHeaders.getDate();
    System.out.println(date);
    return ResponseEntity
            .ok().headers(httpHeaders)//здесь метод принимающий MultiValueMap<String, String>
            .body(HttpStatus.OK);
}
Here we use another method of the ResponseEntity class, which takes a value of type MultiValueMap<String, String> . It will also be more informative to check how it works in the browser. We go to the address http://localhost:8080/set-headers, we receive a response that the status is OK. If you are great and use Google Chrome, then press the key combination Ctrl + Shift + I and go to “Developer Tools”, then look for the Network tab in the top panel , by clicking it look for the entry: set-headers (if it’s not there, refresh the page) click on it and in the window that opens, select the Headers tab and in ResponseHeaders we see our headers. To get acquainted with the headlines, that's enough for now. Now read: Studying ResponseEntity<!--?--> and getting rid of it in Spring controllers With that, let me take my leave 🤓, see you again...
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION