【问题标题】:Does @RequestParameter only work with GetMapping and PostMapping?@RequestParameter 是否仅适用于 GetMapping 和 PostMapping?
【发布时间】:2018-04-19 07:44:19
【问题描述】:

我有这些映射:

@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 request。

编辑: 请求是如何提出的(第一个工作):

(对数据进行字符串化并添加 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 时,它​​会作为表单数据发送。而通过表单发送数据只支持 post 和 get 所以可能与它有关?

【问题讨论】:

  • 您如何访问它们?您是否像这样访问它们:localhost:/rparam?test=test ?
  • 方法是相同的,所以问题可能不在于该代码:) 您如何访问它们或您的 servlet 是如何制作的
  • 您需要在实际访问这些端点的地方添加一些代码
  • 我添加了请求的生成方式
  • 是否可以使用@RequestBody 代替@RequestParam 进行PATCH、PUT 和DELETE 请求?

标签: java spring model-view-controller


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    @RequestParam 可以与各种@RequestMapping 一起使用:

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

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

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

    你可以看看this very similar question.

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2020-07-30
      • 2022-11-18
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多