본문 바로가기

자바 웹/MVC

MVC - 서블릿(컨트롤러)/답변형 게시판 4(답글 작성)

728x90

글 상세창에서 답글쓰기를 클릭하면 parentno를 컨트롤러로 전송하고, 답글 쓰기창에서 답변 글을 작성한 후 컨트롤러로 요청한다. 그러면 컨트롤러에서는 전송된 답글 정보를 게시판 테이블에 부모 글 번호와 함께 추가한다.

 

답글도 새 글이기 때문에 새 글 쓰기 기능과 비슷하다. 차이점은 답글창을 요청할 때 미리 부모 글 번호를 parentno 속성으로 세션에 저장해 두고, 답글을 작성한 후 등록을 하면 세션에서 parentno를 가져와 테이블에 추가한다는 점이다.

 

 

원래 있던 글을 선택하고 답글 쓰기를 누른 후 새로운 글을 작성하면 위와 같이 부모글에 대한 답변으로 달리게 된다.

 

답글의 글 번호에 해당하는 폴더도 새로 생성되어 이미지가 저장되는 것은 그냥 부모글을 작성하는 것과 마찬가지로 된다. 메서드도 그냥 글을 추가할 때 사용했던 insertNewArticle 메서드를 사용하지만 차이점은 부모글 번호에는 세션에 저장된 부모글 번호가 들어간다는 점이다.

 

Controller

 

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
@WebServlet("/board/*")
public class BoardController extends HttpServlet {
    
    private static String ARTICLE_IMG_REPO = "C:\\pra_board\\article_img";//이미지 저장 위치
    BoardService boardService;
    ArticleVO articleVO;
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        //서블릿 초기화 시 BoardService 객체 생성
        boardService = new BoardService();
        articleVO = new ArticleVO();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doHandle(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doHandle(request, response);
    }
    
    private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nextPage ="";
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        HttpSession session;//답글에 대한 부모 글 번호를 저장하기 위해 세션을 사용
        String action = request.getPathInfo();//요청명을 가져옴
        
        try {
            List<ArticleVO> articleList = new ArrayList<ArticleVO>();
            if(action == null) {
                articleList = boardService.listArticles();
                request.setAttribute("articleList", articleList);
                nextPage = "/board01/listArticles.jsp";
            }
            //액션 값이 아래와 같으면 전체 글을 조회
            else if(action.equals("/listArticles.do")) {
                articleList = boardService.listArticles();//전체 글 조회
                request.setAttribute("articleList", articleList);//articleList로 바인딩
                nextPage = "/board01/listArticles.jsp";//listArticles.jsp로 포워딩
            }
            //액션 값이 아래와 같으면 글쓰기 페이지로 이동
            else if(action.equals("/articleForm.do")) {
                nextPage = "/board01/articleForm.jsp";
            }        
            //액션 값이 아래와 같으면 새 글 추가 작업 실행
            else if(action.equals("/addArticle.do")) {
                int articleno = 0;
                //파일 업로드 기능을 사용하기 위해서 upload()로 요청을 전달
                Map<StringString> articleMap = upload(request,response);
                //articleMap에 저장한 글 정보를 다시 가져옴
                String title = articleMap.get("title");
                String content = articleMap.get("content");
                String imagefilename = articleMap.get("imagefilename");
                System.out.println(title+","+content+","+imagefilename);
                
                //글쓰기 창에서 입력된 정보를 VO 객체에 설정한 후 addArticle()로 전달
                articleVO.setParentno(0);//새 글의 부모 글 번호를 0으로 설정
                articleVO.setId("hong");//새 글 작성자 ID를 hong으로 설정
                articleVO.setTitle(title);
                articleVO.setContent(content);
                articleVO.setImagefilename(imagefilename);
                articleno = boardService.addArticle(articleVO);//테이블에 새 글을 추가한 후 새 글에 대한 글 번호 가져옴                
                
                //파일을 첨부한 경우에만 수행
                if(imagefilename != null && imagefilename.length() != 0) {
                    //temp 폴더에 임시로 업로드 될 파일 객체를 생성
                    File srcFile = new File(ARTICLE_IMG_REPO+"\\"+"temp"+"\\"+imagefilename);
                    System.out.println("srcFile = "+srcFile);
                    
                    //CURR_IMAGE_REPO_PATH의 경로 하위에 글 번호로 폴더를 생성
                    File destDir = new File(ARTICLE_IMG_REPO+"\\"+articleno);
                    System.out.println("destDir = "+destDir);
                    destDir.mkdirs();
                    
                    //temp 폴더의 파일을 글 번호를 이름으로 하는 폴더로 이동
                    FileUtils.moveFileToDirectory(srcFile, destDir, true);
                }
                //새 글 등록 메시지를 나타낸 후 자바스크립트 location 객체의 href 속성을 이용해 글 목록을 요청
                PrintWriter writer = response.getWriter();
                writer.print("<script>" + " alert('새 글을 추가했습니다.');"
                                        + " location.href='"
                                        + request.getContextPath()
                                        + "/board/listArticles.do';"+"</script>");
                return;
                
            }
            else if(action.equals("/viewArticle.do")) {
                String articleno = request.getParameter("articleno");//글 상세창을 요청할 경우 articleno 값을 가져옴
                
                //articleno에 대한 글 정보를 조회하고 article 속성으로 바인딩
                articleVO = boardService.viewArticle(Integer.parseInt(articleno));
                request.setAttribute("article", articleVO);
                
                nextPage = "/board01/viewArticle.jsp";
            }
            else if(action.equals("/modArticle.do")) {
                Map<String,String> articleMap = upload(request,response);
                int articleno = Integer.parseInt(articleMap.get("articleno"));
                articleVO.setArticleno(articleno);
                System.out.println("articleno = "+articleno);
                
                String title = articleMap.get("title");
                String content = articleMap.get("content");
                String imagefilename = articleMap.get("imagefilename");
                
                articleVO.setParentno(0);
                articleVO.setId("hong");
                articleVO.setTitle(title);
                articleVO.setContent(content);
                articleVO.setImagefilename(imagefilename);
                
                boardService.modArticle(articleVO);//전송된 글 정보를 이용해 글을 수정
                
                if(imagefilename != null && imagefilename.length() != 0) {
                    String originalFileName = articleMap.get("originalFileName");
                    
                    //수정된 이미지 파일을 폴더로 이동
                    File srcFile = new File(ARTICLE_IMG_REPO+"\\"+"temp"+"\\"+imagefilename);
                    File destDir = new File(ARTICLE_IMG_REPO+"\\"+articleno);
                    destDir.mkdirs();
                    FileUtils.moveFileToDirectory(srcFile, destDir, true);
                    
                    //전송된 originalFileName을 이용해 기존의 파일을 삭제
                    File oldFile = new File(ARTICLE_IMG_REPO+"\\"+articleno+"\\"+originalFileName);
                    oldFile.delete();
                }
                //새 글 등록 메시지를 나타낸 후 자바스크립트 location 객체의 href 속성을 이용해 글 목록을 요청
                PrintWriter writer = response.getWriter();
                writer.print("<script>" + " alert('글을 수정했습니다.');"
                                        + " location.href='"
                                        + request.getContextPath()
                                        + "/board/viewArticle.do?articleno="+articleno+"';"+"</script>");
                return;
            }
            else if(action.equals("/removeArticle.do")) {
                int articleno = Integer.parseInt(request.getParameter("articleno"));
                //articleno 값에 대한 글을 삭제한 후 삭제된 부모 글과 자식 글의 articleno 목록을 가져옴
                List<Integer> articleNoList = boardService.removeArticle(articleno);
                
                //삭제된 글들의 이미지 저장 폴더들을 삭제
                for(int _articleno : articleNoList) {
                    File imgDir = new File(ARTICLE_IMG_REPO+"\\"+_articleno);
                    if(imgDir.exists()) {
                        FileUtils.deleteDirectory(imgDir);
                    }
                }
                
                PrintWriter writer = response.getWriter();
                writer.print("<script>" + " alert('글을 삭제했습니다.');"
                                        + " location.href='"
                                        + request.getContextPath()
                                        + "/board/listArticles.do';"+"</script>");
                return;
            }
            else if(action.equals("/replyForm.do")){
                System.out.println("parentno = "+request.getParameter("parentno"));
                //답글창 요청 시 미리 부모 글 번호를 parentno 속성으로 세션에 저장
                int parentno = Integer.parseInt(request.getParameter("parentno"));
                session = request.getSession();
                session.setAttribute("parentno", parentno);
                
                nextPage = "/board01/replyForm.jsp";
            }
            else if(action.equals("/addReply.do")){
                //답글 전송 시 세션에 저장된 parentno를 가져옴
                session = request.getSession();
                int parentno = (Integer) session.getAttribute("parentno");
                session.removeAttribute("parentno");
                
                Map<String,String> articleMap = upload(request,response);
                String title = articleMap.get("title");
                String content = articleMap.get("content");
                String imagefilename = articleMap.get("imagefilename");
                
                articleVO.setParentno(parentno);//답글의 부모글 번호를 설정
                articleVO.setId("lee");//답글의 작성자 ID를 lee로 설정
                articleVO.setTitle(title);
                articleVO.setContent(content);
                articleVO.setImagefilename(imagefilename);
                
                int articleno = boardService.addReply(articleVO);//답글을 테이블에 추가
                
                //답글에 첨부한 이미지를 temp 폴더에서 답글 번호 폴더로 이동
                if(imagefilename != null && imagefilename.length() != 0) {
                    File srcFile = new File(ARTICLE_IMG_REPO+"\\"+"temp"+"\\"+imagefilename);
                    File destDir = new File(ARTICLE_IMG_REPO+"\\"+articleno);
                    destDir.mkdirs();
                    FileUtils.moveFileToDirectory(srcFile, destDir, true);                    
                }
                
                PrintWriter writer = response.getWriter();
                writer.print("<script>" + " alert('답글을 추가했습니다.');"
                        + " location.href='"
                        + request.getContextPath()
                        + "/board/viewArticle.do?articleno="+articleno+"';"+"</script>");
                
                return;
                
            }
            else {
                nextPage = "/board01/listArticles.jsp";
            }
            
            RequestDispatcher dispatch = request.getRequestDispatcher(nextPage);
            dispatch.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private Map<StringString> upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<StringString> articleMap = new HashMap<StringString>();
        String encoding = "utf-8";
        File currentDirPath = new File(ARTICLE_IMG_REPO);//글 이미지 저장 폴더에 대해 파일 객체를 생성
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(currentDirPath);
        factory.setSizeThreshold(1024*1024);
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        try {
            List items = upload.parseRequest(request);//request 객체에서 매개변수를 List로 가져옴
            for (int i = 0; i < items.size(); i++) {
                FileItem fileItem = (FileItem) items.get(i);//파일 업로드창에서 업로드된 항목들을 하나씩 가져옴
                
                //폼 필드면 전송된 매개변수 값을 출력
                if (fileItem.isFormField()) {
                    System.out.println(fileItem.getFieldName()+"="+fileItem.getString(encoding));
                    //파일 업로드로 같이 전송된 새 글 관련 매개변수를 Map에 저장한 후 반환하고, 새 글과 관련된 title, content를 Map에 저장
                    articleMap.put(fileItem.getFieldName(), fileItem.getString(encoding));
                }
                else {
                    //업로드한 파일이 존재하는 경우 업로드한 파일의 파일 이름으로 저장소에 업로드
                    if(fileItem.getSize() > 0) {
                        int idx = fileItem.getName().lastIndexOf("\\");
                        
                        if(idx == -1) {
                            idx = fileItem.getName().lastIndexOf("/");
                        }
                        //첨부한 파일을 먼저 temp 폴더에 업로드,
                        String fileName = fileItem.getName().substring(idx+1);
                        System.out.println("파일명 = "+fileName);
                        articleMap.put(fileItem.getFieldName(), fileName);//익스플로러에서 업로드 파일의 경로 제거 후 map에 파일명 저장
                        File uploadFile = new File(currentDirPath+"\\temp\\"+fileName);
                        
                        fileItem.write(uploadFile);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return articleMap;
    }
}
 
cs

 

서비스

 

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
public class BoardService {
    BoardDAO boardDAO;
 
    public BoardService() {
        //생성자 호출 시 BoardDAO()객체 생성
        boardDAO = new BoardDAO();
    }
 
    public List<ArticleVO> listArticles() {
        List<ArticleVO> articleList = boardDAO.selectAllArticles();
        return articleList;
    }
    
    public int addArticle(ArticleVO article) {
        return boardDAO.insertNewArticle(article);
    }
    
    public ArticleVO viewArticle(int articleno) {
        ArticleVO article = null;
        article = boardDAO.selectArticle(articleno);
        return article;
    }
    
    public void modArticle(ArticleVO article) {
        boardDAO.updateArticle(article);
    }
    
    public List<Integer> removeArticle(int articleno) {
        List<Integer> articleNoList = boardDAO.selectRemovedArticles(articleno);
        boardDAO.deleteArticle(articleno);
        return articleNoList;
    }
    
    //새 글 추가 시 사용한 insertNewArticle()메서드를 사용해서 답글을 추가
    public int addReply(ArticleVO article) {
        return boardDAO.insertNewArticle(article);
    }
}
cs

 

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
    public int insertNewArticle(ArticleVO article) {
        int articleno = getNewArticleNO();//새 글을 추가하기 전에 새 글에 대한 글 번호를 가져옴
 
        try{
            con = getConnection();
            
            int parentno = article.getParentno();
            String title = article.getTitle();
            String content = article.getContent();
            String id = article.getId();
            String imagefilename = article.getImagefilename();
 
            String sql = "insert into t_board (articleno, parentno, title, content, id, imagefilename) values(?,?,?,?,?,?)";
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, articleno);
            pstmt.setInt(2, parentno);
            pstmt.setString(3, title);
            pstmt.setString(4, content);
            pstmt.setString(5, id);
            pstmt.setString(6, imagefilename);
            System.out.println("dao imagefilename = "+imagefilename);
            pstmt.executeUpdate();
            
            pstmt.close();
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("dao articleno = "+articleno);
        return articleno;
    }
cs

 

viewArticle.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
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
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>  
<%request.setCharacterEncoding("utf-8"); %>      
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>    
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
 
<style type="text/css">
    #tr_btn_modify{
        display:none;
    }
</style>
 
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    //이미지 미리보기
    function readURL(input) {
        if(input.files && input.files[0]){
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#preview').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    //글 수정 클릭 시 버튼 활성화
    function fn_enable(obj) {//수정하기 클릭 시 텍스트 박스 활성화
        //텍스트 박스의 id로 접근해 disabled 속성을 false로 설정
        document.getElementById("i_title").disabled = false;
        document.getElementById("i_content").disabled = false;
        document.getElementById("i_imagefilename").disabled = false;
        document.getElementById("tr_btn_modify").style.display = "block";
        document.getElementById("tr_btn").style.display = "none";
    }
    
    //수정반영하기 클릭 시 컨트롤러에 수정 데이터를 전송
    function fn_modify_article(obj) {
        obj.action = "${contextPath}/board/modArticle.do";
        obj.submit();
    }
    
    //목록으로
    function backToList(obj) {
        obj.action = "${contextPath}/board/listArticles.do";
        obj.submit();
    }
    
    //글 삭제
    function fn_remove_article(url, articleno) {
        //자바스크립트를 이용해 동적으로 <form>태그 생성
        var form = document.createElement("form");
        form.setAttribute("method""post");
        form.setAttribute("action", url);
        
        //자바스크립트를 이용해 동적으로 <input> 태그를 생성한 후 name과 value를 articleno와 글 번호로 설정
        var articleNoInput = document.createElement("input");
        articleNoInput.setAttribute("type""hidden");
        articleNoInput.setAttribute("name""articleno");
        articleNoInput.setAttribute("value", articleno);
        
        form.appendChild(articleNoInput);//동적으로 생성된 <input>을 동적으로 생성한 <form>에 append
        
        //<form> 태그를 <body> 태그에 추가(append)한 후 서버에 요청
        document.body.appendChild(form);
        form.submit();
    }
    
    //답글 작성
    function fn_reply_form(url,parentno) {
        var form = document.createElement("form");
        form.setAttribute("method","post");
        form.setAttribute("action",url);//전달된 요청명을 <form>의 action에 설정
        var parentnoInput = document.createElement("input");
        
        //함수 호출 시 전달된 articleno 값을 <input>을 이용해 컨트롤러에 전달
        parentnoInput.setAttribute("type","hidden");
        parentnoInput.setAttribute("name","parentno");
        parentnoInput.setAttribute("value",parentno);
        
        form.appendChild(parentnoInput);
        document.body.appendChild(form);
        form.submit();
    }
</script>
</head>
<body>
    <form name="frmArticle" method="post" enctype="multipart/form-data">
        <table>
            <tr>
                <td width="150" align="center">글번호</td>
                <td>
                    <input type="text" value="${article.articleno}" disabled>
                    <!-- 글 수정 시 글 번호를 컨트롤러로 전송하기 위해 미리 hidden 태그를 이용해 글 번호 저장 -->
                    <input type="hidden" value="${article.articleno}" name="articleno">
                </td>
            </tr>
            <tr>
                <td width="150" align="center">작성자 아이디</td>
                <td><input type="text" value="${article.id}" disabled name="id"></td>
            </tr>
            <tr>
                <td width="150" align="center">제목</td>
                <td><input type="text" value="${article.title}" disabled name="title" id="i_title"></td>
            </tr>
            <tr>
                <td width="150" align="center">내용</td>
                <td>
                    <textarea rows="20" cols="60"  name="content"  id="i_content"  disabled />${article.content }</textarea>
                </td>
            </tr>
        <!-- imagefilename 값이 있으면 이미지를 표시 -->
        <!-- 이미지 수정에 대비해 hidden 태그에 원래 이미지 파일 이름을 저장 -->
        <!-- FileDownloadController 서블릿에 이미지 파일 이름과 글 번호를 전송해서 이미지를 img 태그에 표시 -->
        <!-- imagefilename으로 수정된 이미지 파일 이름을 전송 -->
        <c:if test="${not empty article.imagefilename && article.imagefilename != 'null'}">
            <tr>
                <td width="20%" align="center" rowspan="2">이미지</td>
                <td>
                    <input type="hidden" name="originalFileName" value="${article.imagefilename }">
                    <img src="${contextPath}/download.do?imagefilename=${article.imagefilename}&articleno=${article.articleno}" id="preview">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="file" name="imagefilename" id="i_imagefilename" onchange="readURL(this);" disabled>
                </td>
            </tr>
        </c:if>
            <tr>
                <td width="20%" align="center">등록일자</td>
                <td>
                    <input type="text" value='<fmt:formatDate value="${article.writedate}"/>' disabled>
                </td>
            </tr>
            <tr id="tr_btn_modify">
                <td colspan="2" align="center">
                    <input type="button" value="수정반영하기" onclick="fn_modify_article(frmArticle)">
                    <input type="reset" value="취소" onclick="backToList(frmArticle)">
                </td>
            </tr>
            <tr id="tr_btn">
                <td colspan="2" align="center">
                    <input type="button" value="수정하기" onclick="fn_enable(this.form)">
                    <!-- 삭제하기 클릭 시 fn_remove_article() 자바스크립트 함수를 호출하면서 articleno를 전달 -->
                    <input type="button" value="삭제하기" onclick="fn_remove_article('${contextPath}/board/removeArticle.do',${article.articleno})">
                    <input type="button" value="리스트로 돌아가기" onclick="backToList(this.form)">
                    <input type="button" value="답글쓰기" onclick="fn_reply_form('${contextPath}/board/replyForm.do',${article.articleno})">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
cs

 

replyForm.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
56
57
58
59
60
61
62
63
64
65
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>  
<%request.setCharacterEncoding("utf-8"); %>      
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>    
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
    //이미지 미리보기
    function readURL(input) {
        if(input.files && input.files[0]){
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#preview').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
    
    //목록으로
    function backToList(obj) {
        obj.action = "${contextPath}/board/listArticles.do";
        obj.submit();
    }
</script>    
</head>
<body>
    <h1 style="text-align: center">답글쓰기</h1>
    <form action="${contextPath}/board/addReply.do" method="post" name="frmReply" enctype="multipart/form-data">
        <table align="center">
            <tr>
                <td align="right">글쓴이 &nbsp;</td>
                <td><input type="text" size="5" value="lee" disabled></td>
            </tr>
            <tr>
                <td align="right">글제목 &nbsp;</td>
                <td><input type="text" size="67" name="title" maxlength="100"></td>
            </tr>
            <tr>
                <td align="right" valign="top">글내용 &nbsp;</td>
                <td>
                    <textarea rows="10" cols="65" name="content" maxlength="4000"></textarea>
                </td>
            </tr>
            <tr>
                <td align="right">이미지파일 첨부: </td>
                <td><input type="file" name="imagefilename" onchange="readURL(this)"></td>
                <td><img id="preview" src="#" width="200" height="200"></td>
            </tr>
            <tr>
                <td align="right"></td>
                <td>
                    <input type="submit" value="답글반영하기">
                    <input type="button" value="취소" onclick="bactToList(this.form)">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
cs

 

 

 

728x90