泽西岛路径注释中的正则表达式

时间:2014-08-06 17:23:58

标签: java regex path jersey

我目前面临一个简单的想法,其API看起来像这样:

/users                  -> return a collection of users
/users/1                -> return all data included in one user
/users/1/information    -> return the information json
/users/1/dogs/rex       -> return the information of the users dog rex :)
/users/1/dogs/          -> return the collection of the users dogs

请注意,这些代表文件系统中的文件夹结构,其中用户,1,dog,rex是文件夹,信息将是包含json的文件(并不真正重要的内容)

所以我的想法是用正则表达式构建它(为什么?!我想让它变得有点通用 - 我在这里所做的只是"一个小小的形象")。

1 Folder:            \/[a-zA-Z0-9]+
2 Folders:           \/[a-zA-Z0-9]+\/[a-zA-Z0-9]+
2 Folders - 1 File:  \/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+
4 Folders:           \/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+\/[a-zA-Z0-9]+ //should be the first loop of 2 folders.

那么如何获得一个正则表达式也匹配一个循环(我知道2 Folders *3 -> 6 Folders)(2 Folders + 1 File)*2 -> 6 "Folders")但是在这一点上它对我来说并不重要。

2 个答案:

答案 0 :(得分:1)

如果您想对文件夹和文件及其关系进行建模,我建议采用不同的方法。在URL中复制文件/文件夹关系并不是必需的。此类信息可以是每个文件/文件夹资源的表示的一部分。

资源

文件

文件具有ID,名称以及可能的其他一些属性。 包含在文件夹中。

{
  "id": "file-1",
  "link": "/files/file-1",
  "name": "file-1.txt",
  "folder": "folder-1"
}

所有文件的收集资源都有网址

/files

单个文件具有网址

/files/{id}

例如

/files/file-1

文件夹

文件夹具有ID,名称以及可能的其他一些属性。它包含零个或多个文件和文件夹。

{
  "id": "folder-1",
  "link": "/folders/folder-1",
  "name": "folder-1",
  "children": [
    {
      "id": "folder-2",
      "link": "/folders/folder-2"
    },
    {
      "id": "file-1"
      "link": "/files/file-1"
    }
  ]
}

所有文件夹的收集资源具有网址

/folders

单个文件夹包含网址

/folders/{id}

例如

/folders/folder-1

根文件夹

根文件夹有一些已知的ID,例如

/folders/root

答案 1 :(得分:0)

我知道这不是你想要的,而是试图将你的解决方案用于正则表达式,为什么不用@PathParam捕获整个路径并在java中解析它?

@Path("/operation/{path:.+}")
public String getFile(@PathParam("path") String path) {
    // Parse "path"
}

显示的路径参数应捕获其余呼叫中 / operation / 之后的所有内容。