gpt4 book ai didi

java - 如何在 Spring Rest @PathVariable 中正确转义 '/'

转载 作者:行者123 更新时间:2023-12-02 12:06:42 38 4
gpt4 key购买 nike

在 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);
}

访问

http://localhost:9000/api/v1/graph/2/details/http%3Anthnth33

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

但是访问

http://localhost:9000/api/v1/graph/2/details/http%3A%2F%2Fserverurl.net%2Fv1%2Fus%2Fh.schumacher%408tsch.net%2Fn%2FLouSchumacher

给出错误的服务器请求(无法加载资源:服务器响应状态为 400(错误请求))。在这种情况下,甚至没有完成到端点的请求映射。

显然,编码为 %2F 的斜杠“/”(使用encodeURIComponent())会引起麻烦。为什么?我缺少什么?那么uri参数应该如何编码呢?​​

问题不仅在于如何提取 PathVariables,还在于如何强制 String 识别正确的映射。

最佳答案

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

http://localhost:9000/api/v1/graph/2/details/http%3A%2F%2Fserverurl.net%2Fv1%2Fus%2Fh.schumacher%408tsch.net%2Fn%2FLouSchumacher

将被容器解码为

http://localhost:9000/api/v1/graph/2/details/http://serverurl.net/v1/us/h.schumacher@8tsch.net/n/LouSchumacher

在 Spring 匹配器处理之前。这使得 matche 认为这只是 http: 对应于 {iri:.+} ,稍后会变成 / 所以这是你不需要的更长的路径没有映射。

此处描述的方法应该适合您:Spring 3 RequestMapping: Get path value

@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);
}

关于java - 如何在 Spring Rest @PathVariable 中正确转义 '/',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860979/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com