gpt4 book ai didi

基于 Java-Jersey 的 RESTful 网络服务 : What is the best way to handle path param for a file entity

转载 作者:搜寻专家 更新时间:2023-11-01 03:07:40 25 4
gpt4 key购买 nike

我正在使用 jersey 编写基于 Java 的 REST 网络服务。我为其编写 Web 服务的实体是一个媒体文件。请求媒体文件的客户端需要将路径和文件名作为路径参数发送。允许的媒体路径最多可达五个目录的深度。现在的挑战是编写一个方法来处理所有路径深度的可能性。就业务场景而言,使用路径参数是唯一允许的选择。这是处理媒体文件请求的方法契约:

public Response getMediaFile(@PathParam("path") String path,
@PathParam("filename") String filename);

此方法的问题在于,如果请求类似于/media/filedir1/filedir2/filename,则无法正确获取文件名。

我已经实现的解决方案是,我已经重载了这个方法来处理所有目录深度,但我并不真的相信这是最好的解决方案:

public Response getMediaFile(@PathParam("path1") String path1, 
@PathParam("path2") String path2,
@PathParam("filename") String filename);

public Response getMediaFile(@PathParam("path1") String path1,
@PathParam("path2") String path2,
@PathParam("path3") String path3,
@PathParam("filename") String filename);

等等。

最佳答案

您应该能够在您的@PathParam 注释中使用正则表达式来处理所有路径过滤逻辑。例如,这将为您提供最多向下 5 个目录的文件路径:

@Path("{path:(?:[^/]+/){0,4}[^/]+}")

然后您将该值注入(inject)预期的方法中:

@Path("{path:(?:[^/]+/){0,4}[^/]+}")
/* Other attributes too... */
public Response getMediaFile(@PathParam("path") String path) {
File file=new File(MEDIA_HOME_DIR, path);
if(file.exists()) {
// Process file
}
else {
// No such file
}
}

正则表达式将处理“五个目录”的限制,如果将来数量从五个改变,将很容易修复。如果您只需要匹配 .jpg 文件(例如),您也可以轻松地更仔细地过滤文件名。

解决了这个问题后,您只需要为媒体服务即可。 :)

关于基于 Java-Jersey 的 RESTful 网络服务 : What is the best way to handle path param for a file entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16870566/

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