pavithran
pavithran

Reputation: 41

how to get a path variable value in servlet

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");       
  }
}

Upvotes: 3

Views: 5348

Answers (1)

worpet
worpet

Reputation: 3893

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.

Upvotes: 1

Related Questions