我从主servlet调用另一个servlet,通过实现jsp会很容易,但我这个实验的目的是只使用servlet,请帮助
答案 0 :(得分:2)
您不能在课程中多次覆盖某个方法,因此您无法多次覆盖doPost
。
如果你的意思是超载它,那就没有充分的理由这样做。最后,Servlet容器只会调用其中一个方法。
如果要使用单个Servlet处理多种请求,可以发送一个参数来指示您将执行的操作。例如:
@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框架存在的原因)。你也可以参考