20.03 ~ 20.08 국비교육/JSP

MVC 모델2 - 4. Front Controller, Command, DAO

찹키리 2020. 6. 17. 12:32

<Front Controller>

 

 

-매핑 클래스

명령어 : 액션 클래스 매핑

 

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
package my.controller;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import my.action.CommandAction;
public class ControllerAction extends HttpServlet {
    private Map commandMap = new HashMap();
 //명령어와 명령어 처리 클래스를 쌍으로 지정
    //Map -> 무언가를 저장할 때 사용
    @Override
    public void init(ServletConfig config) throws ServletException {
    //init: 처음 1회는 무조건 실행되는 메소드
        
        String path = config.getServletContext().getRealPath("/");
        //서블릿 실제 경로
        String props = config.getInitParameter("propertyConfig");
        //서블릿 정보
        Properties pr = new Properties();
        FileInputStream f = null;
        //파일을 읽어오는 객체
        try {
        f = new FileInputStream(path + props);
        //경로, action클래스를
        pr.load(f);
        //f로 읽어와 properties에 저장
        } catch(IOException e) {
        throw new ServletException(e);
        } finally {
        if(f != nulltry {f.close();} catch(IOException ex) {}
        }
        Iterator keyIter = pr.keySet().iterator();
        //반복자
        while(keyIter.hasNext()) {
        String command = (String)keyIter.next();
        //경로 -> command에 담음
        String className = pr.getProperty(command);
        //액션클래스 -> className에 담음
        try {
        Class commandClass = Class.forName(className);
        //동적으로 클래스 로딩(소스를 메모리 상에 로딩)
        Object commandInstance = commandClass.newInstance();
        //인스턴스화, object로 받는다.
        commandMap.put(command, commandInstance);
        //맵에 저장
        } catch(ClassNotFoundException e) {
        throw new ServletException(e);
        } catch(InstantiationException e) {
        throw new ServletException(e);
        } catch(IllegalAccessException e) {
        throw new ServletException(e);
        }
    }
}
 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
    public void doGet( //get방식의 서비스 메소드
            HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException { 
        execute(request, response);
    }
    
    protected void doPost( //post방식의 서비스 메소드
            HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        execute(request, response);
    }
    

 

 

 

-작업 처리 클래스

액션 클래스에서 처리한 작업을 가져와 view페이지로 forward

 

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
    //사용자의 요청을 분석해서 해당 작업을 처리
    private void execute
        (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String view = null;
        CommandAction com = null;
        
        try {
            String command = request.getRequestURI();
            
            //if(command.indexOr(request.getcontextPath()) -- 0 {
            //    command = command.substring
            //        (request.getContextPath().length());
            //    System.out.println(command);
            //}
            
            System.out.println(command);
            com = (CommandAction) commandMap.get(command);
            //오버라이딩 된 해당 action 객체
            view = com.requestPro(request, response);
            //액션에서 돌아오는 msg를 view로 받음
            System.out.println(view);
        } catch(Throwable e) {
            throw new ServletException(e);
        }
    RequestDispatcher dispatcher = request.getRequestDispatcher(view);
        //이동객체 -> view가 목적지
        dispatcher.forward(request, response);
        //forward한다.
    }
}
 

 

 

 

 

 

<Command>

 

 

 

1
2
3
4
5
6
7
8
9
10
package my.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
    //요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스
    public interface CommandAction {
        public String requestPro(HttpServletRequest request,
                HttpServletResponse response) throws Throwable;
    }

 

액션 클래스를 인터페이스로 정의해 기능별로 오버라이딩해 사용한다.

 

 

 

 

 

<DAO>

 

 

 

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
package my.board;
 
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
 
public class BoardDBBean {
    private static BoardDBBean instance = new BoardDBBean();
    public static BoardDBBean getInstance() {
        return instance;
    } //자기자신 객체를 반환
    
    private BoardDBBean() {
        
    } //기본 생성자
    
    private Connection getConnection() throws Exception {
    //원래는 public이어야 하는데...
        Context initCtx = new InitialContext();
        Context envCtx = (Context)initCtx.lookup("java:comp/env");
        //java component 환경변수 중에서 찾아라
        DataSource ds = (DataSource)envCtx.lookup("jdbc/oracle");
        //리소스 이름이 jdbc/oracle로 되어있는 객체를
        return ds.getConnection();
        //Connection 반환
    }
 
    //이 아래에 멤버 메소드를 정의한다.

'20.03 ~ 20.08 국비교육 > JSP' 카테고리의 다른 글

MVC 모델2 - 6. 글 목록(List)  (0) 2020.06.19
MVC 모델2 - 5. 글쓰기(Write)  (0) 2020.06.17
MVC 모델2 - 2. 작동 원리, 매핑(Mapping)  (0) 2020.06.03
MVC 모델2 - 1. Server Pool 생성  (0) 2020.06.02
파일 업로드  (0) 2020.05.06