3

I want to get the path variable in servlet. Assume the url is www.demo.com/123/demo. I want to get the 123 value from the path without doing any string manipulation operation.

Note: the following servlet doesn't have any web.xml configurations. My code is:

@WebServlet(urlPatterns = { "/demo" })
public class DemoServlet extends HttpServlet {

  public DemoServlet()
  {
      super();
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
      doPost(request,response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  { 
      sysout("demo");       
  }
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
pavithran
  • 41
  • 1
  • 7

1 Answers1

1

The portion of the URL you are referring to is the "context". Use request.getContextPath() to get this. In the case of your example, this would return /123. If you want exactly 123 you would have to remove the leading slash.

From the documentation:

Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "". The container does not decode this string.

worpet
  • 3,788
  • 2
  • 31
  • 53
  • Sorry i mentioned wrong actually the url is www.demo.com/test/123/demo.In this url the context path is test.But i want to get the 123 present between test and demo.In spring i can do this with @pathparam annotation.But in sevlet i dont know how to do.this is the problem. – pavithran Feb 17 '17 at 13:21
  • The link above shows all the methods that get parts of the URL. There is not way to get exactly what you are looking for without doing some basic String manipulation. – worpet Feb 17 '17 at 20:43