英文:
How to make Spring throw an error when a body is provided
问题
这个控制器不应该接受任何请求体。然而,当我带有请求体调用这个端点时,请求体会被忽略。我该如何让Spring在向不接受请求体的端点提供请求体时抛出错误?
英文:
I have an application with a controller like this:
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping
public String handler() {
return ...;
}
}
This controller is not supposed to accept any body. However, when I call the endpoint with a body the body is just ignored. How can I make Spring throw an error when providing a body to an endpoint which accepts none?
答案1
得分: 1
我有两个选项供您选择。第一个选项是接受一个带有 Body 参数,然后由您自己处理:
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping
public String handler(@RequestBody(required = false) String requestBody) {
if (requestBody != null && !requestBody.isEmpty()) {
throw new YourException("This endpoint does not accept a request body.");
}
return ...;
}
}
第二个选项是消耗 Mediatype。在这个选项中,Spring 将显示 'HttpMediaTypeNotSupportedException'。实际上,您可以添加任何 MediaType:
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String handler() {
return ...;
}
}
英文:
I have 2 options for you. The first one is to take a parameter with Body and then handle it by yourself:
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping
public String handler(@RequestBody(required = false) String requestBody) {
if (requestBody != null && !requestBody.isEmpty()) {
throw new YourException("This endpoint does not accept a request body.");
}
return ...;
}
}
and the second one is to consume Mediatype. In this option, Spring will show 'HttpMediaTypeNotSupportedException'. Actually, you can add any MediaType:
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String handler() {
return ...;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论