java - 请求映射 : How to access the "method" value used for a rest endpoint

标签 java spring rest request-mapping

我有一个接受 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/

相关文章:

spring - 通过向表添加行在 thymeleaf 中创建动态列表对象

java - 静态 block 不适用于 Spring 中的@Value

java - 为基于 Spring 的 REST API 编写 Junit 测试用例

android - REST api项目的用户认证方法

java - 如何分发具有依赖项的开源 jar?

java - 使用 Java7 在 OSX 上启用 Swing 菜单

java - 这个算法有什么问题呢? ( java )

java - CXf-意外元素(uri :"",本地 :"ns2.CustomerData")。预期元素为 <{customerbean}CustomerData>

java - 如何关闭 REST 服务的流?

java - 由于 apache ant 上的 crashlytics 构建错误,应用程序崩溃