【问题标题】:spring-way handle slash in resource name资源名称中的弹簧方式句柄斜线
【发布时间】:2014-11-05 02:01:49
【问题描述】:

我在控制器中有以下方法:

 @RequestMapping(value = "/items/{identifier}", method = RequestMethod.DELETE)
    public void delete(@PathVariable String identifier) {
    ... 
    // find item in database by identifier
}

问题是标识符是一个可以包含斜杠('/')字符串。 IE。可能发生的情况:

http://myhost/items/file:/123

对于给定的 URL,“标识符”必须是“file:/123”。

如果有'/',则由于 URL 不正确而引发 405(不允许使用方法)。

如何告诉 Spring 它应该将 '/items/' 之后的所有内容作为“标识符”(REST 术语中的资源名称)?

编辑: 有人告诉我,管理斜线和编码是客户的责任,所以我保持原样。

但对于信息,基于 cmets 中的ankur-singhal 回答:

在 Spring 4.1.0 中添加了我想要的支持,请参阅 this link 和此 commit。 所以在我的情况下,它将是:

 @RequestMapping(value = "/items/{/identifier}", method = RequestMethod.DELETE)

“标识符”之前的“/”起到了作用。

【问题讨论】:

  • 目前我正在使用 JUnit 进行测试,而不是在真正的应用服务器上。
  • @user2138356 试试我的答案,如果它适合你
  • 只是备注:/slash\ backslash ...

标签: java spring rest url


【解决方案1】:

尝试将代码更改为下面,看看它是否有效

它将接受identifier 的任何值。

 @RequestMapping(value = "/items/{identifier:.*}", method = RequestMethod.DELETE)
    public void delete(@PathVariable String identifier) {
    ... 
    // find item in database by identifier
}

如果你使用identifier作为request parameter,那么你可以如下实现:

 @RequestMapping(value = "/items", method = RequestMethod.DELETE)
    public void delete(@RequestParam("identifier") String identifier) {
    ... 
    // find item in database by identifier
}

更多信息请参考here

【讨论】:

  • 它不起作用。我试过这个。例如,此解决方案适用于点,但不适用于反斜杠。
  • @user2138356 使用requestParam..??
  • 我使用 {identifier} 之类的资源名称而不是 requestParam。
  • @user2138356 这里是link,他们谈论的是对 url 进行编码。
  • 谢谢你的链接,我发现它很有用。编辑了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 2017-10-13
相关资源
最近更新 更多