英文:
Select2 search term is not being sent to my controller endpoint
问题
$(".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,
},
});
@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}'
,但每次 query 都为 null,在这种情况下函数甚至不会被执行,因为请求中没有 query 参数。
英文:
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.
答案1
得分: 1
你使用路径变量的方式是错误的。
首先,路径变量是URL的一部分。
因此,您的Get映射URL变成
@GetMapping(path = "/credenciamento/busca-procedimentos/{q}")
。
你的第二个错误在于你的AJAX请求。
当你使用路径变量时,AJAX请求中的URL应包含查询字符串。因此,你的URL实际上变成了 - url:'http://localhost:8080/credenciamento/busca-procedimentos/queryString'
所以你可以比较这两个URL,它们应该完全匹配。
你在Spring请求映射中的 /{q}
对应于AJAX请求URL中的 /queryString
。
想了解更多信息,请访问
https://www.journaldev.com/3358/spring-requestmapping-requestparam-pathvariable-example
这是正确使用路径变量的方法。
进行这两个更改,应该就可以正常工作了。
英文:
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.
答案2
得分: 0
以下是翻译好的部分:
- 你的代码中缺少了 URL 末尾的 "q"。
@GetMapping(path = "/credenciamento/busca-procedimentos/"),
@ResponseBody
public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required =
false) String query) {
System.out.println(query);
- 正确的方式
@GetMapping(path = "/credenciamento/busca-procedimentos/{q}"),
@ResponseBody
public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required =
false) String query) {
System.out.println(query);
英文:
Here's have exemple to use PathVariable <https://stackoverflow.com/questions/19803731/spring-mvc-pathvariable>.
- 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);
- Correct way
@GetMapping(path = "/credenciamento/busca-procedimentos/{q}"),
@ResponseBody
public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required =
false) String query) {
System.out.println(query);
- This link has several ways to do this: <https://www.baeldung.com/spring-optional-path-variables>
答案3
得分: 0
我找到了问题所在。不是因为我的请求或与select2相关的任何内容。问题出在我处理筛选的方式上。我试图按照教程的步骤进行,但教程是针对数组的。而在我的情况下,我需要一个列表,我尝试进行了适应,但并没有成功。我只是将所有的筛选逻辑都删除了,然后手动进行了筛选,遍历我的列表,并且只将那些在描述中包含查询字符串的过程添加到我的返回中。\n附注:不需要使用 @PathVariable,正确的方式是使用 @RequestParam,并且路由应该保持相同。末尾不需要 /{q}。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论