티스토리 뷰

JSP만 사용해서 만드는 게시판

  • MariaDB 사용
  • 기본적인 CRUD
    Create/Read/Update/Delete




게시판 수정 

게시판 목록을 만들었다. → 게시판 목록
게시판 글 쓰기도 만들었다. → 게시판 글 생성
게시판 상세보기도 만들었다. → 게시판 상세보기

이제 게시판 수정을 해보자!

저번 게시판 상세보기를 만들면서, 상세페이지 안에 수정 페이지로 가는 버튼을 만들었다.
수정은 상세페이지에서 수정 버튼을 누르면 수정 페이지로 이동하게 되고, 글을 수정한 뒤 
수정된 사항을 DB에 넣는 작업을 해주고, DB에 성공적으로 들어가면 다시 수정된 글이 보이는 상세페이지로 이동하게 된다.


1.


1
<button type=button title="수정" onClick="location.href='update.jsp?idx=<%=idx%>'">수정</button>
cs

상세 페이지에서 수정 버튼을 클릭하면 update.jsp로 이동하게 되는데, 그때 상세페이지의 idx를 가지고 넘어가게 된다.

수정 페이지 또한 글 생성 페이지와 같으나, 수정을 위해 DB에서 데이터를 가져와 뿌려주어야 한다.


2.

그렇다면 html 코드를 보자 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<body>
    <div>
        <h1>글수정</h1>
    </div>
    <div>
        <form name="update" action="updatedb.jsp" method=post onsubmit="return check()">
        <input type="hidden" name="idx" value=""/>
            제목 : <input type="text" id="title" name="title" value=""/></br>
            작성자 : <br/><br/>
            =============================================<br/>
            <textarea rows="10" cols="50" name="text"> </textarea>
            <div>
                <input type=submit value="수정"/>
                <input type=button value="목록" onclick="location.href='list.jsp'"/>
            </div>
        </form>
    </div>        
</body>
cs


글 생성 코드와 같다 다른것은 value="" 값이 추가 되었다.
value값 안에 DB에서 가져온 값을 넣어 주게 될 것이다.


수정 버튼을 클릭해서 submit 할때 form의 onsubmit에서 check() 함수로 이동하여 유효성 검사를 하게 된다.

script 부분이다. 

form 안의 요소를 가지고 올때에는 form의 이름을 사용하여 가져와야 한다.
document.update.title → 문서에서 form이름인 update form 의 title 값을 가져온다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script type="text/javascript">
    
    function check(){
        //form 의 요소를 가지고 올 때에는 form의 이름을 사용하여 가져와야 한다. getElementById는 안댕
        var title = document.update.title;
        var name = document.update.name;
        var text = document.update.text;
                
        if(title.value==""){
            alert("제목을 입력해주세요.");
            title.focus();
            return false;
        }else if(text.value==""){
            alert("내용을 입력해주세요.");
            text.focus();
            return false;
        }else{
            alert("글이 등록됩니다!");
            return true;
        }
    }
</script>
cs

 


2.

DB연결을 하자!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<% 
    //DB연결
    Connection conn = null;
    Statement stmt = null;
    
    String idx = request.getParameter("idx");
    
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/haeun?useUnicode=true&characterEncoding=utf-8","","");
        //db insert시 한글 깨져서 db명 뒤에 ?useUnicode=true&characterEncoding=utf-8 붙여준다.
        if(conn == null)
            throw new Exception("데이터베이스에 연결할 수 없습니다.");
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select * from board where idx=" +idx);
 
%>
cs


여기는 또 게시판 상세 화면이랑 동일하다.
html 코드 위에 <% %> 자바 코드를 삽입하여 DB에 연결한다.
상세화면에서 수정버튼 클릭 시 파라미터로 idx를 넘겨주었다.

idx를 받으려면 request.getParameter를 이용하여 받을 수 있다.

받아온 idx를 가지고 쿼리를 실행하여 select 문으로 idx가 idx 인 데이터를 가지고 온다.

"select * from board where idx=" + idx

이 쿼리를 실행시키면 된다.


그리고 나서 가져온 데이터를 rs.next()를 이용하여 value 값에 넣어준다.

상세화면과의 차이점은, input 안에 넣느냐 안넣느냐 차이 인듯(헤헤)

아 그리고 작성자는 수정하지 않기로 해서(내맘) input box를 만들지 않았다.


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
<body>
    <div>
        <h1>글수정</h1>
    </div>
<%
        while(rs.next()){
%>    
    <div>
        <form name="update" action="updatedb.jsp" method=post onsubmit="return check()">
        <input type="hidden" name="idx" value="<%= idx %>"/>
            제목 : <input type="text" id="title" name="title" value="<%= rs.getString("title") %>"/></br>
            작성자 : <%= rs.getString("name"%><br/><br/>
            =============================================<br/>
            <textarea rows="10" cols="50" name="text"><%= rs.getString("text"%></textarea>
 
            <div>
                <input type=submit value="수정"/>
                <input type=button value="목록" onclick="location.href='list.jsp'"/>
            </div>
        </form>
    </div>    
<%
    }
        conn.close();
    }catch(Exception e){
        out.println("데이터베이스에 문제가 있습니다.");
        out.println(e.getMessage());
        e.getStackTrace();
    }
%>            
</body>
cs


수정 JSP를 다 만들었으면 이제 DB에 수정된 값을 넣어 업데이트 해 주어야 한다.
form 전송을 하면 form 안의 값들이 파라미터로 넘어가게 되는데, 여기서 GET방식과 POST 방식을 알아보자

# GET 방식과 POST 방식의 차이 
- GET 방식 :  URL 뒤에 파라미터가 붙어 넘어간다 -> 가져오는것 
- POST 방식 : Form 전송시 많이 사용한다. URL 뒤에 파라미터가 붙지 않는다 -> 수행하는것 

글 목록에서 상세 페이지로 넘어갈때나, 글 수정 페이지로 넘어갈때나 나는 URL 뒤에 idx를 붙여 GET방식으로 넘겨주었다.
POST방식일 때는 URL 뒤에 파라미터가 붙지 않는다고 했는데 그렇다면 어떻게 해주어야 하는가??????

내가 이미 알고있던 방식이었다.(하하)

<input type="hidden" name="idx" value="<%= idx %>"/>

hidden 값으로 idx를 넘기면 되는 것이다 ! (꼭 기억해두자)



3.

update.jsp 화면에서 수정 버튼을 누르면 form 의 action을 통해서 updatedb.jsp 로 이동하게 되는데, 
updatedb.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
47
48
49
50
51
52
53
54
55
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>    
<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>
<%
 
    request.setCharacterEncoding("UTF-8");
 
    String idx = request.getParameter("idx");
    System.out.println("idx======"+idx);
    
    String title = request.getParameter("title");
    System.out.println("title======"+title);
 
    String text = request.getParameter("text");
    System.out.println("text======"+text);
    
    String time = null;
    
      if(title==null || text==null){
        throw new Exception("데이터를 입력하세요.");
    }
 
    Connection conn = null;
    Statement stmt = null;
    
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/haeun?useUnicode=true&characterEncoding=utf-8","khe","1231");
        //db insert시 한글 깨져서 db명 뒤에 ?useUnicode=true&characterEncoding=utf-8 붙여주니 안깨지고 들어간다.
        if(conn == null)
            throw new Exception("데이터베이스에 연결할 수 없습니다.");
        stmt = conn.createStatement();
        String command = String.format("update board set title='%s', text='%s', time=now()" + "where idx='%s'", title, text, idx);
        int rowNum = stmt.executeUpdate(command);
        if(rowNum<1)
            throw new Exception("데이터를 DB에 입력할 수 없습니다.");
    }
    finally{
        try{
            stmt.close();
        }
        catch(Exception ignored){
        }
        try{
            conn.close();
        }
        catch(Exception ignored){
        }
    }
    
    response.sendRedirect("detail.jsp?idx="+idx);
%>
 
cs


request.getParameter 를 사용하여 idx, title, text를 가지고 온다.

받아온 값들을 SQL문에 넣어 실행한다.

 update 하는 SQL문은 update set을 해주면 된다.

("update board set title='%s', text='%s', time=now()" + "where idx='%s'", title, text, idx)

DB에 update를 성공한 후 finally 문에서 DB연결을 종료하고 
마지막에 상세화면으로 sendRedirect를 시켜준다. 

그럼 끝>_<





'게시판정복 > JSP게시판' 카테고리의 다른 글

6. 게시판 글 삭제  (0) 2017.04.07
4. 게시판 상세보기  (0) 2017.04.04
3. 게시판 글 생성  (0) 2017.03.28
2. 게시판 목록  (0) 2017.03.28
1. 페이지설계/ TABLE설계/ JDBC/ 이클립스DB연결  (1) 2017.02.21
댓글