Select2搜索项未发送到我的控制器端点

问题描述 投票:0回答:1

我有一个select2(它使用AJAX请求从远程源中获取数据,在我的情况下是SpringBoot API)。我设法获取了我想要的数据。但是,我无法在端点中接收搜索词,因此我可以根据用户输入的内容过滤结果:

下面是我的代码,带有select2的AJAX请求和带有相应功能的SpringBoot端点。

$(".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,
    },
});

这里是我的Java函数:

@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:每次执行该函数时,我的system.out.println结果为null。我尝试将@PathVariable更改为@RequestParam,但会引发异常,表示未从请求中接收任何参数,并且尝试将路由更改为'/ credenciamento / busca-procedimento / {query}',但每次都进行查询为null,在这种情况下,该函数甚至不会执行,因为请求中没有查询。

java ajax spring-boot jquery-select2 jquery-select2-4
1个回答
0
投票

这里有使用PathVariable Spring mvc @PathVariable的示例。

  1. 在您的代码中,URL末尾缺少“ q”
    @GetMapping(path = "/credenciamento/busca-procedimentos/"),
    @ResponseBody
    public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required = 
    false) String query) {
    System.out.println(query);
  1. 正确的方式
    @GetMapping(path = "/credenciamento/busca-procedimentos/{q}"),
    @ResponseBody
    public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required = 
    false) String query) {
    System.out.println(query);
  1. 此链接有几种方法可以做到这一点:https://www.baeldung.com/spring-optional-path-variables
© www.soinside.com 2019 - 2024. All rights reserved.