Search code examples
servletspath-parameter

How to read the following path from a servlet?


I have a servlet which works on organizations address (@WebServlet("/organizations")). This way using GET or POST method on address .../organizations leads to calling of this servlet. When I need to work with a current organization (for example, 12th), I should call .../organizations/12. This way I can write @WebServlet("/organizations/*"), but how to read this number (12 in this case)? Or can I replace it with a variable somehow like @WebServlet("/organizations/{orgNumber}") (this variant didn't work)?


Solution

  • You could map it on /organizations/* and extract information from getPathInfo():

    @WebServlet("/organizations/*")
    public class OrganizationsController extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String[] pathInfo = request.getPathInfo().split("/");
            String id = pathInfo[1]; // {id}
            String command = pathInfo[2];
            // ...
           //..
          //.
        }
    
    }