How to check if an Integer type parameter received in Spring is empty?

Asked

Viewed 438 times

0

I have a method that will receive several parameters. But the parameters are set to required = false because I don’t want it to be mandatory for them to be informed and I also didn’t enter a default value because they should only receive some kind of value if the user passes such value. That is, if the user informs the parameter, he must assign a value to it. If he does not inform the parameter, there is no problem. It just can’t enter a parameter without assigning value to it.

In Postman, when I pass the URL to enter my method in Java informing the parameter and I do not assign a value to it (for example, when I leave the equal sign empty or do not inform the equal sign:)

http://localhost:8181/project/status? code=

It identifies as if the parameter was not passed instead of identifying that the parameter is empty even though I have written the following code:

inserir a descrição da imagem aqui

(That is, if the given parameter is not null but empty, then it will return error 400 instead of entering the method that performs the desired routine.)

I can’t change the type of parameter in the line of the @RequestParam(value = "codigoEstado", required = false) Integer codigoEstado because otherwise I would have to change a good part of my project.

Does anyone know what I can do to check if an Integer is empty?

  • 1

    Always put the code as text and not as an image. What is the problem of interpreting "parameter value was not passed" as "parameter was not passed"?

  • Man I don’t know if this is gonna be much help but you can build your if depending on the value that the System.Out.Println(codigoEstado) returns. What in your case will probably be a NullPointerException or 0.

  • Are you using Java 8? If so, maybe the java.util.Optional can help, instead of using required = false. Something like this: @RequestParam("codigoEstado") Optional<Integer> codigoEstado

1 answer

0

I think there’s even a better way to do this, but it’s a solution: I think it’s possible for you to take the object HttpServletRequest and call the method getParameterMap(), and check if the parameter is in Map and if its value is null. Something like this:

@RequestMapping(value = "/", method = RequestMethod.GET)
public ResponseEntity buscar(
        @RequestParam(value = "codigoEstado", required = false) Integer codigoEstado 
        HttpServletRequest request) {
     Map<String, String> parametros = request.getParameterMap();
     if (parametros.contains("codigoEstado") && parametros.get("codigoEstado") == null) { 
          // erro 400
     }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.