How to pass numbers between "{ }" in the url?

Asked

Viewed 163 times

4

I’m having a dumb doubt in some exercises using Spring Boot.

The exercise requires that I receive the list of numbers as follows:

http://localhost:8080/listaDecrescente?lista={12,55,70,22}

And return the answer:

HTTP 200 OK {70,55,22,12}

Ok, the logic is simple. My question is: how do I pass the parameters between the keys, like the above example?

Like I’m doing:

    @RequestMapping(value = {"/listaDecrescente"})
    public int[] listaDecrescente(@RequestParam int[] lista){
        //lógica aqui...
        return lista;
}

The only way my URL accepts receiving data:

http://localhost:8080/api/listaDecrescente?lista=12,55,70,22
  • Hello, I’m new in spring... but try List<Integer>. Your @Requestmapping is strange, so those {} on the outside? should be "/{list}". In the last case you will have to read as String and do the parse in the same hand... But it must have better shape. Still, I give a star to those who link me where in the spring documentation it lists which are the mappings between java types and "parsers" of spring controller. Because, for example, if you pass a DTO on a body it parses and validates automatically with the validation annotations, where it is documented?

2 answers

1

I found nothing in the Spring documentation that supports this format using keys (or brackets):

lista={12,55,70,22}

However, Spring accepts:

lista=12,55,70,22

Or:

lista=12&lista=55&lista=70&lista=22

Using, respectively:

public String metodo(@RequestParam String[] lista){

}

And:

public String metodo(@RequestParam List<String> lista){

}

In your case, then, I believe the option is to receive the information as a String even and read the information to turn it into a array. Something like:

public String metodo(@RequestParam String lista){
    List<String> ids = lista
        .replace("{","") // remover o {
        .replace("}","") // remover o }
        .split(",");
}

It won’t look elegant, but I don’t see any other way.

0

Hello, if you really need the method to be GET, then the shipping way would be the one you talked about:

listaDecrescente?lista=12,55,70,22

and if they had other parameters you would separate by &...

listaDecrescente?lista=12,55,70,22&nome=nome passado&idade=20

However I believe that it would be better if you change the method of sending to POST, so it would be easier for you to pass the list and other parameters that exist.

@RequestMapping(value = "/detalha", method = RequestMethod.POST)

or

@PostMapping(value = "/listaDecrescente")

I hope I’ve helped!

Browser other questions tagged

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