web

[jsp] 글 작성 게시물 만들기

소댓 2023. 4. 30. 21:17

* 글 작성 게시물 만들기

 

- [write.jsp] 
  > servlets.com > cosfile upload library > cos-22.05.zip(dev에 압축풀기)
  > lib의 cos.jar 파일을 webapp- web-inf 에 추가! (=>파일 다운받는 것을 도와줄!)

 

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>write.jsp</title>
</head>
<body>
    <form action="result.jsp" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <th>제목</th>
                <td><input type="text" name="title" id="" /></td>
            </tr>
            <tr>
                <th>작성자</th>
                <td><input type="text" name="writer" id="" /></td>
            </tr>
            
            <tr>
                <th>내용</th>
                <td><textarea name="contents" id="" cols="30" rows="10"></textarea></td>
            </tr>
            <tr>
                <th>첨부파일</th>
                <td><input type="file" name="filename" id="" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="전송" /></td>
            </tr>
        </table>
    
    </form>
    
</body>
</html>
cs

 

 

 


- [result.jsp] : 게시판에 작성한 내용으로 실제 파일 저장 + 화면에 출력
  >> webapp에 upload 라는 폴더 생성!! (폴더 생성하고 활성화를 위해 이미지 파일 하나 넣어놓기)

 

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
<%@page import="vo.FileVO"%>
<%@page import="dao.FileDAO"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>result.jsp</title>
</head>
<body>
 
    <%
        // upload 디렉토리의 실제 경로 얻어오기
        String saveDir = request.getRealPath("/upload");
        /* out.println(saveDir); */
        
        // 첨부파일의 최대 크기 : 30MB 까지 업로드 가능
        // 1MB ==> 1024KB
        int maxFileSize = 1024*1024*30;
        
        // 1Kb ==> 1023Byte
                
        MultipartRequest mr = new MultipartRequest(request, saveDir, maxFileSize, 
                "UTF-8", new DefaultFileRenamePolicy());
        
        // 파라미터값 가져오기
        /* String title = request.getParameter("title"); */
        String title = mr.getParameter("title");
        String writer = mr.getParameter("writer");
        String contents = mr.getParameter("contents");
        
        // 파일의 원래 이름
        String f = mr.getOriginalFileName("filename");
        
        // db에도 저장되어 있어야..
        FileDAO dao = new FileDAO();
        dao.addOne(title, writer, contents, f);
        
    %>
    
    <h2>제목: <%= title %></h2>
    <h2>작성자: <%= writer %></h2>
    <h2>내용: <%= contents %></h2>
    <h2>파일명: <%= f %></h2>
    
    <a href="view.jsp">이미지 보러가기</a>
</body>
</html>
cs

 

 

- [filedao]

  > 생성자 : 객체의 초기화를 담당

 

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
package dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
 
import vo.FileVO;
 
public class FileDAO {
    // 1.
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    String user = "scott";
    String password = "tiger";
    Connection conn ;
    PreparedStatement pstmt ;
    ResultSet rs ; 
    StringBuffer sb = new StringBuffer();
    
    public FileDAO() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("conn : "+conn);
        } catch (ClassNotFoundException e) {
            System.out.println("드라이버 로딩 실패");
        } catch (SQLException e) {
            System.out.println("DB 연결 실패");
        }
        
    }
    
    public void addOne(String title, String writer, String contents, String f) {
        
        FileVO vo = new FileVO(0, title, writer, contents, f);
        
        sb.setLength(0);
        sb.append("INSERT INTO fileuploadtest ");
        sb.append("VALUES(FILE_NO_SEQ.nextval, ?, ?, ?, ?)");
        
        try {
            pstmt = conn.prepareStatement(sb.toString());
 
            pstmt.setString(1, vo.getTitle());
            pstmt.setString(2, vo.getWriter());
            pstmt.setString(3, vo.getContents());
            pstmt.setString(4, vo.getF());
            
            pstmt.executeUpdate();
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
                
    } // addOne() end
    
    public ArrayList<FileVO> selectAll(){
        ArrayList<FileVO> list = new ArrayList<FileVO>();
        sb.setLength(0);
        sb.append("SELECT * FROM fileuploadtest ");
        
        try {
            pstmt = conn.prepareStatement(sb.toString());
            rs = pstmt.executeQuery();
            while(rs.next()) {
                int no = rs.getInt("no");
                String title = rs.getString("title");
                String writer = rs.getString("writer");
                String contents = rs.getString("contents");
                String f = rs.getString("filename");
                
                FileVO vo = new FileVO(no, title, writer, contents, f);
                list.add(vo);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        return list;
    } // selectAll() end
    
    
    
}
 
cs

 

 

- [fileVO] 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package vo;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FileVO {
    int no;
    String title;
    String writer;
    String contents;
    String f;
}
 
cs

 

- [view.jsp] : 업로드한 파일 확인(result에서 연결) (>수정..)
  > result..에 파일 업로드한 거 테스트하기 위해 cmd에 'FILEUPLOADTEST' 테이블 생성

CREATE TABLE FILEUPLOADTEST
 (NO NUMBER(4),
 TITLE VARCHAR2(20),
 WRITER VARCHAR2(20),
 CONTENTS VARCHAR2(300),
 FILENAME VARCHAR2(2000));

 

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
<%@page import="java.util.ArrayList"%>
<%@page import="vo.FileVO"%>
<%@page import="dao.FileDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>view.jsp</title>
<style>
    table, td, tr, th{
        text-align: center;
        border-collapse: collapse;
        width: 800px;
        margin: 0 auto;
        border: 1px solid gray;
    }
    th{
    background-color: #ECE8EC
    }
    img{
    width: 50px;
    height: 50px;
    }
</style>
</head>
<body>
    <table>
        <tr>
            <th>파일번호</th>
            <th>제목</th>
            <th>작성자</th>
            <th>내용</th>
            <th>파일명</th>
        </tr>
    
    
    <!-- 반복 -->
    <% 
    FileDAO dao = new FileDAO(); // 파일 객체 접근
    ArrayList<FileVO> list = dao.selectAll(); // 전체 목록 가져오기
    for(FileVO vo : list){ // 파일 하나씩 꺼내기
    %>
    
        <div>
        <tr>
            <td><%=vo.getNo() %></td>
            <td><%=vo.getTitle() %></td>
            <td><%=vo.getWriter() %></td>
            <td><%=vo.getContents() %></td>
            <td><img src="../upload/<%=vo.getF() %>" alt="" /></td>
        </tr>
        
        </div>
    <% 
    }
    
    %>
    
    </table>
 
</body>
</html>
cs

 

 

 

- [dirView.jsp] : file directory 볼 수 있게!

 

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
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>dirView.jsp</title>
</head>
<body>
    <%
        // upload 디렉토리의 실제 os 경로
        String path = request.getRealPath("/upload");
        out.println("파일이 저장되어 있는 os 경로 : " + path);
        
        // 파일 객체
        File f = new File(path); // 경로를 파일 객체로!
        
        // 디렉토리인지 확인 ?
        if(f.isDirectory()){//디렉토리이면 true,아니면 false 반환하는 메서드 사용    
                out.println("디렉토리 맞음 ");
                String[] fList = f.list();
                for(String x : fList){
                    out.println("<h2>" + x + "</h2>");
                }
                
        
            for(String x : fList){
                out.println("<img src='../upload/"+x+"' />");
            }
        }
        
    %>
    
    
</body>
</html>
cs