java 用于匹配以斜杠 ("/") 结尾的 URL 的 Servlet URL 模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/459263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:28:37  来源:igfitidea点击:

Servlet URL pattern to match a URL that ends with a slash ("/")

javaservletsweb.xmlurl-pattern

提问by Jon Cram

I'd like to specify a Servlet URL pattern to match a URL that ends with a slash ("/") and only a slash.

我想指定一个 Servlet URL 模式来匹配以斜杠 ("/") 结尾且仅以斜杠结尾的 URL。

I understand that the pattern

我明白这个模式

    /example/path/*

will match a URL of

将匹配一个 URL

    http://example.com/example/path/

and that this appears to work. However, that same pattern would also match URLs of

并且这似乎有效。但是,相同的模式也会匹配

    http://example.com/example/path/a/
    http://example.com/example/path/b/
    http://example.com/example/path/c/

I'm merely looking for a URL pattern that will match http://example.com/example/path/only without also matching http://example.com/example/path/a/and so on.

我只是在寻找一个http://example.com/example/path/只匹配而不匹配http://example.com/example/path/a/等等的 URL 模式。

Clarification: a URL pattern ending with a slash is not allowed.

说明:不允许以斜杠结尾的 URL 模式。

采纳答案by Peter ?tibrany

It's quite possible that you can't do this by mapping in web.xml.

您很可能无法通过在 web.xml 中进行映射来做到这一点。

What you can do is to map servlet to /mypath/* and then check part after /mypath/ via request.getPathInto(). If it is "/", run your code. If it isn't, return 404 error.

您可以做的是将 servlet 映射到 /mypath/*,然后通过 request.getPathInto() 检查 /mypath/ 之后的部分。如果它是“/”,请运行您的代码。如果不是,则返回 404 错误。

回答by Yu Chen

In NetBeans, if I go to the Servlets tab on the web.xml file, the IDE would complain with, "Error: URL patterns cannot end with slash (/)". From the URL spec, it reads,

在 NetBeans 中,如果我转到 web.xml 文件上的 Servlets 选项卡,IDE 会抱怨“错误:URL 模式不能以斜杠 (/) 结尾”。从URL 规范中,它读取,

httpurl        = "http://" hostport [ "/" hpath [ "?" search ]]
hpath          = hsegment *[ "/" hsegment ]

So yes, an URI with an ending slash is invalid.

所以是的,带有结尾斜杠的 URI 是无效的。