-4

我正在从主 servlet 调用另一个 servlet,通过实现 jsp 本来很容易,但我对这个实验的目标是只使用 servlet,请帮助

4

1 回答 1

2

你不能在一个类中多次重写一个方法,所以你不能doPost多次重写。

如果您的意思是超载,则没有充分的理由这样做。最后,Servlet Container 只会调用这些方法中的一种。

如果您想使用单个 Servlet 处理超过 1 种类型的请求,您可以发送一个参数来指示您将执行的操作。例如:

@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...
    }
}

请注意,这是需要手动处理的大量工作(这是 Java Web MVC 框架存在的原因)。你也可以参考

于 2013-04-10T17:35:29.910 回答