What is Dispatcher-Servlet:
Dispatcher-Servlet is important in Spring MVC.
Dispatcher-Servlet first gets client's requests and sends them to corresponding controller.
Dispatcher-Servlet is called Front Controller.
Why use Dispatcher-Servlet :
To process common codes in each controller.
To get all client requests using only a single dispatcher-servlet
Don't have to use servlet in other controllers except dispatcher-servlet
How to use Dispatcher-Servlet:
1. Make FrontControllerServletV1 class and extends HttpServlet.
@WebServlet(name = "frontControllerServletV1", urlPatterns = "/front-controller/v1/*")
public class FrontControllerServletV1 extends HttpServlet {
2. Make a Map. The Key is Strring and the value is a ControllerV1 Interface.
protected Map<String, ControllerV1> controllerMap = new HashMap<>();
3. Make a constructor consposed controllerMap.
public FrontControllerServletV1() {
controllerMap.put("/front-controller/v1/members/new-form", new MemberFormControllerV1());
controllerMap.put("/front-controller/v1/members/save", new MemberSaveControllerV1());
controllerMap.put("/front-controller/v1/members", new MemberListControllerV1());
}
4. Search the controller from the url(location) mappring information.
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
ControllerV1 controller = controllerMap.get(requestURI);
if(controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
controller.process(request, response);
}
getRequestURI() returns the part of this request's URL.
Entire codes of FrontContollerServletV1 which is Dispatcher-Servlet.
@WebServlet(name = "frontControllerServletV1", urlPatterns = "/front-controller/v1/*")
public class FrontControllerServletV1 extends HttpServlet {
protected Map<String, ControllerV1> controllerMap = new HashMap<>();
public FrontControllerServletV1() {
controllerMap.put("/front-controller/v1/members/new-form", new MemberFormControllerV1());
controllerMap.put("/front-controller/v1/members/save", new MemberSaveControllerV1());
controllerMap.put("/front-controller/v1/members", new MemberListControllerV1());
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
ControllerV1 controller = controllerMap.get(requestURI);
if(controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
controller.process(request, response);
}
}
Reference:
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard
댓글