상세 컨텐츠

본문 제목

MVC 패턴(Model1, Model2)

WebProgramming/JSP

by ChrisMare 2018. 10. 29. 05:20

본문

MVC

Model, View, Controller 를 뜻하는 용어로 개발 형태의 일종을 말한다.


Model은 데이터베이스와의 관계를 담당

클라이언트의 요청에서 필요한 자료를 데이터베이스로부터 추출하거나, 수정하여 Controller로 전달 한다.

View는 사용자한테 보여지는 UI 화면

주로 .jsp파일로 작성 하며, Controller에서 어떤 View 컴포넌트를 보여줄지 결정 한다.

Controller는 Model, View를 지시 및 전달 담당

클라이언트의 요청을 받고, 절적한 Model에 지시를 내리며, Model에서 전달된 데이터를 적절한 View에 전달 한다.

이렇게 작업을 분할하면, 추후 유지보에서 좋다.



MVC1 Pattern

MVC에서 View와 Controller 가 같이 있는 형태이다. ( 규모가 작고 유지보수 보단 빨리 개발할 때 사용. )

하지만 이러한 로직은 추후 유지보수시 Controller와 View와 같이 있다보니 소스가 지저분하고 고치기에 다소 걸리고 

동료가 하던 것을 넘겨받아서 유지보수를 할 시 에는 소스보기에도 힘든 면이 있고 분석하고 다시 고치기에 시간이 걸립니다.


MVC2 Pattern

MVC에서 Model, View, Controller 가 모두 모듈화 되어 있는 형태이다. ( 규모가 크고 추후 유지보수 시 개발이 자주 일어날 수 있는 경우에 사용. )

* 모듈화 : 소프트웨어를 부품화 시킨다는 개념.

예를들어, 모든 소스가 한곳에 다 적혀서 만들어진 웹 어플리케이션이라면 추후 유지보수 시 찾는 것도 힘들고 재활용하기에도 힘들것 입니다. 하지만, 모듈화를 한다면 DB관련 따로 View화면 따로, 이 두개를 관리하는 곳도 따로 관리한다면 유지보수시 에러가 난 곳을 쉽게 찾아가서 수정가능하고 업데이트 시에도 해당 파일만 건드리면 되기에 유지보수가 쉽습니다.


사용자 화면에 데이터가 필요한 과정이라면 이러한 로직이 수행될 것입니다.

또한, View 단이 꼭 jsp로 하는 것은 아니지만, 표현하기 쉽기 때문에 jsp파일로 많이 표현합니다.

그리고 Model 역시 java 파일로 많이 표현합니다.


Model1 과 Model2에서 작업속도는 Model1 이 더 빠를 수 있겠지만, 추후 시간이 흐르고 프로젝트가 커졌을 경우 유지보수 및 관리 측면에서 Model2 방식이 효율이 훨씬 뛰어날것입니다.



전체적인 컴포넌트 설계


MVC로 간단한 게시판 프로그램을 만들어 보자

게시판 프로그램에 앞서 DB부터 만들자.


1. mvc_board Table 생성

1
2
3
4
5
6
7
8
9
10
11
create table mvc_board(
    bId        number(4primary key,
    bName        varchar2(20),
    bTitle        varchar2(100),
    bContent        varchar2(300),
    bDate        date default sysdate,
    bHit        number(4default 0,
    bGroup        number(4),
    bStep        number(4),
    bIndent        number(4)
);
cs

1
create sequence mvc_board_seq;
cs
sequence 사용 이유는 bId값이 유니크하며 자동으로 증가시키기 위해서 만들었습니다.


2. 테스트를 위한 Dummy Data 입력

1
2
insert into mvc_board(bId, bName, bTitle, bContent, bHit, bGroup, bStep, bIndent) 
values (mvc_board_seq.nextval, '관리자''글 제목''글 내용'0, mvc_board_seq.currval, 00);
cs



* list.do 생성 로직을 예로 보여 줬지만, 모든 로직이 MVC 패턴으로 모듈화하였기 때문에,

로직에는 큰 차이가 없을 것입니다.



3. FrontController 만들기

클라이언트의 요청을 받는 역할을 하는 Controller를 만든다. (BFrontController)


패키지 : com.mvc_board.ex.frontcontroller

클래스명 : BFrontController


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
package com.mvc_board.ex.frontcontroller;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.Character.Subset;
 
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 com.mvc_board.ex.command.*;
 
/**
 * Servlet implementation class BFrontController
 */
// url 패턴 중 확장자 패턴으로 받고 있다.
@WebServlet("*.do")
public class BFrontController extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BFrontController() {
        super();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doGet");
        doAction(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doPost");
        doAction(request, response);
    }
 
    private void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doAction");
        
        request.setCharacterEncoding("EUC-KR");    // 한글 깨짐 처리
        
        String viewPage = null;    // 어떤 View 페이지로 보여줄지를 담는 변수
        // 웹에서 어떤 로직을 수행할지를 결정해주는 Command객체 -> 유지보수 및 관리를 위한 분산 처리
        // 동일한 BCommand 라는 인터페이스를 이용하여 동일한 메소드를 통해 각자 알맞은 로직을 수행하게 만들기위한 객체.
        BCommand command = null;
        
        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String commandName = viewPage.substring(contextPath.length());
        
        // 웹페이지 글 쓰기 화면
        if(commandName.equals("/write_view.do")) {
            viewPage = "write_view.jsp";
        }else if(commandName.equals("/write.do")) {
            /* 웹페이지 글 작성 화면
             * 'write.do' 요청이 들어오면 해당
             *  command를 생성하여 적절한 로직을 
             *  수행한 후 'list.do' 페이지로 포워딩. 
             */    
            command = new BWriteCommand();
            command.execute(request, response);
            viewPage = "list.do";
        }else if(commandName.equals("/list.do")) {
            command = new BListCommand();
            command.execute(request, response);
            viewPage = "list.jsp";
        }else if(commandName.equals("/content_view.do")) {
            command = new BContentCommand();
            command.execute(request, response);
            viewPage = "content_view.jsp";
        }else if(commandName.equals("/modify.do")) {
            command = new BModifyCommand();
            command.execute(request, response);
            viewPage = "list.do";
        }else if(commandName.equals("/delete.do")) {
            command = new BDeleteCommand();
            command.execute(request, response);
            viewPage = "list.do";
        }else if(commandName.equals("/reply_view.do")) {
            command = new BReplyViewCommand();
            command.execute(request, response);
            viewPage = "reply_view.jsp";
        }else if(commandName.equals("/reply.do")) {
            command = new BReplyCommand();
            command.execute(request, response);
            viewPage = "list.do";
        }else {
            System.out.println("해당 Command 로직이 없습니다.");
            viewPage = "notCommand.jsp";
        }
        
        // RequestDispatcher 객체에다가 어떤 View 페이지로 보낼지 맵핑할 곳을 담는다.
        RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
        // 해당 페이지로 포워딩해준다. --> *.do로 받으면 다시 BFrontController로 가서 로직 수행.
        // .jsp 로 받으면 해당 View로 화면을 보여준다.
        dispatcher.forward(request, response);
        
    }
 
}
 
cs


4. Command 만들기

웹에서 어떤 로직을 수행할지를 결정해주는 Command객체 -> 유지보수 및 관리를 위한 분산 처리

동일한 BCommand 라는 인터페이스를 이용하여 동일한 메소드를 통해 각자 알맞은 로직을 수행하게 만들기위한 객체.

이를 통해 해당 로직만 검사하기 때문에 로직을 수행하고 관리하기 편해진다.


패키지 : com.mvc_board.ex.command;

인터페이스명 : BCommand


1
2
3
4
5
6
7
8
9
package com.mvc_board.ex.command;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public interface BCommand {
    void execute(HttpServletRequest request, HttpServletResponse response );
}
 
cs


BCommand를 구현해서 해당 알맞은 로직을 수행하는 Command 객체들


BListCommand.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.mvc_board.ex.command;
 
import java.util.ArrayList;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mvc_board.ex.dao.BDao;
import com.mvc_board.ex.dto.BDto;
 
public class BListCommand implements BCommand {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        BDao dao = new BDao();
        ArrayList<BDto> dtos = dao.list();
        request.setAttribute("list", dtos);
    }
 
}
 
cs


BWriteCommand.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.mvc_board.ex.command;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mvc_board.ex.dao.BDao;
 
public class BWriteCommand implements BCommand {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        
        String bName = request.getParameter("bId");
        String bTitle = request.getParameter("bTitle");
        String bContent = request.getParameter("bContent");        
 
        BDao dao = new BDao();
        dao.write(bName, bTitle, bContent);
        
    }
 
}
 
cs


BContentCommand.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.mvc_board.ex.command;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mvc_board.ex.dao.BDao;
import com.mvc_board.ex.dto.BDto;
 
public class BContentCommand implements BCommand {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        
        BDao dao = new BDao();
        BDto dto = dao.contentView(request.getParameter("bId"));
        
        request.setAttribute("content_view", dto);
    }
 
}
 
cs


BModifyCommand.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.mvc_board.ex.command;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mvc_board.ex.dao.BDao;
 
public class BModifyCommand implements BCommand {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        String bId = request.getParameter("bId");
        String bName = request.getParameter("bName");
        String bTitle = request.getParameter("bTitle");
        String bContent = request.getParameter("bContent");
        
        BDao dao = new BDao();
        dao.modify(bId, bName, bTitle, bContent);
    }
 
}
 
cs


BDeleteCommand.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.mvc_board.ex.command;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mvc_board.ex.dao.BDao;
 
public class BDeleteCommand implements BCommand {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        BDao dao = new BDao();
        dao.delete(request.getParameter("bId"));
    }
 
}
 
cs


BReplyViewCommand.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.mvc_board.ex.command;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mvc_board.ex.dao.BDao;
import com.mvc_board.ex.dto.BDto;
 
public class BReplyViewCommand implements BCommand {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        String bId = request.getParameter("bId");
        BDao dao = new BDao();
        BDto dto = dao.reply_view(bId);
        
        request.setAttribute("reply_view", dto);
    }
 
}
 
cs


BReplyCommand.java

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
package com.mvc_board.ex.command;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.mvc_board.ex.dao.BDao;
 
public class BReplyCommand implements BCommand {
 
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        // Form 속에 있는 값을 가져온다.
        String bId = request.getParameter("bId");
        String bName = request.getParameter("bName");
        String bTitle = request.getParameter("bTitle");
        String bContent = request.getParameter("bContent");
        String bGroup = request.getParameter("bGroup");
        String bStep = request.getParameter("bStep");
        String bIndent = request.getParameter("bIndent");
        
        BDao dao = new BDao();
        dao.reply(bId, bName, bTitle, bContent, bGroup, bStep, bIndent);
    }
 
}
 
cs

5. DTO(Data Transfer Object) 만들기

알맞은 Data를 관리하는 DTO 객체를 만듭니다.


패키지 : com.mvc_board.ex.dto;

인터페이스명 : BDto


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
package com.mvc_board.ex.dto;
 
import java.sql.Timestamp;
 
public class BDto {
    
    // member data
    private int bId;
    private String bName;
    private String bTitle;
    private String bContent;
    private Timestamp bDate;
    private int bHit;
    private int bGroup;
    private int bStep;
    private int bIndent;
    
    // Constructor
    public BDto() {    }
 
    public BDto(int bId, String bName, String bTitle, String bContent,
            Timestamp bDate, int bHit, int bGroup, int bStep, int bIndent) {
        this.bId = bId;
        this.bName = bName;
        this.bTitle = bTitle;
        this.bContent = bContent;
        this.bDate = bDate;
        this.bHit = bHit;
        this.bGroup = bGroup;
        this.bStep = bStep;
        this.bIndent = bIndent;
    }
 
    // Setter, Getter
    public int getbId() {
        return bId;
    }
 
    public void setbId(int bId) {
        this.bId = bId;
    }
 
    public String getbName() {
        return bName;
    }
 
    public void setbName(String bName) {
        this.bName = bName;
    }
 
    public String getbTitle() {
        return bTitle;
    }
 
    public void setbTitle(String bTitle) {
        this.bTitle = bTitle;
    }
 
    public String getbContent() {
        return bContent;
    }
 
    public void setbContent(String bContent) {
        this.bContent = bContent;
    }
 
    public Timestamp getbDate() {
        return bDate;
    }
 
    public void setbDate(Timestamp bDate) {
        this.bDate = bDate;
    }
 
    public int getbHit() {
        return bHit;
    }
 
    public void setbHit(int bHit) {
        this.bHit = bHit;
    }
 
    public int getbGroup() {
        return bGroup;
    }
 
    public void setbGroup(int bGroup) {
        this.bGroup = bGroup;
    }
 
    public int getbStep() {
        return bStep;
    }
 
    public void setbStep(int bStep) {
        this.bStep = bStep;
    }
 
    public int getbIndent() {
        return bIndent;
    }
 
    public void setbIndent(int bIndent) {
        this.bIndent = bIndent;
    }
    
}
 
cs

6. DAO(Data Access Object) 만들기

데이터 베이스에 연결하여 필요한 로직을 수행하는 DAO클래스를 만든다.

생성자에서 DBCP를 만든다.

그 후 DBCP로부터 Connection을 얻고, 데이터 베이스와 관련해서 필요한 작업을 시작한다.


패키지 : com.mvc_board.ex.dao;

인터페이스명 : BDao


BDao.java

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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package com.mvc_board.ex.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
import com.mvc_board.ex.dto.BDto;
import com.mvc_board.ex.frontcontroller.BFrontController;
 
public class BDao {
 
    // Member field
    DataSource dataSource;
    
    // Constructor
    // 생성자에서 DBCP를 만든다. --> server.xml에 container 생성
    public BDao() {
        
        try {
            // InitialContext로 콘텍스를 구한다.
            Context context = new InitialContext();
            // db 커넥션 풀을 이용해서 dataSource를 구한다.
            dataSource = (DataSource) context.lookup("java:comp/env/jdbc/Oracle11g");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    
    // member function
    
    // 글 작성
    public void write(String bName, String bTitle, String bContent) {
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = dataSource.getConnection(); // db 연결 사용중인 커넥션 객체를 가져온다. (커넥션 풀)
            String query = "insert into mvc_board (bId, bName, bTitle, bContent, bHit, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, 0, mvc_board_seq.currval, 0, 0 )";
            pstmt = conn.prepareStatement(query);
            pstmt.setString(1, bName);
            pstmt.setString(2, bTitle);
            pstmt.setString(3, bContent);
            int result = pstmt.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
    }
    
    public ArrayList<BDto> list(){
        ArrayList<BDto> dtos = new ArrayList<BDto>();
        Connection conn = null;    // 데이터 접근을 위한 객체
        PreparedStatement pstmt = null;    // 쿼리문 실행을 위한 객체
        ResultSet rs = null;    // 데이터를 가져와 결과값을 얻기 위한 객체
        
        try {
            conn = dataSource.getConnection();
            String query = "select * from mvc_board order by bGroup desc, bStep asc";
            pstmt = conn.prepareStatement(query);
            rs = pstmt.executeQuery();
            
            while(rs.next()) {
                int bId = rs.getInt("bId");
                String bName = rs.getString("bName");
                String bTitle = rs.getString("bTitle");
                String bContent = rs.getString("bContent");
                Timestamp bDate = rs.getTimestamp("bDate");
                int bHit = rs.getInt("bHit");
                int bGroup = rs.getInt("bGroup");
                int bStep = rs.getInt("bStep");
                int bIndent = rs.getInt("bIndent");
                
                BDto dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
                dtos.add(dto);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
        return dtos;
    }
 
    public BDto contentView(String bId_str) {
        // TODO Auto-generated method stub
 
        upHit(bId_str);
        
        BDto dto = new  BDto();
        Connection conn = null;    // 데이터 접근을 위한 객체
        PreparedStatement pstmt = null;    // 쿼리문 실행을 위한 객체
        ResultSet rs = null;    // 데이터를 가져와 결과값을 얻기 위한 객체
        
        try {
            conn = dataSource.getConnection();
            String query = "select * from mvc_board where bId=?";
            pstmt = conn.prepareStatement(query);
            pstmt.setInt(1, Integer.parseInt(bId_str));
            rs = pstmt.executeQuery();
            
            if(rs.next()) {
                String bName = rs.getString("bName");
                String bTitle = rs.getString("bTitle");
                String bContent = rs.getString("bContent");
                Timestamp bDate = rs.getTimestamp("bDate");
                int bHit = rs.getInt("bHit");
                int bGroup = rs.getInt("bGroup");
                int bStep = rs.getInt("bStep");
                int bIndent = rs.getInt("bIndent");
                int bId = Integer.parseInt(bId_str);
                dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
        return dto;
    }
 
    public void modify(String bId, String bName, String bTitle, String bContent) {
        // TODO Auto-generated method stub
        Connection conn = null;
        PreparedStatement pstmt = null;
 
        try {
            conn = dataSource.getConnection();
            String query = "update mvc_board set bName=?, bTitle=?, bContent=? where bId=?";
            pstmt = conn.prepareStatement(query);
            pstmt.setString(1, bName);
            pstmt.setString(2, bTitle);
            pstmt.setString(3, bContent);
            pstmt.setInt(4, Integer.parseInt(bId));
            int result = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }finally {
            try {
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
 
    public void delete(String bId) {
        // TODO Auto-generated method stub
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = dataSource.getConnection();
            String query = "delete from mvc_board where bId=?";
            pstmt = conn.prepareStatement(query);
            pstmt.setInt(1, Integer.parseInt(bId));
            int result = pstmt.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
 
    public BDto reply_view(String str_bId) {
        // TODO Auto-generated method stub
        BDto dto = null;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = dataSource.getConnection();
            String query = "select * from mvc_board where bId=?";
            pstmt = conn.prepareStatement(query);
            pstmt.setInt(1, Integer.parseInt(str_bId));
            rs = pstmt.executeQuery();
            
            if(rs.next()) {
                int bId = rs.getInt("bId");
                String bName = rs.getString("bName");
                String bTitle = rs.getString("bTitle");
                String bContent = rs.getString("bContent");
                Timestamp bDate = rs.getTimestamp("bDate");
                int bHit = rs.getInt("bHit");
                int bGroup = rs.getInt("bGroup");    // 게시글과 답글을 묶는 그룹
                int bStep = rs.getInt("bStep");        // 게시글을 기준으로 몇번째 밑에 있는 답글을 달지의 단계
                int bIndent = rs.getInt("bIndent");    // 얼마만큼 안쪽으로 들어가서 글을 시작할지의 수
                
                dto = new BDto(bId, bName, bTitle, bContent, bDate, bHit, bGroup, bStep, bIndent);
            }
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                if(rs != null) rs.close();
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        
        return dto;
    }
 
    public void reply(String bId, String bName, String bTitle, String bContent, String bGroup, String bStep, String bIndent) {
        // TODO Auto-generated method stub
        
        // 계속 답글을 달려고 할 때 step 과 indent가 더해지면 안되니 조건을 거는 함수필요
        replyShape(bGroup, bStep);
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = dataSource.getConnection();
            String query = "insert into mvc_board (bId, bName, bTitle, bContent, bGroup, bStep, bIndent) values (mvc_board_seq.nextval, ?, ?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(query);
            
            pstmt.setString(1, bName);
            pstmt.setString(2, bTitle);
            pstmt.setString(3, bContent);
            pstmt.setInt(4, Integer.parseInt(bGroup));    // 게시글과 같은 그룹이라서 같음
            pstmt.setInt(5, Integer.parseInt(bStep) + 1);    // 게시글 기준 몇번째 밑에 있는 답글인지
            pstmt.setInt(6, Integer.parseInt(bIndent) + 1);    // 얼만큼 안쪽으로 들어가서 글을 시작할지
            int result = pstmt.executeUpdate();
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
 
    private void replyShape(String bGroup, String bStep) {
        // TODO Auto-generated method stub
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = dataSource.getConnection();
            String query = "update mvc_board set bStep = bStep + 1 where bGroup = ? and bStep > ?";
            pstmt = conn.prepareStatement(query);
            pstmt.setInt(1, Integer.parseInt(bGroup));
            pstmt.setInt(2, Integer.parseInt(bStep));
            
            int result = pstmt.executeUpdate();
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally {
            try {
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
    
    private void upHit( String bId) {
        // TODO Auto-generated method stub
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        
        try {
            connection = dataSource.getConnection();
            String query = "update mvc_board set bHit = bHit + 1 where bId = ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, bId);
            
            int rn = preparedStatement.executeUpdate();
                    
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
    }
    
}
 
cs


View 페이지 만들기

list.jsp
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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>   
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>게시판</title>
</head>
<body>
<h1>list</h1>
<hr>
<table width="500" cellpadding="0" cellspacing="0" border="1">
    <tr>    
        <th>번호</th>
        <th>이름</th>
        <th>제목</th>
        <th>날짜</th>
        <th>히트</th>
    </tr>
    <c:forEach items="${ list }" var="dto" <!-- request 로 보낸 list를 dto라는 변수로 하나씩 뽑는다. -->
    <tr>
        <td>${ dto.bId }</td>
        <td>${ dto.bName }</td>
        <td>
            <c:forEach begin="1" end="${ dto.bIndent }">-</c:forEach>
            <a href="content_view.do?bId=${ dto.bId }">${ dto.bTitle }</a>
        </td>
        <td>${ dto.bDate }</td>
        <td>${ dto.bHit }</td>
    </tr>
    </c:forEach>
    <tr>
        <td colspan="5"><a href="write_view.do">글작성</a></td>
    </tr>
</table>
</body>
</html>
cs

write_view.jsp
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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <form action="write.do" method="post">
        <table width="500" cellpadding="0" cellspacing="0" border="1">
            <tr>
                <td> 이름 </td>
                <td> <input type="text" name="bName" size = "50"> </td>
            </tr>
            <tr>
                <td> 제목 </td>
                <td> <input type="text" name="bTitle" size = "50"> </td>
            </tr>
            <tr>
                <td> 내용 </td>
                <td> <textarea name="bContent" rows="10" ></textarea> </td>
            </tr>
            <tr >
                <td colspan="2"> <input type="submit" value="입력"> &nbsp;&nbsp; <a href="list.do">목록보기</a></td>
            </tr>
        </table>
    </form>
    
</body>
</html>
cs

content_view.jsp
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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>글 내용</title>
</head>
<body>
<h1>Content View</h1>
<hr>
<form action="modify.do" method="post">
    <table width="500" cellpadding="0" cellspacing="0" border="1">
        <input type="hidden" name="bId" value="${ content_view.bId }">
        <tr>
            <td>번호</td>
            <td>${content_view.bId}</td>
        </tr>
        <tr>
            <td>히트</td>
            <td>${content_view.bHit}</td>
        </tr>
        <tr>
            <td>이름</td>
            <td><input type="text" name="bName" value="${content_view.bName}"></td>
        </tr>
        <tr>
            <td>제목</td>
            <td><input type="text" name="bTitle" value="${content_view.bTitle}"></td>
        </tr>
        <tr>
            <td>글내용</td>
            <td><input type="text" name="bContent" value="${content_view.bContent}"></td>
        </tr>
        <tr>
            <td colspan="2">
            <input type="submit" value="수정">&nbsp;&nbsp;
            <a href="list.do">목록 보기</a>&nbsp;&nbsp;
            <a href="delete.do?bId=${content_view.bId}">글 삭제</a>&nbsp;&nbsp;
            <a href="reply_view.do?bId=${content_view.bId}">댓글 달기</a
            </td>
        </tr>
    </table>
</form>
</body>
</html>
cs

reply_view.jsp
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
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 
    <table width="500" cellpadding="0" cellspacing="0" border="1">
        <form action="reply.do" method="post">
            <!-- 화면에 보이지는 않지만 form에 담기위해서  -->
            <input type="hidden" name="bId" value="${reply_view.bId}">
            <input type="hidden" name="bGroup" value="${reply_view.bGroup}">
            <input type="hidden" name="bStep" value="${reply_view.bStep}">
            <input type="hidden" name="bIndent" value="${reply_view.bIndent}">
            <tr>
                <td> 번호 </td>
                <td> ${reply_view.bId} </td>
            </tr>
            <tr>
                <td> 히트 </td>
                <td> ${reply_view.bHit} </td>
            </tr>
            <tr>
                <td> 이름 </td>
                <td> <input type="text" name="bName" value="${reply_view.bName}"></td>
            </tr>
            <tr>
                <td> 제목 </td>
                <td> <input type="text" name="bTitle" value="${reply_view.bTitle}"></td>
            </tr>
            <tr>
                <td> 내용 </td>
                <td> <textarea rows="10"  name="bContent">${reply_view.bContent}</textarea></td>
            </tr>
            <tr >
                <td colspan="2"><input type="submit" value="답변"> <a href="list.do" >목록</a></td>
            </tr>
        </form>
    </table>
    
</body>
</html>
cs

notCommand.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>해당 수행할 Command가 존재하지 않습니다.</h1>
<hr>
<a href="list.do">board_List로 다시 가기</a>
</body>
</html>
cs




관련글 더보기

댓글 영역