이전까지 블로그에 포스팅한 예제들은 단순히 Servlet 파일로 요청을 보내고, DAO 에 의해 DB에 접근, VO 로 값을 전달, jsp 로 응답을 전달하여 보여주는 방식을 사용하였다.
이런 웹 어플리케이션의 구성 방식은 최초 구성 방식은 간편할지 모르나, 이후의 유지보수 및 추가가 진행될 수록 복잡해진다.
이에 대해 디자인 패턴 중 MVC 패턴이 있으나, 우선 MVC2 패턴을 소개한 후 이후에 따로 포스팅 하겠다.
1. Controller : 클라이언트의 모든 요청을 받아 처리하는 부분. servlet 파일로 작성된다
2. View : 요청에 대한 데이터 등을 받아 클라이언트에게 응답을 전달하는 부분, Jsp 파일로 구성된다.
3. Model : 요청에 대한 DB 접근, 연산 등의 복잡한 동작을 처리하는 부분, class 파일로 작성되어, controller 부분에서 객체로 생성되어 값을 반환함
※ 코드 구현부 예시(view는 생략)
controller
- controller 부분의 servlet 파일은 단순히 경로의 이동을 맡으며, 요청은 url 의 쿼리 스트링을 이용, 해당 쿼리 스트링에 대응 되는 요청은 controller의 다른 부분이 되는 class 파일의 아래의 메소드와 같이 결정된다.
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 | public Action getAction(String command) { Action action = null; System.out.println("AF : "+command); if(command.equals("board_list")) { action = new BoardListAction(); }else if(command.equals("board_write_form")) { action = new BoardWriteFormAction(); } else if(command.equals("board_write")) { action = new BoardWriteAction(); } else if(command.equals("board_view")) { action = new BoardViewAction(); } else if(command.equals("board_check_pass_form")) { action = new BoardCheckPassFormAction(); } else if(command.equals("board_check_pass")) { action = new BoardCheckPassAction(); } else if(command.equals("board_update_form")) { action = new BoardUpdateFormAction(); } else if(command.equals("board_update")) { action = new BoardUpdateAction(); } else if(command.equals("board_delete")) { action = new BoardDeleteAction(); } return action; } | cs |
-실제 동작은 아래의 코드와 같이 동작된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String command = request.getParameter("command"); // 요청을 쿼리 스트링으로 받음 if(command==null) command = "board_list"; //default 경로 System.out.println("요청 : "+command); ActionFactory af = ActionFactory.getInstance(); // controller 부분의 처리는 하나의 객체만 처리 : 싱글톤 Action action = af.getAction(command); if(action != null) { action.excute(request, response); // model 객체 수행 } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); doGet(request, response); } | cs |
- servlet 파일에서 요청을 받아 해당 요청에 따른 model 의 객체를 class 파일에 따라 생성
- 생성된 객체는 메소드에 의해 실행된다.
model
1 2 3 4 5 6 7 8 9 10 11 12 13 | package com.seayon.controller.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.rowset.serial.SerialException; public interface Action { public void excute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException; } | cs |
- 모든 model class는 위의 인터페이스를 상속 받는다.
- reqest, response 객체의 사용을 위함이며, controller 부분에서 중복 코드의 작성을 줄이기 위함이다.
- 각 model 클래스의 작성은 이전 예제의 servlet 파일의 작성과 동일하다.
댓글
댓글 쓰기