<글 쓰기 폼(write form)>
1)Action Class
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
|
package my.action;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class WriteFormAction
*/
@WebServlet("/WriteFormAction")
public class WriteFormAction implements CommandAction
{ //글 입력 폼 처리(인터페이스 적용)
public String requestPro(HttpServletRequest request,
HttpServletResponse response) throws Throwable {
//제목글과 답변글의 구분('re' = 답글)
int num = 0, ref = 1, re_step = 0, re_level = 0;
try {
if(request.getParameter("num") != null) {
num = Integer.parseInt(request.getParameter("num"));
ref = Integer.parseInt(request.getParameter("ref"));
re_step = Integer.parseInt(request.getParameter("re_step"));
re_level = Integer.parseInt(request.getParameter("re_level"));
}
} catch(Exception e) {e.printStackTrace();}
//해당 뷰에서 사용할 속성
request.setAttribute("num", new Integer(num));
request.setAttribute("ref", new Integer(ref));
request.setAttribute("re_step", new Integer(re_step));
request.setAttribute("re_level", new Integer(re_level));
//뷰에서 사용할 데이터 request영역에 저장
return "writeForm.jsp";
//해당 뷰 리턴
}
}
|
2)View
-유효성 검사
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
|
function writeSave() {
if(document.writeform.writer.value == "") {
alert("이름을 입력하세요");
document.writeform.writer.focus();
return false;
}
if(document.writeform.subject.value == "") {
alert("제목을 입력하세요");
document.writeform.subject.focus();
return false;
}
if(document.writeform.content.value == "") {
alert("내용을 입력하세요");
document.writeform.content.focus();
return false;
}
if(document.writeform.passwd.value == "") {
alert("암호를 입력하세요");
document.writeform.passwd.focus();
return false;
}
}
|
-view page
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
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file = "/color.jspf" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시판</title>
<script language="JavaScript" src="script.js"></script>
</head>
<body bgcolor = ${bodyback_c}>
<!-- el태그 사용해 배경색 설정 -->
<center><b>글쓰기</b></center><br/>
<form method = "post" name = "writeform"
action = "/boardMvc2Ora/writePro.do" onsubmit = "return writeSave()">
<!-- .do로 끝나는 write 처리 페이지로 전송 -->
<input type = "hidden" name = "num" value = "${num}">
<input type = "hidden" name = "ref" value = "${ref}">
<input type = "hidden" name = "re_step" value = "${re_step}">
<input type = "hidden" name = "re_level" value = "${re_level}">
<!-- request영역에 저장된 데이터를 el로 호출해 hidden으로 보낸다. -->
<table width = "400" border = "1" cellspacing = "0"
cellpadding = "0" align = "center">
<tr>
<td align = "right" colspan = "2" bgcolor = "${value_c }">
<a href = "/boardMvc20ra/list.do"></a>
</td>
</tr>
|
중략
1
2
3
4
5
6
7
8
9
|
<tr>
<td width = "70" bgcolor = "${value_c }" align = "center">제목</td>
<td width = "330">
<c:if test = "${num == 0 }">
<input type = "text" size = "40" maxlength = "50"
name = "subject"></td></c:if> <c:if test = "${num != 0 }">
<input type = "text" size = "40" maxlength = "50"
name = "subject" value = "[답변]"></td></c:if> </tr>
|
처음 쓰는 글이면 빈 텍스트 입력 공간을, 답변 글이면 텍스트 입력 공간에 [답변]이라는 문자를 추가한다.
뒷부분 생략
마지막으로, 매핑 잊지 말기!
<실행>
그냥 실행을 하면 답변글 쓰기 폼이 나오는데,
url 맨 뒷부분을 .do로 바꿔주면 정상적으로 글쓰기 폼이 작동한다.
<글쓰기 처리(write process)>
1)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
|
//글쓰기
public void insertArticle(BoardDataBean article) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int num = article.getNum();
int ref = article.getRef();
int re_step = article.getRe_step();
int re_level = article.getRe_level();
//빈을 받는 변수
int number = 0;
String sql = "";
try {
conn = getConnection();
pstmt = conn.prepareStatement("select max(num) from board");
//가장 최근 글의 글번호
rs = pstmt.executeQuery();
if(rs.next())
number = rs.getInt(1) + 1;
//에 1을 더한다.
else
number = 1;
if(num != 0)
//글번호가 0이 아니면
{
sql =
"update board set re_step=re_step + 1 where ref = ? and re_step > ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, ref);
pstmt.setInt(2, re_step);
pstmt.executeUpdate();
re_step = re_step + 1;
re_level = re_level + 1;
//답글 step을 1 증가시켜라
//실행 뒤 또 답글 step, level을 1 증가시켜라
} else {
ref = number;
re_step = 0;
re_level = 0;
}
//쿼리를 작성
sql =
"insert into board(num, writer, email, subject, passwd, reg_date, ";
sql +=
"ref, re_step, re_level, content, ip)"
+ "values(board_num_seq.nextval, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, article.getWriter());
pstmt.setString(2, article.getEmail());
pstmt.setString(3, article.getSubject());
pstmt.setString(4, article.getPasswd());
pstmt.setTimestamp(5, article.getReg_date());
pstmt.setInt(6, ref);
pstmt.setInt(7, re_step);
pstmt.setInt(8, re_level);
pstmt.setString(9, article.getContent());
pstmt.setString(10, article.getIp());
pstmt.executeUpdate();
//데이터 입력쓰
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if(rs != null) try { rs.close(); } catch(SQLException ex) {}
if(pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if(conn != null) try { conn.close(); } catch(SQLException ex) {}
}
}
|
2)Action Class
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
|
package my.action;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import my.board.BoardDBBean;
import my.board.BoardDataBean;
public class WriteProAction implements CommandAction{ //입력된 글 처리
public String requestPro(HttpServletRequest request,
HttpServletResponse response) throws Throwable {
request.setCharacterEncoding("UTF-8"); //한글 인코딩
BoardDataBean article = new BoardDataBean();
//데이터 빈
article.setNum(Integer.parseInt(request.getParameter("num")));
article.setWriter(request.getParameter("writer"));
article.setEmail(request.getParameter("email"));
article.setSubject(request.getParameter("subject"));
article.setPasswd(request.getParameter("passwd"));
article.setReg_date(new Timestamp(System.currentTimeMillis()));
article.setRef(Integer.parseInt(request.getParameter("ref")));
article.setRe_step(Integer.parseInt(request.getParameter("re_step")));
article.setRe_level(Integer.parseInt(request.getParameter("re_level")));
article.setContent(request.getParameter("content"));
article.setIp(request.getRemoteAddr());
//빈에 데이터 저장
BoardDBBean dbPro = BoardDBBean.getInstance();
//DB 처리: DAO 인스턴스 참조
dbPro.insertArticle(article);
//Business Method 실행
return "writePro.jsp"; // 뷰
}
}
|
request영역에서 가져온 데이터를 빈에 set한다.
3)Msg 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="0;url=/boardMvc2Ora/list.do">
<title>Insert title here</title>
</head>
<body>
글 입력 성공
</body>
</html>
|
매핑
<실행>
글쓰기 폼에서 글을 입력한 뒤 글쓰기 버튼을 클릭
아직 list 처리를 하지 않아 오류가 뜬다.
데이터베이스를 확인해보면 데이터는 입력되었으므로 잘 작동하고 있다고 할 수 있다.
'20.03 ~ 20.08 국비교육 > JSP' 카테고리의 다른 글
MVC 모델2 - 7. 글 보기(Read) (0) | 2020.06.22 |
---|---|
MVC 모델2 - 6. 글 목록(List) (0) | 2020.06.19 |
MVC 모델2 - 4. Front Controller, Command, DAO (0) | 2020.06.17 |
MVC 모델2 - 2. 작동 원리, 매핑(Mapping) (0) | 2020.06.03 |
MVC 모델2 - 1. Server Pool 생성 (0) | 2020.06.02 |