Thalys Menezes
Thalys Menezes

Reputation: 371

Select2 search term is not being sent to my controller endpoint

I have a select2 (which uses AJAX request to fetch data from remote source, in my case a SpringBoot API). I managed to fetch the data I wanted. However, I'm having trouble to receive in my endpoint the search term, so I can filter the results based on what the user types:

Right below is my code, both AJAX request with select2 and my SpringBoot endpoint with the corresponding function.

$(".select2-single").select2({
     ajax: {
        url: 'http://localhost:8080/credenciamento/busca-procedimentos/',
        dataType: 'json',
        delay: 500,
        data: function (params) {
           console.log(params.term);
           return {
                q: params.term, // search term
           };
        },
        processResults: function (response) {
            var procedures = [];
            for (let i = 0; i < response.length; i++) {
                procedures.push({
                    id: response[i].id, 
                    text: response[i].descricao
                })
            }
            return { results: procedures }
        },
        cache: true,
    },
});

And here, my Java function:

@GetMapping(path = "/credenciamento/busca-procedimentos/")
@ResponseBody
public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required = false) String query) {
    System.out.println(query);

    List<Procedimento> procedimentos = procedimentoService.findAll();
    int size = procedimentos.size();

    if (StringUtils.isEmpty(query)) {
        return procedimentos.subList(0, size);
    }

    Procedimento[] procedimentosArray = new Procedimento[size];
    procedimentosArray = (Procedimento[]) procedimentos.toArray();

    return (List<Procedimento>) Arrays.stream(procedimentosArray)
    .filter(procedimento -> 
            procedimento.getDescricao().toLowerCase().contains(query)
    ).limit(2);
}

PS: everytime the function is executed, my system.out.println result is null. I have tried changing from @PathVariable to @RequestParam, but it throws an exception, saying that no parameter was received from the request, and I have tried changing the route to '/credenciamento/busca-procedimento/{query}' but everytime query is null, and in this case the function doesn't even get executed, since there's no query in the request.

Upvotes: 1

Views: 900

Answers (3)

Thalys Menezes
Thalys Menezes

Reputation: 371

I figured it out what was the problem. It wasn't because of my request or anything related to select2. The problem was the way I was handling the filtering. I was trying to follow a tutorial, however it was with an array. Since in my Case I needed a list, I tried to adapt it but with no success. I just removed all that filtering logic and filtered manually, iterating over my list and adding in my return only the procedures which had in their description the query string. PS: There's no need to @PathVariable, the correct way is with @RequestParam and the route should be the same way. With no /{q} in the end.

Upvotes: 0

Abhijeet Saxena
Abhijeet Saxena

Reputation: 41

The way you have used path variable is wrong. First of all path variables are a part of url formed. So your get mapping url becomes @GetMapping(path = "/credenciamento/busca-procedimentos/{q}").

The second mistake that your making is in your AJAX request. When you are using path variable, your url in the ajax request should contain the query string. So effectively your url becomes - url:'http://localhost:8080/credenciamento/busca-procedimentos/queryString'

So you can compare the two urls and they should match exactly. Your /{q} in spring request mapping refers to /queryString in AJAX request url.

For more you can visit

https://www.journaldev.com/3358/spring-requestmapping-requestparam-pathvariable-example

This is the proper way of using path variables. Make these two changes and it should work.

Upvotes: 1

Andrey Rosa
Andrey Rosa

Reputation: 91

Here's have exemple to use PathVariable Spring mvc @PathVariable.

  1. In Your code was missing the "q" at the end of the url
    @GetMapping(path = "/credenciamento/busca-procedimentos/"),
    @ResponseBody
    public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required = 
    false) String query) {
    System.out.println(query);
  1. Correct way
    @GetMapping(path = "/credenciamento/busca-procedimentos/{q}"),
    @ResponseBody
    public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required = 
    false) String query) {
    System.out.println(query);
  1. This link has several ways to do this: https://www.baeldung.com/spring-optional-path-variables

Upvotes: 0

Related Questions