1.Controller.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ⾃定义接⼝,实现管理多个请求,在模拟Spring MVC中的控制器
*/
public interface Controller {
String handleRequest(HttpServletRequest request,
HttpServletResponse response);
}
2.DispatcherServlet.java负责将多个请求分发给各⾃不同的控制器
@WebServlet(urlPatterns = {"/ProductInput", "/ProductDetail"})
public class DispatcherServlet extends HttpServlet {protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
String action =requestURI.substring(requestURI.lastIndexOf("/") + 1);
Controller controller = null;
if("ProductInput".equalsIgnoreCase(action)){
controller = new ProductInputController();
}else if("ProductDetail".equalsIgnoreCase(action)){
controller = new ProductDetailController();
}
String url = controller.handleRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
结论:多个请求可以交给同⼀个Servlet(DispatcherServlet),然后各⾃不同的请求会交给各
⾃的控制器。所有请求都叫个DispatcerServet,该⻆⾊相当于⼀个前端控制器,可以⼤⼤的提
⾼客户的以及服务器端的⼯作效率。