Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Spring Rest@PathVariable中正确转义“/”_Java_Spring_Rest - Fatal编程技术网

Java 如何在Spring Rest@PathVariable中正确转义“/”

Java 如何在Spring Rest@PathVariable中正确转义“/”,java,spring,rest,Java,Spring,Rest,在Spring Boot 1.5.4中,我有如下请求映射: @RequestMapping(value = "/graph/{graphId}/details/{iri:.+}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public JSONObject getGraph(@PathVariable Long

在Spring Boot 1.5.4中,我有如下请求映射:

@RequestMapping(value = "/graph/{graphId}/details/{iri:.+}", 
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public JSONObject getGraph(@PathVariable Long graphId, 
                           @PathVariable String iri) {
    log.debug("Details called for graph ID {} for IRI {}", graphId, iri);
    return detailsService.getDetails(graphId, iri);
}
访问

工作正常,服务器正确映射请求,代码返回预期结果

但是访问

提供错误的服务器请求加载资源失败:服务器以400错误请求的状态响应。在这种情况下,甚至没有完成到端点的请求映射

显然,使用encodeURIComponent编码为%2F的斜杠“/”会导致问题。为什么?我错过了什么?uri参数应该如何编码


问题不仅在于如何提取PathVariables,更在于如何强制字符串识别正确的映射

您的示例的问题是Spring如何进行路径匹配。您提供的URL作为示例

http://localhost:9000/api/v1/graph/2/details/http%3A%2F%2Fserverurl.net%2Fv1%2Fus%2Fh.schumacher%408tsch.net%2Fn%2FLouSchumacher
将由容器解码为

在弹簧匹配器处理之前。这使得matche认为只有http:对应于{iri:.+},正如后面所说的,这是一条较长的路径,您没有映射

这里描述的方法应该适用于您:


与其获取API,不如将其设置为POST API请求,并在请求体中发送URI。作为一个经验法则,每当您需要传递大量参数时,POST都会更方便地复制Spring 3 RequestMapping:Get path value是相关的,但问题不是重复的,因为这个问题是关于Rest端点的映射,而不是关于PathVariables的提取。这有助于,但是,如果我不使用encodeURIComponent对URL进行编码,那么到Rest端点的映射确实可以这样工作。如果我使用encodeURIComponent进行编码,映射将无法识别,并且我会收到一个错误的请求400。因此,对于的映射有效,而对于的映射无效。
@RequestMapping(value = "/graph/{graphId}/details/**", 
                method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public JSONObject getGraph(@PathVariable Long graphId, 
                           HttpServletRequest request) {
    String iri = (String) request.getAttribute(
        HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    log.debug("Details called for graph ID {} for IRI {}", graphId, iri);
    return detailsService.getDetails(graphId, iri);
}