Getting part of request url inside servlet

旧巷老猫 提交于 2019-12-03 12:45:20

问题


I have an EmailVerification Servlet mapped with /ev/* url-pattern.

http://example.com/ev/ce52320570

How can I get this ce52320570 part of the URL in my Servlet?

protected void doPost(HttpServletRequest request, HttpServletResponse response)
                                                     throws ServletException, IOException {
      String vid = "";  // Here I need to get the id from the URL
}

回答1:


Considering a Servlet (called EmailVerification) mapped to /ev/*:

Will the URL http://example.com/ev/ce52320570 trigger the EmailVerification servlet ?

Yes. In Servlet versions 2.5 and 3.0 (maybe earlier), it'll get the subpath if you map it with *, like /ev/*, as you did.

How can I get this ce52320570 part of the URL http://example.com/ev/ce52320570?

  • request.getRequestURI() will get you the requested URL as a String, like /ev/ce52320570.

  • request.getPathInfo() gets you (if exists) everything after /ev/.

    • So in a request to /ev/123, getPathInfo() would give you /123. The same way, a request to /ev/some/other, getPathInfo() would give you /some/other.

  • request.getQueryString() should be used if you need the query parameters part of the URL.

    • Keep in mind both getRequestURI() and getPathInfo() give you only the path requested. If you need to obtain the query parameters, that is, those after the ?, like /ev/something?query1=value1&other=123, only request.getQueryString() would return the query1=value1&other=123 part.
  • request.getParameter(parameterName) if you need the value of a specific query parameter.

    • Resort to .getParameterValues() if it is a multivalued parameter

More examples of the URL parts in the request here.




回答2:


Use request.getRequestURI() and remove what you don't need, i.e. request.getRequestURI().replace("/ev/");



来源:https://stackoverflow.com/questions/16501478/getting-part-of-request-url-inside-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!