我有一个接受 GET 和 POST 请求的 Spring Boot REST Controller 端点:
@RequestMapping(
value="/users",
method= {RequestMethod.GET, RequestMethod.POST},
headers= {"content-type=application/json"}
)
public ResponseEntity<List<User>> getUsers() {
if(/*Method is GET*/) {
System.out.println("This is a GET request response.");
} else if( /*Method is POST*/) {
System.out.println("This is a POST request response.");
}
}
如果此端点被 GET 请求命中,我希望 Controller 在适当的 if 语句中执行某些操作。然而,如果端点被 POST 请求命中,我希望 Controller 采取另一种行动。
如何从 rest Controller 中提取这些信息?我宁愿不必将此共享端点拆分为两种不同的方法。这看起来很简单,我只是找不到任何关于它的文档。
最佳答案
正确的方法是映射两个单独的 GET 和 POST 方法,但如果您打算采用这种方法,则可以通过访问 HttpServletRequest 来获取请求的 HTTP 动词,如下所示:
@RequestMapping(
value="/users",
method= {RequestMethod.GET, RequestMethod.POST},
headers= {"content-type=application/json"}
)
public ResponseEntity<List<User>> getUsers(final HttpServletRequest request) {
if(request.getMethod().equals("GET")) {
System.out.println("This is a GET request response.");
} else if(request.getMethod().equals("POST")) {
System.out.println("This is a POST request response.");
}
}
您不需要更改调用代码,因为 HttpServletRequest 会自动传递
关于java - 请求映射 : How to access the "method" value used for a rest endpoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144009/