영한킴: spring MVC (1) : 강의 노트 : 스프링 만들기 V1 to V5
이 포스트는 강의 내용에 관한 노트나 필자가 코딩한 것을 기록했습니다
MVC Version 1
- FrontController 패턴으로 전환
- FrontController 생성
- 매핑정보를 조회하기 위한 ControllMap 생성
아래처럼 코드를 구성해보았는데 잘 작동한다 !
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FrontControllerServletV1.service");
String requestURI = request.getRequestURI();
ControllerV1 whichController =
controllerMap
.entrySet()
.stream()
.filter(entry -> entry.getKey().equals(requestURI))
.findFirst()
.orElseThrow(()-> new IllegalArgumentException("해당되는 URI가 없습니다"))
.getValue();
whichController.process(request, response);
}
하지만 영한 킴님의 간결한 코드에.. 난 울어버렸다 ..
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FrontControllerServletV1.service");
String requestURI = request.getRequestURI();
ControllerV1 controller = controllerMap.get(requestURI);
if (controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
controller.process(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 {
System.out.println("FrontControllerServletV1.service");
String requestURI = request.getRequestURI();
ControllerV1 controller = controllerMap.get(requestURI);
if (controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
controller.process(request, response);
}
}
public interface ControllerV1 {
void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
MVC Version 2
- View 분리
- MyView 생성
- 이제 Controller에서 MyView를 반환한다
- FrontController에서는 이것을 렌더링(JSP 호출)
내가 리펙터링 한 것
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FrontControllerServletV1.service");
String requestURI = request.getRequestURI();
ControllerV1 controller = controllerMap.get(requestURI);
if (controller == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
controller.process(request, response);
String[] strings = requestURI.split("/");
Arrays.stream(strings).iterator().forEachRemaining(s -> System.out.println("s = " + s));
String lastURI = strings[strings.length - 1];
System.out.println("lastURI = " + lastURI);
if(lastURI.equals("save")) {
lastURI = "save-result";
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/" + lastURI+".jsp");
dispatcher.forward(request, response);
}
아래는 영한킴님의 코드
public interface ControllerV2 {
MyView process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
@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);
}
public class MemberFormControllerV2 implements ControllerV2 {
@Override
public MyView process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return new MyView("/WEB-INF/views/new-form.jsp");
}
}
// MemberServiceControllerV2, MemberListCOntrollerV2 등... 이하 동일
MVC Version 3
- Model 분리
- Controller가 HttpServlet에서 완전히 독립할 수 있도록 인자로 전달되는 request, response 제거
- 이것을 위한 Model 클래스 생성 (
request.setAttribute
를 대체하기 위함) - view path를 조립해주는 viewResolver 추가
public interface ControllerV3 {
ModelView process(Map<String, String> paramMap);
}
public class FrontControllerServletV3 extends HttpServlet {
...
protected void service (...) {
...
// paramMap
Map<String, String> paramMap = createParamMap(request);
ModelView mv = controller.process(paramMap);
String viewName = mv.getViewName(); // 논리 이름 new-form
MyView view = viewReolver(viewName);
view.render(mv.getModel(), request, response);
}
private MyView viewReolver(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 ControllerV3 {
ModelView process(Map<String, String> paramMap);
}
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;
}
}
@Getter @Setter
public class ModelView {
private String viewName;
private Map<String, Object> model = new HashMap<>();
public ModelView(String viewName) {
this.viewName = viewName;
}
}
public class MyView {
...
public void render(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
modelToRequestAttribute(model, request);
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPath);
dispatcher.forward(request, response);
}
private void modelToRequestAttribute(Map<String, Object> model, HttpServletRequest request) {
model.forEach((key, value) -> {
request.setAttribute(key, value);
});
}
}
MVC Version 4
Model
을 각 컨트롤러가 아닌 Front Controller 에서 생성하게 하자 !
아래는 주 변경 내역이다
public interface ControllerV4 {
/**
* @param paramMap
* @param model
* @return viewName
*/
String process(Map<String, String> paramMap, Map<String, Object> model);
}
public class MemberFormControllerV4 implements ControllerV4 {
@Override
public String process(Map<String, String> paramMap, Map<String, Object> model) {
return "new-form";
}
}
public class FrontControllerServletV4 ... {
protected void service(...) {
...
Map<String, Object> model = new HashMap<>(); //추가
String viewName = controller.process(paramMap, model);
...
}
}
MVC Version 5
- process 인자로 V1 ~ V4 .. 혹은 그 이외의 시그니쳐로 이용하고 싶을 때가 있다
이럴 때,어댑터 패턴
을 이용한다 ! - 이제 Controller는 Adapter를 통해 호출된다 !