개발자
[JSP 6일차] 서블릿페이지를 하나로 모으는 환경설정 본문
Frontcontroller 환경설정 클래스ㅇ
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
|
package common.controller;
import java.io.*;
import java.lang.reflect.Constructor;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(
description = "사용자가 웹에서 *up 을 했을 경우 이 서블릿이 응답을 해주도록 한다.",
urlPatterns = { "*.up" },
initParams = {
@WebInitParam(name = "propertyConfig", value = "C:/NCS/workspace(jsp)/MyMVC/src/main/webapp/WEB-INF/Command.properties", description = "*.up 에 대한 클래스의 매핑파일")
}) // \ 인식못해서 \\ 로써준다 또는 /로 써준다
public class FrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
private Map<String, Object> cmdMap = new HashMap<>(); //다형성
public void init(ServletConfig config) throws ServletException {
/*
웹브라우저 주소창에서 *.up 을 하면 FrontController 서블릿이 응대를 해오는데
맨 처음에 자동적으로 실행되어지는 메소드가 init(ServletConfig config) 이다.
여기서 중요한 것은 init(ServletConfig config) 메소드는 WAS(톰캣)가 구동되어진 후
딱 1번만 init(ServletConfig config) 메소드가 실행되어지고, 그 이후에는 실행이 되지 않는다.
그러므로 init(ServletConfig config) 메소드에는 FrontController 서블릿이 동작해야할 환경설정을 잡아주는데 사용된다.
*/
// *** 확인용 *** //
// System.out.println("~~~ 확인용 => 서블릿 FrontController 의 init(ServletConfig config) 메소드가 실행됨.");
String props = config.getInitParameter("propertyConfig");
//System.out.println("~~~ 확인용 props => " + props);
// ~~~ 확인용 props => C:/NCS/workspace(jsp)/MyMVC/src/main/webapp/WEB-INF/Command.properties
try {
FileInputStream fis = new FileInputStream(props);
// 특정 파일에 있는 내용을 읽어오기 위한 용도로 쓰이는 객체 exception 처리 필요
//C:/NCS/workspace(jsp)/MyMVC/src/main/webapp/WEB-INF/Command.properties 파일의 내용을 읽어오는데 사용되는 객체이다.
Properties pr = new Properties();
// Properties 는 Collection 중 HashMap 계열중의 하나로써
// "key","value"으로 이루어져 있는것이다.
// 그런데 중요한 것은 Properties 는 key도 String 타입이고, value도 String 타입만 가능하다는 것이다.
// key는 중복을 허락하지 않는다. value 값을 얻어오기 위해서는 key값만 알면 된다.
pr.load(fis);
//FileInputStream의 부모클래스가 InputStream 이다
/*
pr.load(fis); 은 fis 객체를 사용하여 C:/NCS/workspace(jsp)/MyMVC/WebContent/WEB-INF/Command.properties 파일의 내용을 읽어다가
Properties 클래스의 객체인 pr 에 로드시킨다.
그러면 pr 은 읽어온 파일(Command.properties)의 내용에서
= 을 기준으로 왼쪽은 key로 보고, 오른쪽은 value 로 인식한다.
공백있으면 안되는듯
*/
Enumeration<Object> en = pr.keys();
/*
pr.keys(); 은
C:/NCS/workspace(jsp)/MyMVC/WebContent/WEB-INF/Command.properties 파일의 내용물에서
= 을 기준으로 왼쪽에 있는 모든 key 들만 가져오는 것이다.
리턴타입 object
*/
while(en.hasMoreElements()) {
//엘리먼트가 있다면
String key = (String) en.nextElement();
//리턴타입 object니까 String 으로 캐스팅
/*
System.out.println("~~~ 확인용 key =>" + key);
~~~ 확인용 key =>/test/test2.up
~~~ 확인용 key =>/test1.up
*/
/*
* System.out.println("~~~ 확인용 value => " +pr.getProperty(key)); ~~~ 확인용 value
* => test.controller.Test2Controller ~~~ 확인용 value =>
* test.controller.Test1Controller
*/
String className = pr.getProperty(key);
if(className != null ) { className = className.trim(); //공백 제거
Class<?> cls = Class.forName(className); ////exception 처리 필요
// <?> 은 generic 인데 어떤 클래스 타입인지는 모르지만 하여튼 클래스 타입이 들어온다는 뜻이다.
// String 타입으로 되어진 className 을 클래스화 시켜주는 것이다.
// 주의할 점은 실제로 String 으로 되어져 있는 문자열이 클래스로 존재해야만 한다는 것이다.
Constructor<?> constrt = cls.getDeclaredConstructor();
// 생성자 만들기
Object obj = constrt.newInstance();
// 생성자로 부터 실제 객체(인스턴스)를 생성해주는 것이다.
/*
확인용 ###: Test2Controller 클래스의 기본생성자 호출됨
확인용 : Test1Controller 클래스의 기본생성자 호출됨
*/
cmdMap.put(key, obj); //key는 url(/test1.up) value값은 객체(test.controller.Test1Controller)를 map에 올려두었다
// cmdMap 에서 키값으로 Command.properties 파일에 저장되어진 url 을 주면
// cmdMap 에서 해당 클래스에 대한 객체(인스턴스)를 얻어오도록 만든 것이다.
}// end of if(className != null )
}//end of while -----------------------
} catch (FileNotFoundException e) {
System.out.println(">>>C:/NCS/workspace(jsp)/MyMVC/src/main/webapp/WEB-INF/Command.properties 파일이 존재하지 않습니다.<<<");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println(">>> 문자열로 명명되어진 클래스가 존재하지 않습니다. <<<");
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace(); //오류 이거맞나 확인필요
}
}// end of public void init(ServletConfig config) throws ServletException------------
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
requestProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
requestProcess(request, response);
}
private void requestProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 웹브라우저의 주소 입력창에서
// http://localhost:9090/MyMVC/member/idDuplicateCheck.up?userid=leess 와 같이 입력되었더라면
//String url = request.getRequestURL().toString(); //리턴타입 String 으로 바꿔주기
//System.out.println("~~~ 확인용 url => " + url);
//~~~ 확인용 url => http://localhost:9090/MyMVC/member/idDuplicateCheck.up
// 웹브라우저의 주소 입력창에서
// http://localhost:9090/MyMVC/member/idDuplicateCheck.up?userid=leess 와 같이 입력되었더라면
String uri = request.getRequestURI();
//System.out.println("~~~ 확인용 uri => " + uri);
//~~~ 확인용 uri => /MyMVC/member/idDuplicateCheck.up
//~~~ 확인용 uri => /MyMVC/test1.up
//~~~ 확인용 uri => /MyMVC/test/test2.up
String key = uri.substring(request.getContextPath().length()); // /MyMVC
/* request.getContextPath().length(); ==> 6 이다.
/member/idDuplicateCheck.up
/test1.up
/test/test2.up
*/
AbstractController action = (AbstractController) cmdMap.get(key);
if(action == null) {
System.out.println(">>> "+ key +" 은 URI 패턴에 매핑된 클래스가 없습니다. <<<");
// >>> /member/idDuplicateCheck.up 은 URI 패턴에 매핑된 클래스가 없습니다. <<<
}
else {
try {
// 필터의 로직을 작성하는 메소드
// ==> doPost()에서 한글이 안 깨지려면
// request.getParameter("name"); 을 하기전에
// request.setCharacterEncoding("UTF-8"); 을
// 먼저 해주어야 한다.
request.setCharacterEncoding("UTF-8");
action.execute(request, response);
boolean bool = action.isRedirect();
String viewPage = action.getVwPage();
if(!bool) {
// viewPage 에 명기된 view단 페이지로 forward(dispatcher)를 하겠다는 말이다.
// forward 되어지면 웹브라우저의 URL주소 변경되지 않고 그대로 이면서 화면에 보여지는 내용은 forward 되어지는 jsp 파일이다.
// 또한 forward 방식은 forward 되어지는 페이지로 데이터를 전달할 수 있다는 것이다.
if(viewPage != null) {
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
dispatcher.forward(request, response);
}
}
else {
// viewPage 에 명기된 주소로 sendRedirect(웹브라우저의 URL주소 변경됨)를 하겠다는 말이다.
// 즉, 단순히 페이지이동을 하겠다는 말이다.
// 암기할 내용은 sendRedirect 방식은 sendRedirect 되어지는 페이지로 데이터를 전달할 수가 없다는 것이다.
if(viewPage != null) {
response.sendRedirect(viewPage);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} //클래스가 있다면
}// end of private void requestProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
|
cs |
AbstractController
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
|
package common.controller;
public abstract class AbstractController implements InterCommand {
/*
=== 다음의 나오는 것은 우리끼리한 약속이다. ===
※ view 단 페이지(.jsp)로 이동시 forward 방법(dispatcher)으로 이동시키고자 한다라면
자식클래스에서는 부모클래스에서 생성해둔 메소드 호출시 아래와 같이 하면 되게끔 한다.
super.setRedirect(false);
super.setViewPage("/WEB-INF/index.jsp");
※ URL 주소를 변경하여 페이지 이동시키고자 한다라면
즉, sendRedirect 를 하고자 한다라면
자식클래스에서는 부모클래스에서 생성해둔 메소드 호출시 아래와 같이 하면 되게끔 한다.
super.setRedirect(true);
super.setViewPage("registerMember.up");
*/
private boolean isRedirect = false;
// isRedirect 변수의 값이 false 이라면 view단 페이지(.jsp)로 forward 방법(dispatcher)으로 이동시키겠다.
// isRedirect 변수의 값이 true 이라면 sendRedirect 로 페이지이동을 시키겠다.
private String viewPage;
// viewPage 는 isRedirect 값이 false 이라면 view단 페이지(.jsp)의 경로명 이고,
// isRedirect 값이 true 이라면 이동해야할 페이지 URL 주소 이다.
public boolean isRedirect() {
return isRedirect;
}
public void setRedirect(boolean isRedirect) {
this.isRedirect = isRedirect;
}
public String getVwPage() {
return viewPage;
}
public void setViewPage(String viewPage) {
this.viewPage = viewPage;
}
////////////////////////////////////////////////////////////////////////
}
|
cs |
command properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# index Mapping Information
/test1.up =test.controller.Test1Controller
/test/test2.up =test.controller.Test2Controller
/template.up = test.controller.TemplateController
#########################################################
/= common.controller.IndexController
/index.up = common.controller.IndexController
/error.up= common.controller.ErrorController
#########################################################
# member Mapping Information
/member/memberRegister.up = member.controller.MemberRegister
/member/idDuplicateCheck.up=member.controller.IdDuplicateCheck
|
cs |
Test1Controller
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
|
package test.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import common.controller.AbstractController;
public class Test1Controller extends AbstractController {
/*
* public Test1Controller() {
* System.out.println("확인용 : Test1Controller 클래스의 기본생성자 호출됨");
* 기본생성자는 없애도 생략되어져있는것임
* }
*/
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setAttribute("name", "최지희");
// super.setRedirect(flase); //flase면 forward 방식 (우리끼리 약속) default가 false니까 안써준것뿐
super.setViewPage("/WEB-INF/test/test1.jsp");
}
}
|
cs |
Test2Controller
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 test.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import common.controller.AbstractController;
public class Test2Controller extends AbstractController{
/*
* public Test2Controller() {
* System.out.println("확인용 ###: Test2Controller 클래스의 기본생성자 호출됨"); }
*/
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
super.setRedirect(true); //우리ㅣ끼리 한 약속인 sendRedirect 을 하겠다는 말이다
super.setViewPage(request.getContextPath() + "/test1.up");
}
}
|
cs |
/test1.up = test.controller.Yest1Controller
키값 벨류값
/test/test2.up = test.controller.Yest2Controller
/test/test2.up 의 키값을 입력하면 test.controller.Yest2Controller 가 응답한다
http://localhost:9090/MyMVC/test1.up 입력 => http://localhost:9090/MyMVC/test1.up/test.controller.Yest2Controller 가 나온다
MyMVC가 컨택스트패스명 된다
1.서블릿만들어서
2.설명 사용자가 웹에서 *up 을 했을 경우 이 서블릿이 응답을 해주도록 한다.
name 추가, value에 Command.properties파일 있는 경로로 추가
C:\NCS\workspace(jsp)\MyMVC\src\main\webapp\WEB-INF\Command.properties
*.up 에 대한 클래스의 매핑파일
3.init 체크
/template.up = test.controller.TemplateController
URL 이패키지의 이 클래스
'개발자 > JSP' 카테고리의 다른 글
[JSP 9일차]회원가입/prop/show/hide/focus/select (0) | 2022.09.15 |
---|---|
[jsp 8일차]암호화 (0) | 2022.09.10 |
[JSP 5일차] Oracle과 연동2 (0) | 2022.09.02 |
[JSP 4일차]fmt/Oracle과 연동/ (0) | 2022.09.01 |
[JSP 3일차]태그 라이브러리 /< c:choose>/<c:forEach>/forTokens (0) | 2022.08.31 |