Servlet request.getServletPath

118 views Asked by At

I am new to Servlet and I am trying to learn but I am facing a problem.

I have a servlet class and I want to do CRUD operation. I want each Operation redirected to a specific method. But I had a problem, it won't redirect. I tested via POSTman but whenever I tried to send a request it does not receive and nothing appears in my console.

Only the default works.

This is my @WebServlet("/budgets")

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("budgetController, doPost() Started");
        String action = request.getServletPath();
        System.out.println("doPost, action ==>" + action);

        switch (action) {

        case "/add": {
            addNewBudget(request, response);
            break;
        }
        case "/update": {
            updateBudget(request, response);
            break;
        }
        case "/delete": {
            deleteBudget(request, response);
            break;
        }
        case "/get": {
            getBudget(request, response);
            break;
        }

        case "/list": {
            getAllBudgets(request, response);
            break;
        }
        default: {
            getAllBudgets(request, response);
            break;
        }

I tried to change the @WebServlet("/budgets") but i couldn't resolve.

1

There are 1 answers

0
Siarhei On

Currently your servlet listens to one specific path /budgets.

To make the servlet listen to everything behind the budgets path, you should set the following URL pattern: /budgets/* in the WebServlet annotation.

In order to read the extra path information you should use the getPathInfo() method instead getServletPath() method.

However, the getPathInfo() may return null if there is no extra path information. You also should check for null.

So change your code to:

@WebServlet("/budgets/*")
....
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("budgetController, doPost() Started");
    String action = request.getPathInfo();
    System.out.println("doPost, action ==>" + action);

    if (action==null)
      action=new String();

    switch (action) {

    case "/add": {
        addNewBudget(request, response);
        break;
    }
    case "/update": {
        updateBudget(request, response);
        break;
    }
    case "/delete": {
        deleteBudget(request, response);
        break;
    }
    case "/get": {
        getBudget(request, response);
        break;
    }

    case "/list": {
        getAllBudgets(request, response);
        break;
    }
    default: {
        getAllBudgets(request, response);
        break;
    }