简体   繁体   English

Spring REST API,将原始类型传递给控制器

[英]Spring REST API, Pass a primitive type to the controller

@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("")
public ResponseEntity<List<ToDoItemViewModel>> loadCategoriesByName(@RequestParam(required = false) String name)
{
    List<ToDoItemViewModel> allItemsByCategoryName = toDoItemService.getAllItemsByCategoryName(name);
    return new ResponseEntity<>(allItemsByCategoryName, HttpStatus.OK);
}

How can i pass just a primitive type to the controller, here is how my $.ajax looks like 我如何仅将原始类型传递给控制器​​,这就是我的$.ajax样子

$.ajax({
    method: 'GET',
    url: "http://localhost:8080/todItems",
    contentType: 'application/json',
    crossDomain: true,
    data: 'Work',
    success: (resp) => {
        console.log(resp)
    },
    error: (resp) => {
        console.log(resp);
    }

})

Now when i debug it, it indeed sends the request to this controller, but the String name is always null for some reason, can you just show me what i have to adjust in my ajax request, it's probably something in the data field. 现在,当我调试它时,它确实会将请求发送到此控制器,但是由于某种原因, String name始终为null,您能告诉我我在ajax请求中必须调整的内容吗,可能是data字段中的内容。

You are using GET Request with request params(@RequestParam annotation). 您正在将GET Request与请求参数(@RequestParam批注)一起使用。 @RequestParam means that param in request pass across url, like this; @RequestParam意味着请求中的参数通过url传递,就像这样;

http://localhost:8080/todItems?name=Work

So, you just need to move data to url params. 因此,您只需要将数据移至url参数。 If you prefer send data across request body, please do not use GET method, use POST instead. 如果您希望跨请求正文发送数据,请不要使用GET方法,而应使用POST。 Many web servers are not supporting request body in GET Requests 许多Web服务器不支持GET请求中的请求主体

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM