繁体   English   中英

@RequestParameter是否仅与GetMapping和PostMapping一起使用?

[英]Does @RequestParameter only work with GetMapping and PostMapping?

我有这些映射:

@GetMapping("rparam")
public void get(@RequestParam("test") String test) {
    System.out.println(test);
}

@PostMapping("rparam")
public void post(@RequestParam("test") String test) {
    System.out.println(test);
}

@PatchMapping("rparam")
public void patch(@RequestParam("test") String test) {
    System.out.println(test);
}

@DeleteMapping("rparam")
public void delete(@RequestParam("test") String test) {
    System.out.println(test);
}

@PutMapping("rparam")
public void put(@RequestParam("test") String test) {
    System.out.println(test);
}

除了GetMapping和PostMapping方法之外,其他所有方法均因400 Bad请求失败而失败,因为它们找不到测试参数。

编辑:如何提出要求(后一作品):

(对数据进行字符串化并添加contentType:application / json也无济于事)

$.ajax({
    url: "api/my-controller/rparam",
    method: "POST",
    data: {
        test: "super test"
    },
    headers: {
        "X-XSRF-TOKEN": cookie
    }
}).done(function() {
    console.log("super cool")
});

$.ajax({
    url: "api/my-controller/rparam",
    method: "PUT",
    data: {
        test: "super test"
    },
    headers: {
        "X-XSRF-TOKEN": cookie
    }
}).done(function() {
    console.log("super cool")
});

编辑:我只是注意到,当我不对数据进行字符串化并设置contentType时,它将作为表单数据发送。 通过表单发送数据仅支持发布和获取,所以这可能与它有关?

尝试通过更改方法来提供一些默认值:

public void delete(@RequestParam(value = "test" , defaultValue = "default") String test)

@RequestParam可以与所有类型的@RequestMapping一起使用

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

但是,关于语义,应该假设PATCH,PUT和DELETE接受请求的主体,然后在URI标识的资源上更新/存储/删除对象。

所以,我建议使用@RequestBody而不是@RequestParam

您可以看一下这个非常相似的问题。

暂无
暂无

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

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