Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

Controller V4 본문

인프런/[인프런] 스프링 MVC 1

Controller V4

Seung__ 2021. 9. 11. 14:07

항상 ModelView객체를 생성하고 반환해야 하는 부분이 귀찮음..

 

1. V4 구조


  • 컨트롤러가 ModelView 를 반환하지 않고, ViewName 만 반환한다

 

2. Controllerr V4


  • FrontController가 model, paramMap을 만들어서 controller에 전달.
public interface ControllerV4 {
    /**
     * @param paramMap
     * @param model
     * @return
     */
    String process(Map<String, String> paramMap, Map<String, Object> model);

}

 

3. FrontController V4


@WebServlet(name = "FrontControllerServletV4", urlPatterns = "/front-controller/v4/*")
public class FrontControllerServletV4 extends HttpServlet {

    private Map<String, ControllerV4> controllerMap = new HashMap<>();

    public FrontControllerServletV4() {

        controllerMap.put("/front-controller/v4/members/new-form", new MemberFormControllerV4());
        controllerMap.put("/front-controller/v4/members/save", new MemberSaveControllerV4());
        controllerMap.put("/front-controller/v4/members", new MemberListControllerV4());
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        ControllerV4 controller = controllerMap.get(requestURI);
        if(controller == null){
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        Map<String, String> paramMap = createParamMap(request);
        Map<String, Object> model = new HashMap<>();
        String viewName = controller.process(paramMap, model);

        MyView view = viewResolver(viewName);

        //모델은 render에 넘겨줘야함.
        view.render(model, request,response);


    }

    private MyView viewResolver(String viewName) {
        return new MyView("/WEB-INF/views/" + viewName + ".jsp");
    }

    private Map<String, String> createParamMap(HttpServletRequest request) {
        //paramMap
        Map<String, String> paramMap = new HashMap<>();
        request.getParameterNames().asIterator()
                .forEachRemaining(paramName -> paramMap.put(paramName, request.getParameter(paramName)));
        return paramMap;
    }
}

 

4. MemberFromController V4


public class MemberFormControllerV4 implements ControllerV4 {


    @Override
    public String process(Map<String, String> paramMap, Map<String, Object> model) {
        return "new-form";
    }
}

 

5. MemberSaveController V4


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";
    }
}
  • model.put("member", member)
  • 모델이 파라미터로 전달되기 때문에, 모델을 직접 생성하지 않아도 된다.

 

6. MemberListController v4


public class MemberListControllerV4 implements ControllerV4 {

    private MemberRepository memberRepository = MemberRepository.getInstance();

    @Override
    public String process(Map<String, String> paramMap, Map<String, Object> model) {
        List<Member> members = memberRepository.findAll();

        model.put("members",members);

        return "members";
    }
}

 

 

7. 정리


  • 이번 버전의 컨트롤러는 매우 단순하고 실용적이다. 
  • 기존 구조에서 모델을 파라미터로 넘기고, 뷰의 논리 이름을 반환한다는 작은 아이디어를 적용했을 뿐인데, 
  • 컨트롤러를 구현하는 개발자 입장에서 보면 이제 군더더기 없는 코드를 작성할 수 있다.
  • 또한 중요한 사실은 여기까지 한번에 온 것이 아니라는 점이다. 
  • 프레임워크가 점진적으로 발전하는 과정속에서 이런 방법도 찾을 수 있었다.

 

 

8. GitHub : 210911 FrontController V4


 

GitHub - bsh6463/MVC1

Contribute to bsh6463/MVC1 development by creating an account on GitHub.

github.com

 

'인프런 > [인프런] 스프링 MVC 1' 카테고리의 다른 글

Controller V5 - 2  (0) 2021.09.12
Controller V5 -1  (0) 2021.09.11
Model 추가 : v3  (0) 2021.09.11
Controller->view이동 분리 : V2  (0) 2021.09.11
FrontController 도입 : v1  (0) 2021.09.10
Comments