Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the action from the HttpServlet request to dispatch to multiple pages

I am using the Page Controller pattern. How could I use the same controller for two different pages by detecting the request action and then dispatching according to the result?

Here is my code:

account.jsp

<form name="input" action="<%=request.getContextPath() %>/edit" method="get">
   <input type="submit" value="Modifier" />
</form>

Account Servlet

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("received HTTP GET");

        String action = request.getParameter("action");

        if (action == null)
        {
            // the account page
            dispatch(request, response, "/account");    
        }
        else if (action == "/edit") {
            // the popup edit page
            dispatch(request, response, "/edit");
        }

        protected void dispatch(HttpServletRequest request,
            HttpServletResponse response, String page)
            throws javax.servlet.ServletException, java.io.IOException {
        RequestDispatcher dispatcher = getServletContext()
            .getRequestDispatcher(page);
        dispatcher.forward(request, response);
}
    }
like image 267
JF Beaulieu Avatar asked Nov 29 '25 08:11

JF Beaulieu


1 Answers

I have found out that using HttpServletRequest#getServletPath() gets exactly what I needed so I don't need to parse anything!

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("received HTTP GET");

    String action = request.getServletPath();

    if (action.equals("/account"))
    {
        // the account page
        dispatch(request, response, "/content/account.jsp");    
    }
    else if (action.equals("/edit")) 
    {
        // the popup edit page
        dispatch(request, response, "/content/edit.jsp");
    }
}

protected void dispatch(HttpServletRequest request,
    HttpServletResponse response, String page)
        throws javax.servlet.ServletException, java.io.IOException {
    RequestDispatcher dispatcher = getServletContext()
            .getRequestDispatcher(page);
    dispatcher.forward(request, response);
    }
}
like image 142
JF Beaulieu Avatar answered Dec 01 '25 16:12

JF Beaulieu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!