在 REST 中处理特殊字符 API

Handling special characters in REST API

我正在关注 URL

http://context_path/info/abc/def

转换为

http://context_path/info/abc%2Fdef

我的控制器映射是:

@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)

此处 'id' 包含正斜杠 (/)。所以当我点击 URL 时,我得到 400 Bad Request

我知道可能的解决方案

但是以上解决方案对我来说是不可能的。

Q. 是否有任何其他解决方案(使用正则表达式或更改映射或其他任何方式)来解决这个问题? 还有 tomcat 如何正确对待其他特殊字符 ('.' , ''' , ':' , ',') 并且控制器被击中但不是 '/'.

试过但没有用:

1) @RequestMapping(value = "/info/{id:.*}", method = RequestMethod.GET)
2) @RequestMapping(value = "/info/{id}/**", method = RequestMethod.GET)
3) @RequestMapping(value = "/info/**", method = RequestMethod.GET)

您可以使用正则表达式来定义您的url。参考 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates-regex

你可以使用这样的东西

但它有其局限性,我建议您在调用 api 时将正斜杠替换为“#”之类的其他内容,然后再次将其替换回正斜杠,然后再在其余控制器中进行处理.

如果在调用 api 时替换是不可能的,那么您可以使用过滤器并替换那里的数据。

不太好,但你可以使用 Base64 transformation

因此您的客户端将发送一个编码的 id 并且您将其解码回您的控制器。

import org.apache.commons.codec.binary.Base64;

@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
public String get(@PathVariable String id) {
    final String realId = new String(new Base64(true).encodeBase64URLSafe(id));
    [...]
}

编辑:您应该使用 url 保存 Base64 的实现

  • java脚本:js-base64
  • java: Base64 from Apache Commons
  • Is it ok to remove newline in Base64 encoding