-4

I am calling another servlet from main servlet,It would have been easy by implementing jsp ,but my aim for this experiment is to use only servlet,pls help

y0uth
  • 42
  • 4

1 Answers1

2

You can't override a method more than once in a class, so you can't override the doPost several times.

If you mean overload it, there's not a good reason for doing that. In the end, only one of those methods will be called by the Servlet Container.

If you want to handle more than 1 kind of requests using a single Servlet, you can send a parameter indicating the action you will perform. For example:

@WebServlet("/person")
public class PersonCRUDServlet extends HttpServlet {

    private static final String ADD = "add";
    private static final String DELETE = "delete";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String action = request.getParameter("action");
        //using if assuming you work with Java SE 6
        if (ADD.equals(action)) {
            add(request, response);
        } else
        if (DELETE.equals(action)) {
            delete(request, response);
        } else {
            //submitted action can't be interpreted
            //or no action was submitted
            errorForward(request, response);
        }
    }

    private void add(HttpServletRequest request, HttpServletResponse response) {
        //handle logic for add operation...
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) {
        //handle logic for delete operation...
    }

    private void errorForward(HttpServletRequest request, HttpServletResponse response) {
        //handle logic for delete operation...
    }
}

Note that this is a lot of work to handle manually (this is a reason why Java Web MVC frameworks exists). You can also refer to

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332