Jsp-MVC2-FrontController

2020. 8. 10. 19:41JSP-MVC model2

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package controller;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import action.Action;
import action.BoardListAction;
import action.BoardWriteProAction;
import vo.ActionForward;
 
// URL 에 요청된 서블릿 주소가 XXX.bo 로 끝날 경우
// 해당 주소를 서블릿 클래스인 BoardFrontController 클래스로 연결(매핑)
@WebServlet("*.bo")
public class BoardFrontController extends HttpServlet {
    // 서블릿 클래스 정의 시 HttpServlet 클래스를 상속받아 정의
    // GET 방식 요청, POST 방식 요청에 해당하는 doGet(), doPost() 메서드 오버라이딩
    // => 두 방식을 공통으로 처리하기 위해 doProcess() 메서드를 별도로 정의하여 호출
    protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("BoardFrontController");
        
        // POST 방식 요청에 대한 한글 처리
        request.setCharacterEncoding("UTF-8");
        
        // 요청 URL 에 대한 판별
        // 1. 요청 URL 중 서버 주소와 포트번호를 제외한 프로젝트명/서블릿주소 부분 추출
//        String requestURI = request.getRequestURI();
//        System.out.println("Requsted URI : " + requestURI);
        
        // 2. 요청 URL 중 프로젝트명 부분 추출
//        String contextPath = request.getContextPath();
//        System.out.println("Context Path : " + contextPath);
        
        // 3. 1번과 2번 문자열을 사용하여 서블릿주소 부분 추출
        // => 프로젝트명 문자열 길이에 해당하는 부분부터 마지막까지 추출
//        String command = requestURI.substring(contextPath.length());
//        System.out.println("Command : " + command);        
        // ===============================================================
        // 위의 1 ~ 3번 과정을 결합한 메서드 : getServletPath()
        String command = request.getServletPath();
        System.out.println("Command : " + command);    
        
        // 여러 객체(XXXAction)를 동일한 타입으로 다루기 위한 변수 선언
        Action action = null;
        ActionForward forward = null;
        
        // 추출된 서블릿 주소에 따라 각각 다른 작업을 수행하도록 제어
        if(command.equals("/Main.bo")) {
            forward=new ActionForward();
            forward.setPath("index.jsp");
        }else if(command.equals("/BoardWriteForm.bo")) {
            // 글쓰기 폼을 위한 View 페이지(JSP) 요청은
            // 별도의 비즈니스 로직(Model) 없이 JSP 페이지로 바로 연결
            // => 이 때, JSP 페이지의 URL 이 노출되지 않아야하며
            //    또한, request 객체가 유지되어야 하므로 Dispatch 방식으로 포워딩
            // 따라서, ActionForward 객체를 생성하고 URL 전달 및 포워딩 타입 false 로 지정
            forward = new ActionForward();
            forward.setPath("/board/qna_board_write.jsp");
//            forward.setRedirect(false); // 생략 가능(기본값 false)
        } else if(command.equals("/BoardWritePro.bo")) {
            //글쓰기 비즈니스 로직을 위한 Action 클래스 인스턴스 생성
            // BoardWriteProAction 클래스 인스턴스 생성 및 공통 메서드 execute() 호출
            // 로직 수행 후 ActionForward 객체를 리턴받아 포워딩 작업 수행
            action = new BoardWriteProAction();
            try {
                forward = action.execute(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(command.equals("/BoardList.bo")) {
            //글목록 요청 비즈니스 로직을 위한 Action 클래스 인스턴스 생성
            // -> BoardListAction 클래스 인스턴스 생성 및 공통 메서드 execute() 호출
            // 로직 수행 후 ActionForward 객체를 리턴받아 포워딩 작업 수행
            action=new BoardListAction();
            try {
                forward=action.execute(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
        
        
        // ----------------------------------------------------------------------
        // Redirect 방식과 Dispatch 방식에 대한 포워딩(이동)을 처리하기 위한 영역
        // 1. ActionForward 객체가 null 이 아닐 때만 포워딩 작업을 수행하도록 판별
        if(forward != null) {
            // 2. ActionForward 객체가 null 이 아닐 때 Redirect 방식 여부 판별
            if(forward.isRedirect()) { // Redirect 방식일 경우
                // response 객체의 sendRedirect() 메서드를 호출하여
                // ActionForward 객체에 저장되어 있는 URL 정보 전달
                response.sendRedirect(forward.getPath());
            } else { // Dispatch 방식일 경우
                // 1) RequestDispatcher 객체를 리턴받기 위해 
                //    request 객체의 getRequestDispatcher() 메서드를 호출
                //    => 파라미터로 ActionForward 객체에 저장되어 있는 URL 정보 전달
                RequestDispatcher dispatcher = 
                        request.getRequestDispatcher(forward.getPath());
                
                // 2) RequestDispatcher 객체의 forward() 메서드를 호출하여
                //    전달된 URL 로 포워딩
                //    => 파라미터로 request 객체와 response 객체 전달
                dispatcher.forward(request, response);
            }
        }
        // ----------------------------------------------------------------------
        
    }
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET 방식 요청에 의해 doGet() 메서드가 호출되면 doProcess() 메서드를 호출하여
        // request 객체와 response 객체를 파라미터로 전달
        doProcess(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // POST 방식 요청에 의해 doPost() 메서드가 호출되면 doProcess() 메서드를 호출하여
        // request 객체와 response 객체를 파라미터로 전달
        doProcess(request, response);
    }
    
 
}
 
 
cs

 

서블릿 파일을 만들고 처음 생성되는 doGet, doPost는 doProcess(request, response)만 선언해 두고 더 이상 다루지 않는다. 그리고 doProcess메서드 안에서 모든 것을 다루는데 Controller에서는 크게 다루는 게 없이 주소 값을 인식해서 주소를 지정해주고 페이지의 이동 방식을 두 가지로 나눠서 어떤 방식으로 넘겨줄지 정해주는 역할만 해준다고 생각하면 된다. 아직 게시판의 Form부분과  Pro 부분, List를 보는 부분까지만 다뤄보았지만 다른 기능이 추가되어도 주소 값을 if로 판별한 후 이동을 정해주는 방식만 추가될 뿐 다르게 다루는 것은 없다.

'JSP-MVC model2' 카테고리의 다른 글

Jsp-MVC2 -DAO  (0) 2020.08.10
Jsp -MVC2- Action,ActionForward  (0) 2020.08.10
Jsp-MVC2,Connection Pool  (0) 2020.08.10
Jsp - MVC2, path 얻기,web.xml  (0) 2020.08.04
Jsp - MVC model2,MVC2  (0) 2020.08.04