파일 구성 WebContent 안에 index.jsp 가 있어야 함
http://localhost:8088/JspProject/index.jsp를 사용하기 위해서 위치를 지정
다른 파일도 JspProject 뒤에 붙음
FrontController 에서 *.net으로 .net을 가지는 모든 파일을 처리함
doProcess에서 처리
Context 경로 뒤에 뭐가 오는지 확인
Command
이전 주소를 따라가기 위해서 forward.setRedirect(false) 로 주소 변경 없이
jsp 페이지의 내용을 유지
path로 어디로 갈지만 지정
DB를 갔다가 와야 하는 애들의 경우
action으로 처리
class를 만들어서 이름은 execute로 생성
인터페이스를 사용해서 오타나 오류를 막는 규격화를 함
frontControl
어떤 메소드를 사용할지도 알고 내가 처리할 주소가 뭔지 알기때문에
JoinProcessAction 을 생성
컨트롤러는 서블릿에서 만들고 보여주는 페이지는 mvc패턴
session은 항상 맞춰줘야 함
DAO는 DB랑 연결된 정보가 다 있음
MVC 패턴은 넘겨줄 값이 뭐고 넘길 값이 뭔지 반환형, 이름만 정하고 분업하기 위해서 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?xml version = "1.0" encoding = "UTF-8"?>
<Context>
<Resource
name ="jdbc/OracleDB"
auth = "Container"
type = "javax.sql.DataSource"
username ="scott"
password = "tiger"
driverClassName = "oracle.jdbc.driver.OracleDriver"
url = "jdbc:oracle:thin:@127.0.0.1:1521:xe"
maxTotal="500"
maxIdle="100"
/>
</Context>
Colored by Color Scripter
|
META-INF에 있는 context.xml
ch10 패키지를 만들고, 표준 규격을 맞추기 위해서 Interface인 Action을 만든다.
Interface Action
특정 비즈니스 요청으로 수행하고 결과 값을 ActionForward 타입으로 변환하는 메서드가 정의되어 있다.
Action : 인터페이스 명
ActionForward : 반환 형
1
2
3
4
5
6
7
8
9
10
11
|
package ch10;
public interface Action{
public ActionForward execute(HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
Colored by Color Scripter
|
데이터 빈 클래스 작성 (Member)
게시판에서 사용되는 정보들을 데이터 빈이라는 하나의 객체에 저장하게 되고 이 객체를 전달하면 각 정보를 하나씩 전달할 필요가 없으며 한꺼번에 모든 정보가 전달된다.
이런 클래스를 DTO(Data Transfer Object), VO(Value Object)라고 한다.
DB에서 만들었던 컬럼명과 동일하게 프로퍼티들을 생성한다.
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
|
package ch10;
public class Member {
private String id;
private String password;
private String name;
private int age ;
private String gender;
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Colored by Color Scripter
|
DAO(Data Acess Object) 클래스
- 데이터베이스와 연동하여 레코드의 추가, 수정, 삭제 작업이 이루어지는 클래스 입니다.
- 어떤 Action 클래스가 호출되더라도 그에 해당하는 데이터베이스 연동처리는 DAO 클래스에서 이루어지게 된다.
데이터 베이스를 담당하는 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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
|
package ch10;
public class MemberDAO {
DataSource ds;
Connection con;
PreparedStatement pstmt;
ResultSet rs;
ResultSet rs2;
int result;
public MemberDAO() {
try {
Context init = new InitialContext();
} catch (Exception ex) {
System.out.println("DB연결 실패 : " + ex);
return;
}
}
public int isId(String id) {
try {
con = ds.getConnection();
System.out.println("getConnection");
String sql = "select id from member where id = ? ";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
result = 0; // 등록된 id가 있습니다.
} else {
result = -1; // 등록된 id가 없습니다.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
if (pstmt != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
if (con != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
} // finally
return result;
}// isId end
public int insert(Member m) {
// TODO Auto-generated method stub
try {
con = ds.getConnection();
System.out.println("getConnection");
String sql = "insert into member values (?,?,?,?,?,?) ";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, m.getId());
pstmt.setString(2, m.getPassword());
pstmt.setString(3, m.getName());
pstmt.setInt(4, m.getAge());
pstmt.setString(5, m.getGender());
pstmt.setString(6, m.getEmail());
result = pstmt.executeUpdate();
if (result != 0) { // 있는지 없는지
result = 1; // 회원 가입 축하
} else {
result = -1; // 문제 발생
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
if (pstmt != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
if (con != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
} // finally
return result;
}
public int isId(String id, String pass) {
// TODO Auto-generated method stub
try {
con = ds.getConnection();
System.out.println("getConnection");
String sql = "select id, password from member where id = ? ";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
if (rs.getString(2).equals(pass)) {
result = 1; // 아이디 비번 일치
} else {
result = 0; // 비번 일치 X
}
} else {
result = -1; // 등록된 id가 없습니다.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
if (pstmt != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
if (con != null)
try {
} catch (SQLException ex) {
ex.printStackTrace();
}
} // finally
return result;
}
// 반환형 list
public Member member_info(String id) {
Member m = new Member();
try {
con = ds.getConnection();
System.out.println("getConnection");
String sql = "select * from member where id=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
m.setId(rs.getString(1));
m.setPassword(rs.getString(2));
m.setName(rs.getString(3));
m.setAge(rs.getInt(4));
m.setGender(rs.getString(5));
m.setEmail(rs.getString(6));
}
} catch (Exception e) {
System.out.println("memberinfo 에러");
e.printStackTrace();
}
return m;
}
public int member_update(Member m) {
try {
con = ds.getConnection();
System.out.println("getConnection");
String sql = "update member set name = ?, age = ?, gender = ?, email = ? where id=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, m.getName());
pstmt.setInt(2, m.getAge());
pstmt.setString(3, m.getGender());
pstmt.setString(4, m.getEmail());
pstmt.setString(5, m.getId());
result = pstmt.executeUpdate();
} catch (Exception e) {
System.out.println("memberinfo 에러");
e.printStackTrace();
}
return result;
}
public List<Member> getList() {
List<Member> list = new ArrayList<Member>();
try {
con = ds.getConnection();
System.out.println("getConnection");
String sql = "select * from member";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
Member m = new Member();
m.setId(rs.getString("id"));
m.setName(rs.getString(3));
list.add(m);
}
}catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public int member_delete(String id) {
try {
con = ds.getConnection();
System.out.println("getConnection");
String sql = "delete from member where id=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
result = pstmt.executeUpdate();
if(id.equals("admin")) {
result = -1;
}
} catch (Exception e) {
System.out.println("memberinfo 에러");
e.printStackTrace();
}
return result;
}
}
Colored by Color Scripter
|
ActionForward 클래스는 Action 인터페이스에서 명령을 수행하고 결과 값을 가지고 포워딩 할 때 사용되는 클래스이다.
이 클래스는 Redirect 여부 값과 포워딩할 페이지 위치를 가지고 있다.
이 값들은 FrontController에서 ActionForward 클래스 타입으로 반환 값을 가져오면 그 값을 확인하여 해당하는 요청 페이지로 포워딩 처리한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package ch10;
public class ActionForward {
private boolean redirect = false;
private String path = null;
//property redirect 의 is 메소드
public boolean isRedirect() {
//프로퍼티 타입이 boolean일 경우 get 대신 is를 앞에 붙일 수 있다.
return redirect;
}
//property redirect의 set 메소드
public String getPath() {
return path;
}
public void setPath(String string) {
this.path = string;
}
public void setRedirect(boolean b) {
this.redirect = b;
}
}
Colored by Color Scripter
|
FrontController
*.net으로 같은 주소 값을 가진 모든 페이지를 제어
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
|
package ch10;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
/**
* Servlet implementation class FrontController
*/
@WebServlet("*.net")
public class FrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FrontController() {
super();
// TODO Auto-generated constructor stub
}
/**
doProcess메서드르 구현하여 요청이 GET 방식이든
Post 방식으로 전송되어 오든 같은 메서드에서 요청을 처리할 수 있도록 하였다.
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doProcess(request, response);
}
private void doProcess(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
//ActionForward forward = null;
/*
요청된 전체 URL 중에서 포트 번호 다음부터 마지막 문자열까지 반환된다.
예) http://localhost:8088/JspProject/login.net인 경우 "/JspProject/login.net" 반환됩니다.
*/
String RequestURI = request.getRequestURI();
System.out.println("RequestURI = " + RequestURI);
//getContextPath()
//contextPath는 "/JspProject" 가 반환된다.
String contextPath = request.getContextPath();
System.out.println("contextPath = " + contextPath);
//RequestURI에서 컨텍스트 경로 길이 값의 인덱스 위치의 문자부터
//마지막 위치 문자까지 추출한다.
//command는 "/login.net"을 반환한다.
String command = RequestURI.substring(contextPath.length());
System.out.println("command = "+command);
//초기화
ActionForward forward = null;
Action action = null;
forward = new ActionForward();
//주소 변경없이 jsp 페이지의 내용을 보여준다.
forward.setRedirect(false);
forward.setPath("ch10_db/login.jsp");
}
forward = new ActionForward();
//주소 변경없이 jsp 페이지의 내용을 보여준다.
forward.setRedirect(false);
forward.setPath("ch10_db/join.jsp");
}
//forward = new ActionForward();
action = new JoinProcessAction();
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
}
//주소 변경없이 jsp 페이지의 내용을 보여준다.
//forward.setRedirect(false);
//forward.setPath("ch10_db/joinPoccess.jsp");
//forward = new ActionForward();
action = new loginProcessAction();
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
}
//forward = new ActionForward();
action = new Member_updateAction();
//
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
}
forward = new ActionForward();
//주소 변경없이 jsp 페이지의 내용을 보여준다.
forward.setRedirect(false);
forward.setPath("ch10_db/main.jsp");
action = new UpdateProcessAction();
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
}
action = new ListAction();
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
}
action = new Member_infoAction();
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
System.out.println("member_info로 못가는 중~");
}
action = new Member_deleteAction();
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
System.out.println("d_info로 못가는 중~");
}
action = new LogoutAction();
try {
forward=action.execute(request, response);
}catch(Exception e) {
e.printStackTrace();
System.out.println("logout_info로 못가는 중~");
}
}
//하단
if(forward != null) {// 페이지 처리
if(forward.isRedirect()) { // 리다이렉트 됩니다.
response.sendRedirect(forward.getPath());
}else {
RequestDispatcher dispatcher=
request.getRequestDispatcher(forward.getPath());
dispatcher.forward(request,response);
}
}
}//doProcess
//내가 페이지 하나 처리한 후에 다음에 어디갈지를 컨트롤러에서제어
//request 객체
}
Colored by Color Scripter
|
'IT > JSP' 카테고리의 다른 글
[JSP] 서블릿 생명주기 (0) | 2019.05.16 |
---|---|
[JSP] JSP 처리 과정 (0) | 2019.05.16 |
[JSP]회원가입 페이지 제어 (0) | 2019.05.15 |
[JSP] JDBC TEST 01 (0) | 2019.05.15 |
[JSP]context.xml (0) | 2019.05.15 |