【问题标题】:Spring-boot rest api. Truncate trailing slash弹簧引导休息 api。截断尾部斜杠
【发布时间】:2018-08-20 04:13:12
【问题描述】:

我有一个spring-boot rest api。

在我的application.properties 我有:

server.port=8100
server.contextPath=/api/users

有一个控制器:

@RestController
@RequestMapping("")
public class UserService {
    @RequestMapping(value = "", method = POST, produces = "application/json; charset=UTF-8")
    public ResponseEntity<UserJson> create(@RequestBody UserJson userJson) {
    ...
    }
}

当我打电话时:

POST http://localhost:8100/api/users/ 注意尾部斜杠(带有用户的 json)-create 方法执行良好。

但是当我打电话时:

POST http://localhost:8100/api/users 不带斜杠(带有用户的 json) - 我收到 405 错误:

{ "timestamp": 1520839904193, "status": 405, "error": "Method Not Allowed", "exception": "org.springframework.web.HttpRequestMethodNotSupportedException", "message": "Request method 'GET' not supported", "path": "/api/users/" }

我需要不带斜杠的 URL,只需 .../api/users,为什么它被视为 GET 方法?

【问题讨论】:

  • 看起来您的 HTTP 服务器正在重写不带斜杠的请求并发送重定向,用 GET 代替 POST。检查您的服务器配置。
  • @JimGarrison 你指的是什么配置?我以mvn spring-boot:run 启动我的应用程序,因此它是嵌入式Tomcat。我没有任何额外的配置。
  • 嗯...基于this question 看起来它不是为进行重定向而设计的......所以这超出了我的专业知识。对不起。
  • 我从这里找到了答案。 stackoverflow.com/a/45258671/331946
  • @htshame 删除“更新”部分+将其添加为答案!

标签: java rest spring-boot request-mapping


【解决方案1】:

如果我将 RestController 中的 server.contextPath 更改为 server.contextPath=/api@RequestMapping 更改为 @RequestMapping("/users") ,一切正常。正在调用create() 方法,在 URL 的末尾带有和不带有斜杠。

【讨论】:

  • 您设置 contextPath 有什么特别的原因吗? /api/users 的请求映射将是我要做的。实际上我会做 /api/users/v1 因为将来你会感谢你尽早而不是稍后引入 API 版本。
  • 我有一个相当大的应用程序,所以我们需要一个 contextPath 来作为通用 API URl 前缀。我也有 /v1 和 /v2 前缀,但它们现在位于 @RestController 级别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 2014-02-28
相关资源
最近更新 更多