관리 메뉴

개발자취 남기는 블로그

2023-04-18 본문

백엔드

2023-04-18

미스터캉 2023. 4. 18. 14:26

 

최상위조건: 최상위 계층의 행을 식별하는 조건을 명시

계층형 구조 조건 : 계층형 구조가 어떤 식으로 연결되는지를 기술하는 부분

order siblings by : 레벨이 같은 형제 행에 한해서 정렬 (계층형 구조를 깨지 않고 정렬)


 

articleVO

package memberMVC.board;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Date;

public class ArticleVO {
	private int level; //글의 깊이를 저장하는 필드
	private int articleNo;
	private int parentNo;
	private String title;
	private String content;
	private String imageFileName;
	private Date writeDate;
	private String id;
	
	public ArticleVO () {
		System.out.println("ArticleVO 생성");
	}

	public ArticleVO(int level, int articleNo, int parentNo, String title, String content, String imageFileName,
			String id) {
		super();
		this.level = level;
		this.articleNo = articleNo;
		this.parentNo = parentNo;
		this.title = title;
		this.content = content;
		this.imageFileName = imageFileName;
		this.id = id;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public int getArticleNo() {
		return articleNo;
	}

	public void setArticleNo(int articleNo) {
		this.articleNo = articleNo;
	}

	public int getParentNo() {
		return parentNo;
	}

	public void setParentNo(int parentNo) {
		this.parentNo = parentNo;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getImageFileName() {
		try {
			if (imageFileName !=null && imageFileName.length() !=0) {
				imageFileName=URLDecoder.decode (imageFileName, "utf-8");
			}else {
				imageFileName=null; 
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("이미지 로딩중 에러");
		}
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		try {
			if (imageFileName !=null && imageFileName.length() !=0) {
				this.imageFileName=URLDecoder.decode (imageFileName, "utf-8"); 
			}else {
				imageFileName=null;
			}
		} catch (UnsupportedEncodingException e) {
			System.out.println("이미지 저장 중 에러");
		}
		this.imageFileName = imageFileName;
	}

	public Date getWriteDate() {
		return writeDate;
	}

	public void setWriteDate(Date writeDate) {
		this.writeDate = writeDate;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	
}

BoardController

package memberMVC.board;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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;


@WebServlet("/board/*")
public class BoardController extends HttpServlet {
	BoardService boardService;
	ArticleVO articleVO;
	
	@Override
	public void init() throws ServletException {
		boardService=new BoardService();
	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandle(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doHandle(request, response);
	}
	
	private void doHandle (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String nextPage=""; 
		String action=request.getPathInfo(); //요청명을 가져온다.
		try {
			List<ArticleVO> articleList=new ArrayList<ArticleVO>();
			if (action == null || action.equals("/listArticles.do")) {
				articleList=boardService.listArticles();
				request.setAttribute("articleList", articleList);
				nextPage="/boardinfo/listArticles.jsp";
			}else if (action.equals("/articleForm.do")) {
				nextPage="/boardinfo/articleForm.jsp";
			}
			RequestDispatcher dispatcher=request.getRequestDispatcher(nextPage);
			dispatcher.forward(request, response);			
		} catch (Exception e) {
			System.out.println("요청 처리 중 에러");
			e.printStackTrace();
		}
	}
}

BoardDAO

package memberMVC.board;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class BoardDAO {
	private Connection conn;
	private PreparedStatement pstmt;
	private DataSource dataFactory;
	
	public BoardDAO() {
		
	 try {
         //JNDI에 접근하기 위한 기본 경로 (java:/comp/env)를 지정
         Context ctx=new InitialContext();
         Context envContext=(Context)ctx.lookup("java:/comp/env");
         /*톰켓 context.xml에 설정한 name 값인 jdbc/oracle를 이용해 톰켓에 미리 연결한 DataSource를 받아옵니다.*/
         dataFactory=(DataSource)envContext.lookup("jdbc/oracle");
      } catch (Exception e) {
         System.out.println("오라클 연결 오류");
         e.printStackTrace();
      }
   }
	 // 글 목록
	   public List<ArticleVO> selectAllArticles() {
	      List<ArticleVO> articleList = new ArrayList<>();
	      
	      try {
	         conn = dataFactory.getConnection();
	         String query = "SELECT LEVEL, articleNo, parentNo, title, content, writeDate, id FROM boardtbl " + 
	                     "START WITH parentNo=0 CONNECT BY PRIOR articleNo=parentNo ORDER SIBLINGS BY articleNo DESC";
	         pstmt = conn.prepareStatement(query);
	         ResultSet rs = pstmt.executeQuery();
	         while(rs.next()) {
	            int level = rs.getInt("level"); // 계층형 글의 깊이(level 속성)
	            int articleNo = rs.getInt("articleNo");
	            int parentNo = rs.getInt("parentNo");
	            String title = rs.getString("title");
	            String content = rs.getString("content");
	            Date writeDate = rs.getDate("writeDate");
	            String id = rs.getString("id");
	            ArticleVO articleVO = new ArticleVO();
	            articleVO.setLevel(level);
	            articleVO.setArticleNo(articleNo);
	            articleVO.setParentNo(parentNo);
	            articleVO.setTitle(title);
	            articleVO.setContent(content);
	            articleVO.setWriteDate(writeDate);
	            articleVO.setId(id);
	            articleList.add(articleVO);
	         }
	         rs.close();
	         pstmt.close();
	         conn.close();
	      } catch (Exception e) {
	         System.out.println("글 목록 처리 중 에러");
	         e.printStackTrace();
	      }
	      return articleList;
	   }
	}

BoardService

package memberMVC.board;

import java.util.List;

public class BoardService {
	BoardDAO boardDAO;
	
	public BoardService () {
		boardDAO=new BoardDAO(); //생성자에서 BoardDAO 객체를 생성
	}
	
	public List<ArticleVO> listArticles() {
		List<ArticleVO> articleList=boardDAO.selectAllArticles();
		return articleList;
	}
}

articleForm

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
     isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%
	request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글쓰기 창</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
	function readImage(input) {
		if (input.files && input.files[0]) {
			let reader=new FileReader ();
			reader.onload = function (event) {
				$('#preview').attr('src',event.target.result);
			}
			reader.readAsDataURL (input.files[0]);
		}
		//다른 액션을 submit
		function toList(obj) {
			obj.action="${contextPath}/board/listArticles.do";
			obj.submit();
		}
	}
</script>
</head>
<body>
	<h2 align="center">새글 쓰기</h2>
	<form action="${contextPath}/board/addArticle.do" method="post" enctype="multipart/form-data">
		<table align="center">
			<tr>
				<td align="right">글제목 : </td>
				<td colspan="2"><input type="text" size="50" name="title"></td>
			</tr>
			<tr>
				<td align="right">글내용 : </td>
				<td colspan="2"><textarea rows="10" cols="50" name="content" maxlenght="4000"></textarea></td>
			</tr>
			<tr>
				<td align="right">이미지파일첨부 : </td>
				<td><input type="file" name="imageFileName" onchange="readImage(this)"></td>
				<td><img id="preview" src="#" width="200" height="200" alt=""></td>
			</tr>
			<tr>
				<td align="right">&nbsp;</td>
				<td colspan="2"></td>
				 <input type="submit" value="글쓰기">
				 <input type="button" value="목록보기" onclick="toList(this.form)">
			</tr>
		</table>
	</form>
</body>
</html>

listArticles

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 목록창</title>
</head>
<body>
	<table align="center" border="1" width="80%">
		<tr align="center" bgcolor="lightgreen">
			<th>글번호</th><th>작성자</th><th>제목</th><th>작성일</th>
		</tr>
		<c:choose>
			<c:when test="${empty articleList}">
				<tr>
					<td colspan="4" align="center">등록된 글이 없습니다. </td>
				</tr>
			</c:when>
			<c:when test="${!empty articleList}">
				<c:forEach var="article" items="${articleList}" varStatus="articleNum">
					<tr align="center">
						<td width="5%">${articleNum.count}</td>
						<td width="10%">${article.id}</td>
						<td align="left" width="50%">
							<span style="padding-left:10px"></span>
							<c:choose>
								<c:when test="${article.level > 1}">
									<c:forEach begin="1" end="${article.level}" step="1">
										<span style="padding-left:20px"></span>
									</c:forEach>
									[답변]<a href="${contextPath}/board/viewArticle.do?articleNo=${article.articleNo}">${article.title}</a>
								</c:when>
								<c:otherwise>
									<a href="${contextPath}/board/viewArticle.do?articleNo=${article.articleNo}">${article.title}</a>
								</c:otherwise>
							</c:choose>
						</td>
						<td width="10%">${article.writeDate}</td>
					</tr>
				</c:forEach>
			</c:when>
		</c:choose>
	</table>
	<p align="center"><a href="${contextPath}/board/articleForm.do">글쓰기</a></p>
</body>
</html>

'백엔드' 카테고리의 다른 글

2023-05-15  (0) 2023.05.15
2023-04-12  (0) 2023.04.12
2023-04-10  (0) 2023.04.10
2023-04-07  (0) 2023.04.07
2023-04-06  (0) 2023.04.06