M
M
MockingAlchemist2021-01-30 14:41:24
Java
MockingAlchemist, 2021-01-30 14:41:24

How to make DTO with data validation in Java Spring?

In general, I was guided by this article - https://habr.com/ru/post/343960/ and several others, but the validation still does not work.

Here is what I did:
1. Controller

import ideaweb.sunny.web.DTO.ProxyDto;
import org.springframework.http.MediaType;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class MainController
{
    @PostMapping("/proxy/add")
    public void saveProxy(@Valid @RequestBody ProxyDto dto) {

        System.out.println(dto.toString());

    }
}


2.DTOs:
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;


public class ProxyDto {

    @NotNull(message = "123")
    @NotEmpty(message = "456")
    private String proxy;
    
}


But if I send a request (json) in which the proxy field is missing, then I get a 200 response, and these objects are printed to the console as if nothing had happened.
Please tell me where I'm wrong.

I send the request like this:
curl -v -X POST localhost:8081/proxy/add -H "Content-type:application
/json" -d "{\"proxy\":\"127.0.0.1\"}"

and expect to see status 400 in response to this:
curl -v -X POST localhost:8081/proxy/add -H "Content-type:application
/json" -d "{\"somethingElse\":\"127.0.0.1\"}"

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2021-01-30
@MockingAlchemist

It seems that you do not have validator libraries in your dependencies, so Boot does not include validation.

O
Orkhan, 2021-01-30
Hasanly @azerphoenix

Hello!
To be honest, the line itself worries me

@NotNull(message = "123")
    @NotEmpty(message = "456")
    private String proxy;

NotEmpty already checks the string for NULL and for emptiness and, accordingly, the annotation @NotNullis not needed.
Try to remove this annotation and check again.

S
sergey, 2021-01-30
kuzmin @sergueik

you had the wrong import instead

import javax.validation.Valid;
@RestController
public class MainController
{
    @PostMapping("/proxy/add")
    public void saveProxy(@Valid @RequestBody ProxyDto dto) {

necessary
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
@RestController
@RequestMapping("/proxy")

public class MainController
{
  @RequestMapping(value = "add", method = RequestMethod.POST)
  public Map<String, Object> addBook(@Validated @RequestBody ProxyDto dto ) {
....
and
import javax.validation.constraints.NotNull;
public class ProxyDto {

  @NotNull(message = "idbn is missing")
  @NotEmpty(message = "idbn is empty")


 private String proxy;

depending on the version of the framework type
{
  "timestamp": 1612029070201,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": [
    {
      "codes": [
        "NotNull.book.isbn",
        "NotNull.isbn",
        "NotNull.java.lang.String",
        "NotNull"
      ],
      "arguments": [
        {
          "codes": [
            "book.isbn",
            "isbn"
          ],
          "arguments": null,
          "defaultMessage": "isbn",
          "code": "isbn"
        }
      ],
      "defaultMessage": "idbn is missing",
      "objectName": "book",
      "field": "isbn",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotNull"
    },
    {
      "codes": [
        "NotEmpty.book.isbn",
        "NotEmpty.isbn",
        "NotEmpty.java.lang.String",
        "NotEmpty"
      ],
      "arguments": [
        {
          "codes": [
            "book.isbn",
            "isbn"
          ],
          "arguments": null,
          "defaultMessage": "isbn",
          "code": "isbn"
        }
      ],
      "defaultMessage": "idbn is empty",
      "objectName": "book",
      "field": "isbn",
      "rejectedValue": null,
      "bindingFailure": false,
      "code": "NotEmpty"
    }
  ],
  "message": "Validation failed for object='book'. Error count: 2",
  "path": "/book/add"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question