我有一个 EmailVerification
Servlet 映射到 /ev/*
url-pattern。
http://example.com/ev/ce52320570
如何在我的 Servlet 中获取 URL 的 ce52320570
部分?
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String vid = ""; // Here I need to get the id from the URL
}
最佳答案
考虑映射到 /ev/*
的 Servlet(称为 EmailVerification
):
Will the URL
http://example.com/ev/ce52320570
trigger theEmailVerification
servlet ?
是的。在 Servlet 版本 2.5 和 3.0(可能更早)中,如果您将其映射到 *
,如 /ev/*
,它将获得子路径。
How can I get this
ce52320570
part of the URLhttp://example.com/ev/ce52320570
?
request.getRequestURI()
将以String
的形式为您提供请求的 URL,例如/ev/ce52320570
。request.getPathInfo()
在/ev/
之后获取(如果存在)所有内容。- 所以在对
/ev/123
的请求中,getPathInfo()
会给你/123
。同样,对/ev/some/other
的请求,getPathInfo()
会给你/some/other
。/p>
- 所以在对
request.getQueryString()
如果您需要 URL 的查询参数部分,应该使用。- 请记住,
getRequestURI()
和getPathInfo()
都只为您提供请求的路径。如果需要获取查询参数,即?
之后的参数,如/ev/something?query1=value1&other=123
,只有request.getQueryString()
会返回query1=value1&other=123
部分。
- 请记住,
request.getParameter(parameterName)
如果您需要特定查询参数的值。- 求助于
.getParameterValues()
如果是多值参数
- 求助于
请求中 URL 部分的更多示例 here .
关于java - 在servlet中获取部分请求url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16501478/