본문으로 바로가기

[JSP개발] Controller 변경 - properties 적용

category 코딩/JSP 2016. 12. 6. 16:19







1. 개요







현재까지 포스팅에서 Controller는 if문으로 명령어를 처리하였다. 이번에는 이것을 프로퍼티 파일을 이용하는 방법으로 변경할 것이다. 이번 포스팅에서는 컨트롤러를 수정하고 프로퍼티 파일을 생성하였다. 그리고 단순한 화면전환을 처리하기 위해 MemberFormChangeAction 이라는 클래스를 생성하였다.



■ Java

  • MemberFormChangeAction.java : 화면전환을 처리하는 Action


 properties

  • 명령어와 Action 정보를 가지고 있는 설정 파일이다. jsp.member.properties 라는 패키지에 파일을 생성하였다.




2. 소스 코드





기존 Controller에서 위와 같이 복잡한 명령어 처리 부분을 수정할 것이다. 명령어(xxxx.do)와 그에 해당하는 Action은 모두 프로퍼티 파일에 입력할 것이다.



 MemberCommand.properties


[New] - [File]를 선택 후 이름을 확장자를 .properties 로 해서 파일을 만든다. 그리고 키=값의 구조로 작성을 한다. 키는 명령어(xxxx.do)이고 값은 Action이다. Action의 경우 패키지부터 클래스명까지 모두 적어야 한다. 참고로 프로퍼티에서 주석은 # 이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Form Change
MainForm.do=jsp.member.action.MemberFormChangeAction
LoginForm.do=jsp.member.action.MemberFormChangeAction
JoinForm.do=jsp.member.action.MemberFormChangeAction
UserInfoForm.do=jsp.member.action.MemberFormChangeAction
ModifyFrom.do=jsp.member.action.MemberFormChangeAction
DeleteForm.do=jsp.member.action.MemberFormChangeAction
ResultForm.do=jsp.member.action.MemberFormChangeAction
# Action
MemberLoginAction.do=jsp.member.action.MemberLoginAction
MemberLogoutAction.do=jsp.member.action.MemberLogoutAction
MemberJoinAction.do=jsp.member.action.MemberJoinAction
MemberInfoAction.do=jsp.member.action.MemberInfoAction
MemberModifyFormAction.do=jsp.member.action.MemberModifyFormAction
MemberModifyAction.do=jsp.member.action.MemberModifyAction
MemberDeleteAction.do=jsp.member.action.MemberDeleteAction
cs



 MemberController.java


Controller에서 if문 부분은 깔끔하게 삭제를 해준다. 그리고 서블릿에서 최초로 수행되는 init( ) 메서드를 추가한다. init( )이 실행되면 자동적으로 loadProperties( )가 실행되며 프로퍼티 파일을 읽어서 명령어에 해당하는 Action 객체를 생성한다. 그리고 명령어와 객체를 Map에 담는다.


실체 명령어를 처리하는 부분인 doProcess( )에서는 명령어와 Action이 담긴 Map을 이용한다. Map에서 Action을 가져와서 다음 처리를 하게된다.




init( ) 메서드를 추가한다. 이 메서드가 수행되면 loadProperties( ) 메서드를 실행시킨다. loadProperties( ) 메서드는 인수로 프로퍼티 파일의 경로를 입력받는다. 




명령어와 Action 객체를 담을 Map을 생성한다. 그리고 넘겨받은 프로퍼티 파일의 경로를 이용해서 프로퍼티 파일에서 키(명령어)를 추출한다.




명령어와 해당 Action의 클래스 이름을 문자열로 가져 온다.




가져온 클래스 이름으로 클래스를 생성하고, 그것을 이용해 객체를 생성한다.




단순한 화면전환인지 특정 작업의 처리인지 확인한다. 단순한 화면전환이라면 MemberFormChangeAction에 해당 명령어를 세팅한다. 그리고 Map에 명령어와 Action 객체를 담는다.




doProcess( )에서는 명령어를 이용하여 Map에서 Action 객체를 가져온다. 이때 Action이 null인 경우, 즉 명령어가 없는 경우 잘못된 명령어라는 메시지를 출력한다.




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
131
132
133
134
135
136
137
138
package jsp.member.action;
 
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.ResourceBundle;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 회원관련 Controller
 *
 */
public class MemberController extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private HashMap<String,Action> commandMap;
    
    /**
     * 최초 실행 init
     */
    public void init(ServletConfig config) throws ServletException {    
        loadProperties("jsp/member/properties/MemberCommand");
    }
    
    /**
     * GET 방식일 경우 doGet()
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
            doProcess(request,response);
    }      
        
    /**
     * POST 방식일 경우 doPost()
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
            doProcess(request,response);
    }                          
    
    /**
     * 프로퍼티 파일에서 키값과 클래스 정보를 추출하여 그것을 Map에 저장한다.
     * @param filePath 프로퍼티 파일의 경로
     */
    private void loadProperties(String filePath) 
    {
        commandMap = new HashMap<String, Action>();
        
        ResourceBundle rb = ResourceBundle.getBundle(filePath);
        Enumeration<String> actionEnum = rb.getKeys(); // 키값을 가져온다.
         
        while (actionEnum.hasMoreElements()) 
        {
            // 명령어를 가져온다.
            String command = actionEnum.nextElement(); 
            // 명령어에 해당하는 Action 클래스 이름을 가져온다.
            String className = rb.getString(command); 
            
            try {
                 Class actionClass = Class.forName(className); // 클래스 생성
                 Action actionInstance = (Action)actionClass.newInstance(); // 클래스의 객체를 생성
                 
                 // 화면전환 Action 인지 확인한다. 화면전환 Action이면 명령어를 전달한다.
                 if(className.equals("jsp.member.action.MemberFormChangeAction")){
                     MemberFormChangeAction mf = (MemberFormChangeAction)actionInstance;
                     mf.setCommand(command);
                 }
                 
                 // 맵에 명령어와 Action을 담는다.
                 commandMap.put(command, actionInstance);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * 명령어에 따른 해당 Action을 지정해 준다.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void doProcess(HttpServletRequest request, HttpServletResponse response) 
             throws ServletException, IOException {
        
        // 넘어온 커맨드를 추출하는 과정
        String requestURI = request.getRequestURI();
        int cmdIdx = requestURI.lastIndexOf("/")+1;
        String command = requestURI.substring(cmdIdx);
        
        // URI, command 확인
        //System.out.println("requestURI : "+requestURI);
        System.out.println("command : "+command);
        
        ActionForward forward = null;
        Action action = null;
        
        try {
            // 맵에서 명령어에 해당하는 Action을 가져온다.
            action = commandMap.get(command);
            
            if (action == null) {
                System.out.println("명령어 : "+command+"는 잘못된 명령입니다.");
                return;
            }
 
            forward = action.execute(request, response);
            
            /*
             * 화면이동 - isRedirext() 값에 따라 sendRedirect 또는 forward를 사용
             * sendRedirect : 새로운 페이지에서는 request와 response객체가 새롭게 생성된다.
             * forward : 현재 실행중인 페이지와 forwad에 의해 호출될 페이지는 request와 response 객체를 공유
             */
            if(forward != null){
                if (forward.isRedirect()) {
                    response.sendRedirect(forward.getNextPath());
                } else {
                    RequestDispatcher dispatcher = request
                            .getRequestDispatcher(forward.getNextPath());
                    dispatcher.forward(request, response);
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    } // end doProcess
}
 
cs



  MemberFormChangeAction.java


단순한 화면전환을 처리하기 위해 생성한 클래스이다. 




setCommand( )에서는 Controller에서 전달받은 명령어를 이용하여 다음으로 이동할 페이지를 생성한다. 우선 명령어에서 . 의 위치를 확인한다. 그리고 위치값을 이용해서 명령어에서 .do부분을 제거한 뒤 .jsp를 붙인다. 이렇게 처리한 것은 명령어와 JSP 파일의 이름이 같기 때문이다. 




Action의 수행 부분이다. 단순 화면전환 처리만 하므로 forward( )를 이용한다. 그래서 setRedirect(false)로 지정한다. 메인 화면의 경우만 전체 경로가 다르기 때문에 if문을 이용해서 다르게 처리한다.




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
package jsp.member.action;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 화면 전환을 처리하는 Action
 *
 */
public class MemberFormChangeAction implements Action
{
    private String form = "MainForm.jsp?contentPage=member/";
    private String path;
    
    /**
     * 명령어로부터 다음 이동할 페이지 경로를 생성한다.
     * @param command 명령어
     */
    public void setCommand(String command){
        int idx = command.indexOf(".");
        path = command.substring(0, idx)+".jsp";
    }
 
    @Override
    public ActionForward execute(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        ActionForward forward = new ActionForward();
        
        forward.setRedirect(false);
        
        // 메인화면일 경우 MainForm.jsp만 경로로 지정한다.
        if(path.equals("MainForm.jsp"))
            forward.setNextPath(path);
        else
            forward.setNextPath(form+path);
        
        return forward;
    }
}
 
cs




3. 소스코드 다운로드 (war 파일)


JSP_DEV.war




RSS구독 링크추가 트위터 이메일 구독