스크린샷 2022-01-14 오전 10.19.20.png

Front Controller

1. 프론트 컨트롤러 V1

@WebServlet(name = "frontControllerServletV1", urlPatterns = "/front-controller/v1/*")
public class FrontControllerServletV1 extends HttpServlet {
    private 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(); // /front-controller/v1/members/new-form 이런 부분 얻어옴
        ControllerV1 controller = controllerMap.get(requestURI);
        if (controller == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        controller.process(request, response); //controller 호출
    }
}
public interface ControllerV1 {
    void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
public class MemberSaveControllerV1 implements ControllerV1 {
    private MemberRepository memberRepository = MemberRepository.getInstance();

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //argument
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
				//save
        Member member = new Member(username,age);
        memberRepository.save(member);

        //model에 데이터 보관하기
        request.setAttribute("member",member);
        String viewPath = "/WEB-INF/views/save-result.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(viewPath);
        dispatcher.forward(request,response);
    }
}

스크린샷 2022-01-14 오전 10.28.04.png

스크린샷 2022-01-14 오전 10.28.14.png

2. 프론트 컨트롤러 - V2

: 모든 컨트롤러에 뷰로 이동하는 부분의 중복이 존재하므로 이를 없애보자

→ 뷰를 처리하는 객체를 생성한다.

public class MyView {
    private String viewPath;

    public MyView(String viewPath) {
        this.viewPath = viewPath;
    }

    //뷰를 만드는 행위
    public void render(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        **RequestDispatcher dispatcher = request.getRequestDispatcher(viewPath);
        dispatcher.forward(request,response);**
    }
}