서블릿 하나
로 클라이언트의 요청을 받음공통 처리가 가능해짐
프론트 컨트롤러가 요청에 맞는 컨트롤러를 찾아 호출함
- 나머지 컨트롤러는 서블릿으로 만들 필요 없음
public interface ControllerV1 {
void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
매개 변수
리턴 타입
서블릿 객체가 아님!
서블릿 객체
는 오직 프론트 컨트롤러 뿐public class MemberFormControllerV1 implements ControllerV1;
public class MemberListControllerV1 implements ControllerV1;
public class MemberSaveControllerV1 implements ControllerV1 {
private MemberRepository memberRepository = MemberRepository.getInstance();
@Override
public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
int age = Integer.parseInt(request.getParameter("age"));
Member member = new Member(userName, age);
memberRepository.save(member);
request.setAttribute("member", member);
String viewPath = "/WEB-INF/views/save-result.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPath);
dispatcher.forward(request, response);
}
}
@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();
ControllerV1 controller = controllerMap.get(requestURI);
if (controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
controller.process(request, response);
}
}
"/front-controller/v1/*"
/front-controller/v1
을 포함한 모든 요청에 대해 서블릿이 실행됨String
, ControllerV1
> controllerMap → 컨트롤러가 비지니스 로직
실행 및 뷰(forward)
관련 코드를 모두 처리
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);
}
}
public interface ControllerV2 {
MyView process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
매개 변수
리턴 타입
MyView
public class MemberFormControllerV2 implements ControllerV2;
public class MemberListControllerV2 implements ControllerV2;
public class MemberSaveControllerV2 implements ControllerV2 {
private MemberRepository memberRepository = MemberRepository.getInstance();
@Override
public MyView process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
int age = Integer.parseInt(request.getParameter("age"));
Member member = new Member(userName, age);
memberRepository.save(member);
request.setAttribute("member", member);
return new MyView("/WEB-INF/views/save-result.jsp");
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
ControllerV2 controller = controllerMap.get(requestURI);
if (controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
MyView view = controller.process(request, response);
view.render(request, response);
}
@Getter @Setter
public class ModelView {
private String viewName;
private Map<String, Object> model = new HashMap<>();
public ModelView(String viewName) {
this.viewName = viewName;
}
}
viewName
model
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);
}
public void render(Map<String, Object> model,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
modelToRequest(model, request);
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPath);
dispatcher.forward(request, response);
}
private void modelToRequest(Map<String, Object> model, HttpServletRequest request) {
model.forEach((key, value) -> request.setAttribute(key, value));
}
}
public interface ControllerV3 {
ModelView process(Map<String, String> paramMap);
}
매개변수
paramMap
리턴 타입
ModelView
public class MemberFormControllerV3 implements ControllerV3;
public class MemberListControllerV3 implements ControllerV3;
public class MemberSaveControllerV3 implements ControllerV3 {
private MemberRepository memberRepository = MemberRepository.getInstance();
@Override
public ModelView process(Map<String, String> paramMap) {
String userName = paramMap.get("userName");
int age = Integer.parseInt(paramMap.get("age"));
Member member = new Member(userName, age);
memberRepository.save(member);
ModelView mv = new ModelView("save-result");
mv.getModel().put("member", member);
return mv;
}
}
@WebServlet(name = "frontControllerServletV3", urlPatterns = "/front-controller/v3/*")
public class FrontControllerServletV3 extends HttpServlet {
private Map<String, ControllerV3> controllerMap = new HashMap<>();
public FrontControllerServletV3() {
controllerMap.put("/front-controller/v3/members/new-form", new MemberFormControllerV3());
controllerMap.put("/front-controller/v3/members/save", new MemberSaveControllerV3());
controllerMap.put("/front-controller/v3/members", new MemberListControllerV3());
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
ControllerV3 controller = controllerMap.get(requestURI);
if (controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
Map<String, String> paramMap = createParamMap(request);
ModelView mv = controller.process(paramMap);
String viewName = mv.getViewName();
MyView myView = viewResolver(viewName);
myView.render(mv.getModel(), request, response);
}
private MyView viewResolver(String viewName) {
return new MyView("/WEB-INF/views/" + viewName + ".jsp");
}
private Map<String, String> createParamMap(HttpServletRequest request) {
Map<String, String> paramMap = new HashMap<>();
request.getParameterNames().asIterator()
.forEachRemaining(paramName -> paramMap.put(paramName, request.getParameter(paramName)));
return paramMap;
}
}
public interface ControllerV4 {
String process(Map<String, String> paramMap, Map<String, Object> model);
}
매개변수
paramMap
model
리턴타입
viewName
public class MemberFormControllerV4 implements ControllerV4;
public class MemberListControllerV4 implements ControllerV4;
public class MemberSaveControllerV4 implements ControllerV4 {
private MemberRepository memberRepository = MemberRepository.getInstance();
@Override
public String process(Map<String, String> paramMap, Map<String, Object> model) {
String userName = paramMap.get("userName");
int age = Integer.parseInt(paramMap.get("age"));
Member member = new Member(userName, age);
memberRepository.save(member);
model.put("member", member);
return "save-result";
}
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestURI = request.getRequestURI();
ControllerV4 controller = controllerMap.get(requestURI);
Map<String, String> paramMap = createParamMap(request);
Map<String, Object> model = new HashMap<>();
String viewName = controller.process(paramMap, model);
MyView myView = viewResolver(viewName);
myView.render(model, request, response);
}
어댑터 패턴
핸들러
핸들러
, (핸들러) 어댑터
를 프론트 컨트롤러에 등록핸들러 조회
어댑터 조회
public interface MyHandlerAdapter {
boolean support(Object handler);
ModelView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException;
}
support
(handler)handle
(requset, response, handler)어댑터가 ModelView를 생성해서라도 리턴
해야함V3
핸들러 어댑터public class ControllerV3HandlerAdapter implements MyHandlerAdapter{
@Override
public boolean support(Object handler) {
return (handler instanceof ControllerV3);
}
@Override
public ModelView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
ControllerV3 controller = (ControllerV3) handler;
Map<String, String> paramMap = createParamMap(request);
return controller.process(paramMap);
}
}
public interface ControllerV3 {
ModelView process(Map<String, String> paramMap);
}
V4
핸들러 어댑터public class ControllerV4HandlerAdapter implements MyHandlerAdapter {
@Override
public boolean support(Object handler) {
return (handler instanceof ControllerV4);
}
@Override
public ModelView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
ControllerV4 controller = (ControllerV4) handler;
Map<String, String> paramMap = createParamMap(request);
Map<String, Object> model = new HashMap<>();
// V4 컨트롤러는 ModelView를 리턴해주지 않음!!
String viewName = controller.process(paramMap, model);
ModelView mv = new ModelView(viewName);
mv.setModel(model);
return mv;
}
}
public interface ControllerV4 {
String process(Map<String, String> paramMap, Map<String, Object> model);
}
ModelView를 만들어 리턴
해야함어댑터 패턴의 핵심!
프론트 컨트롤러 - v5
@WebServlet(name = "frontControllerServletV5", urlPatterns = "/front-controller/v5/*")
public class FrontControllerServletV5 extends HttpServlet {
private Map<String, Object> handlerMappingMap = new HashMap<>();
private List<MyHandlerAdapter> handlerAdapters = new ArrayList<>();
public FrontControllerServletV5() {
initHandlerMappingMap();
initHandlerAdapter();
}
private void initHandlerMappingMap() {
handlerMappingMap.put("/front-controller/v5/v3/members/new-form", new MemberFormControllerV3());
handlerMappingMap.put("/front-controller/v5/v3/members/save", new MemberSaveControllerV3());
handlerMappingMap.put("/front-controller/v5/v3/members", new MemberListControllerV3());
handlerMappingMap.put("/front-controller/v5/v4/members/new-form", new MemberFormControllerV4());
handlerMappingMap.put("/front-controller/v5/v4/members/save", new MemberSaveControllerV4());
handlerMappingMap.put("/front-controller/v5/v4/members", new MemberListControllerV4());
}
private void initHandlerAdapter() {
handlerAdapters.add(new ControllerV3HandlerAdapter());
handlerAdapters.add(new ControllerV4HandlerAdapter());
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object handler = getHandler(request);
MyHandlerAdapter myHandlerAdapter = getHandlerAdapter(handler);
ModelView mv = myHandlerAdapter.handle(request, response, handler);
String viewName = mv.getViewName();
MyView myView = viewResolver(viewName);
myView.render(mv.getModel(), request, response);
}
private Object getHandler(HttpServletRequest request) {
String requestURI = request.getRequestURI();
Object handler = handlerMappingMap.get(requestURI);
return handler;
}
private MyHandlerAdapter getHandlerAdapter(Object handler) {
for (MyHandlerAdapter handlerAdapter : handlerAdapters) {
if (handlerAdapter.support(handler)) {
return handlerAdapter;
}
}
throw new IllegalArgumentException("해당 핸들러의 어댑터가 없습니다.");
}
private MyView viewResolver(String viewName) {
return new MyView("/WEB-INF/views/" + viewName + ".jsp");
}
}
String
, Object
> handlerMappingMapMyHandlerAdapter
> handlerAdapters⇒ 이 두 필드만 외부에서 주입받는다면 완벽한 OCP를 지킬 수 있음
handlerMappingMap에서 URL에 해당하는 컨트롤러를 찾음
해당 컨트롤러를 지원하는 어댑터를 찾음
찾은 어댑터로 컨트롤러를 실행함 (handle)
→ ModelView 리턴
ModelView 리턴으로 컨트롤러 실행 결과를 렌더링
프론트 컨트롤러
적용뷰 로직
을 MyView
클래스를 사용해 분리
ModelView
를 리턴viewResolver
를 통해 뷰의 물리 이름을 저장한 MyView 객체를 얻음MyView
가 model에 담긴 데이터와 뷰의 물리 이름을 사용해 결과를 렌더링어댑터 패턴
을 적용함⭐ 버전이 높아질 수록 프론트 컨트롤러가 복잡해지고 컨트롤러는 간단해진다.
spring MVC 프레임워크는 위와 같은 과정으로 발전해왔다.