23.04.28

이준영·2023년 4월 28일
0
post-custom-banner
페이지 모듈화
include / forward
			페이지의 일부분 분리 ... 호출해서 사용
            		디자인 분리  - include 액션태그 ( <jsp: ...
                    소스 코드 분리 - include directive ( <%@ ~~
모델1
	소스에 대한 고도화 된 분리 
    swing
    	dao
        to(vo)
    
모델2(나중)


TO는 가장 긴 select문을 기준으로 만들기



import문이나 중복되는 코드 include 디렉티브를 통해 통합하여 쓰기

include.jspf

게시판에서 중복된 것들 빼주기
try는 남겨두기
ex> list1.jsp 예시

이런식으로 다른 것들도 해주면 된다.



model1 : 게시판 코드 to dao 사용하기

  1. 새로 프로젝트 만들기 -> web-INF lib에 jdbc 드라이버 , meta-inf에 context.xml 넣어주기

  2. webapp에 필요한 것들 가져오기

  3. java Resources -> src/main/java에서 패키지 하나 만들어주고 to, dao 생성

3.1 => To 생성

3.2 => DAO 생성
각 게시판 클래스마다 사용할 메서드 만들기


  1. 각 게시판 클래스에는 to, dao import 해주고 데이터 가져오기

Write1_ok.jsp

try ~ finally부분 메서드로 보내고 메서드에서는 return flag해주기

Board.DAO

write1_ok.jsp

  1. write1_ok.jsp의 try ~ finally 부분 DAO에 해당 메서드 안에 넣기
  2. modelDAO에서 작업

후에 dao.boardWrite(to)로 안에 to를 넘겨줘서 호출을 하면
dao에서 받은 걸로 실행하고 그것에 대한 flag를 write1_ok.jsp에 넘겨줌!



list1.jsp

  1. ArrayList(BoardTO)를 리턴하도록 메서드 설정

  2. ArrayList 변수에 전체 데이터를 넣는 방식으로 코드작업후 데이터 리턴

BoardDAO.java

public ArrayList<BoardTO> boardList() {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		//stringbuilder 대신 사용할 것
		ArrayList<BoardTO> datas = new ArrayList<>();
		
		try {
			
			conn = this.dataSource.getConnection();
			
			String sql = "select seq, subject, writer, date_format(wdate, '%Y-%m-%d') wdate, 
            hit, datediff(now(), wdate) wgap from board order by seq desc";
			
			pstmt = conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			
			//to 생성 후 arraylist에 전부 추가하기
			while(rs.next()) {
				BoardTO to = new BoardTO();
				to.setSeq(rs.getString("seq"));
				to.setSubject(rs.getString("subject"));
				to.setWriter(rs.getString("writer"));
				to.setWdate(rs.getString("wdate"));
				to.setHit(rs.getString("hit"));
				to.setWgap(rs.getInt("wgap"));
				
				datas.add(to);
				
			}
			
		} catch(SQLException e) {
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if(rs != null) try { rs.close(); } catch(SQLException e) {} 
			if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
			if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
		return datas;
	}

list1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardDAO" %>
<%@ page import="java.util.ArrayList" %>

<%
	
	BoardDAO dao = new BoardDAO();
	
	ArrayList<BoardTO> datas = dao.boardList();
	
	request.setCharacterEncoding("utf-8");
	
	StringBuilder sbHtml = new StringBuilder();
	
	int totalcount = datas.size();
	
	//데이터 for로 읽기
	for(BoardTO to : datas) {		
		String seq = to.getSeq();
		String subject = to.getSubject();
		String writer = to.getWriter();
		String wdate = to.getWdate();
		String hit = to.getHit();
		int wgap = to.getWgap();

		sbHtml.append("<tr>");
		sbHtml.append("<td>&nbsp;</td>");
		sbHtml.append("<td>"+ seq +"</td>");
		sbHtml.append("<td class='left'>");
		sbHtml.append("<a href='board_view1.jsp?seq="+ seq + "'>" + subject + "</a>");
		if(wgap == 0) {
			sbHtml.append("&nbsp;<img src='../../images/icon_new.gif' alt='NEW'></td>");
		}
		sbHtml.append("<td>" + writer + "</td>");
		sbHtml.append("<td>" + wdate + "</td>");
		sbHtml.append("<td>" + hit + "</td>");
		sbHtml.append("<td>&nbsp;</td>");
		sbHtml.append("</tr>");
			
		}
	
%>


view1.jsp

입력과 출력을 동시에 하여 메서드에서도 seq를 매개변수로 줘서 데이터를 담고 to를 리턴하는 형식으로 만든다.

BoardDAO

public BoardTO boardView(BoardTO to) {
		//to로 받고 리턴
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {	
			conn = this.dataSource.getConnection();
			
			//조회수 증가
			String sql = "update board set hit = hit + 1 where seq = ?";
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, to.getSeq());
			
			pstmt.execute();
			
			sql = "select subject, writer, mail, wip, wdate, hit, content from board where seq = ?";
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, to.getSeq());
			
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				to.setSubject(rs.getString("subject"));		
				to.setWriter(rs.getString("writer"));		
				to.setMail(rs.getString("mail"));
				to.setWip(rs.getString("wip"));		
				to.setWdate(rs.getString("wdate"));		
				to.setHit(rs.getString("hit"));		
				to.setContent(rs.getString("content"));		
			}
			
		}  catch(SQLException e) {
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if(rs != null) try { rs.close(); } catch(SQLException e) {} 
			if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
			if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
		return to;
	}

view1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardDAO" %>

<%
	request.setCharacterEncoding("utf-8");

	BoardTO to = new BoardTO();	
	to.setSeq(request.getParameter("seq"));

	BoardDAO dao = new BoardDAO();
	
	to = dao.boardView(to);

	String seq = to.getSeq();
	
	String subject = to.getSubject();
	String writer = to.getWriter();
	String mail = to.getMail();
	String wip = to.getWip();
	String wdate = to.getWdate();
	String hit = to.getHit();
	String content = to.getContent().replaceAll("\n", "<br>");
		
	
%>


delete1 / modify1

view와 마찬가지로 to를 받아서 작업하고 to를 리턴하는 식으로 작업한다.

BoardDAO

public BoardTO boardModify(BoardTO to) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			
			conn = this.dataSource.getConnection();
			
			String sql = "select subject, writer, mail, content from board where seq = ?";
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, to.getSeq());
			
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				  to.setSubject(rs.getString("subject"));
				 to.setWriter(rs.getString("writer"));
				 to.setMail(rs.getString("mail"));
				 to.setContent(rs.getString("content"));
			}
			
		} catch(SQLException e) {
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if(rs != null) try { rs.close(); } catch(SQLException e) {} 
			if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
			if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
		}
		return to;
	}

modify1.jsp

<%@page import="model1.BoardTO"%>
<%@page import="org.mariadb.jdbc.internal.com.read.dao.Results"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO"  %>
<%@ page import="model1.BoardDAO"  %>
<%
	request.setCharacterEncoding("utf-8");

	BoardTO to = new BoardTO();

	to.setSeq(request.getParameter("seq"));

	BoardDAO dao = new BoardDAO();
	
	to = dao.boardModify(to);
	
	String seq = to.getSeq();
	String subject = to.getSubject();
	String writer = to.getWriter();
	//메일을 두개로 분리해서 사용하기 위함
	String[] mail = null;
    //rs에서 빼와서 여따 쓰기
	if(to.getMail().equals("")) {
		 mail = new String[] {"", ""};
	 }
	 else {
		 //@ 중심으로 mail1 과 2를 분리
		 mail = to.getMail().split("@");
	 }
	String content = to.getContent();
	
	
%>

delete도 형식 거의 똑같다.



delete1_ok.jsp

flag를 리턴받아야 하므로 to를 넘겨주고 int로 반환하는 형식

BoardDAO

public int boardDeleteOk(BoardTO to) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		int flag = 2;
		
		try {
			conn = this.dataSource.getConnection();
			
			String sql = "delete from board where seq = ? and password = ?";
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, to.getSeq());
			pstmt.setString(2, to.getPassword());
			
			int result = pstmt.executeUpdate();
			
			if(result == 1) {
				flag = 0;
			}
			else if(result ==0) {
				flag = 1;
			}
			
		} catch(SQLException e) {
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
			if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
		return flag;
	}

delete1_ok.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardDAO" %>

<%
	request.setCharacterEncoding("utf-8");

	BoardTO to = new BoardTO();
	
	to.setSeq(request.getParameter("seq"));
	to.setPassword(request.getParameter("password"));
	
	BoardDAO dao = new BoardDAO();

	int flag = dao.boardDeleteOk(to);
	
	out.println("<script type=text/javascript>");
	if(flag == 0) {
		out.println("alert('삭제 성공!')");
		out.println("location.href='board_list1.jsp'");
	}
	else if(flag == 1) {
		out.println("alert('비밀번호 오류')");		
		out.println("history.back()");	
	} else {
		out.println("alert('삭제 실패')");		
		out.println("history.back()");	
	}
	out.println("</script>");
%>

modify1_ok.jsp

delete1_ok.jsp와 마찬가지

BoardDAO

public int boardModifyOk(BoardTO to) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		int flag = 2;
		
		try {
			conn = this.dataSource.getConnection();
			
			String sql = "update board set subject = ?, mail = ?, content = ? where seq = ? and password = ?";
			
			pstmt = conn.prepareStatement(sql);
			
			
			pstmt.setString(1, to.getSubject());
			pstmt.setString(2, to.getMail());
			pstmt.setString(3, to.getContent());
			pstmt.setString(4, to.getSeq());
			pstmt.setString(5, to.getPassword());
			
			int result = pstmt.executeUpdate();
			
			if(result == 0) {
				flag = 1;
			}
			else if(result == 1) {
				flag = 0;
			}
			
			
		} catch(SQLException e) {
			System.out.println("[에러] : " + e.getMessage());
		} finally {
			if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
			if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
		}
		return flag;
	}

modify1_ok.jsp

<%@page import="org.mariadb.jdbc.internal.com.read.dao.Results"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardDAO" %>

<%
	request.setCharacterEncoding("utf-8");

	BoardTO to = new BoardTO();

	to.setSeq(request.getParameter("seq"));
	
	to.setSubject(request.getParameter("subject"));
	
	to.setMail("");
	if(!request.getParameter("mail1").equals("") && !request.getParameter("mail2").equals("")) { 
		to.setMail(request.getParameter("mail1") + "@" + request.getParameter("mail2"));
	}
	
	to.setPassword(request.getParameter("password"));
	to.setContent(request.getParameter("content"));

	
	BoardDAO dao = new BoardDAO();
	
	int flag = dao.boardModifyOk(to);
	
	//jsp코드로 자바스크립트로 만들기 위함
			out.println("<script type='text/javascript'>");
			if(flag == 0) {
				out.println("alert('수정 성공')");
				//modify 창으로 가기
				out.println("location.href='board_view1.jsp?seq=" + to.getSeq() + "';");
			}
			else if(flag ==1) {
				out.println("alert('비밀번호 오류')");		
				out.println("history.back()");
			}
			else {
				out.println("alert('글 수정 실패')");		
				out.println("history.back()");		
			}
			out.println("</script>");



페이지 분류

list에는 페이지 코드들도 분리할 수 있는데, 이것들은 기존 to에는 들어가지 않는 데이터다. 따라서 이 페이지 변수들을 받을 새로운 to가 필요하다.

위의 BoardTO / BoardDAO 말고도 BoardListTO라는 것을 만들어 주기

BoardListTO

BoardDAO

public BoardListTO boardList(BoardListTO listTO) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		int cpage = listTO.getCpage();
		
		int recordPerPage = listTO.getRecordPerPage();

		int blockPerPage = listTO.getBlockPerPage();

		try {
			conn = this.dataSource.getConnection();

			String sql = "select seq, subject, writer, date_format(wdate, '%Y-%m-%d') wdate, 
            hit, datediff(now(), wdate)wgap from board order by seq desc";
			pstmt = conn.prepareStatement(sql);

			rs = pstmt.executeQuery();

			rs.last();
			listTO.setTotalRecord(rs.getRow());
			rs.beforeFirst();

			listTO.setTotalPage( ( (listTO.getTotalRecord() - 1) / recordPerPage) + 1);

			// 바로 위에서 총 데이터 개수 얻고난 다음 / 현재페이지 어디서부터 읽을 것 인지.
			int skip = (cpage - 1) * recordPerPage;
			if (skip != 0)
				rs.absolute(skip);

			
			ArrayList<BoardTO> boardLists = new ArrayList<>();
			for (int i = 0; i < recordPerPage && rs.next(); i++) {
				BoardTO to = new BoardTO();
				
				to.setSeq(rs.getString("seq"));
				to.setSubject(rs.getString("subject"));
				to.setWriter(rs.getString("writer"));
				to.setWdate(rs.getString("wdate"));
				to.setHit(rs.getString("hit"));
				to.setWgap(rs.getInt("wgap"));
				
				boardLists.add(to);
			}
			
			listTO.setBoardList(boardLists);
			
			listTO.setStartBlock(cpage - (cpage-1) % blockPerPage);
			listTO.setEndBlock(cpage - (cpage-1) % blockPerPage + blockPerPage - 1);
			if(listTO.getEndBlock() >= listTO.getTotalPage()) {
				listTO.setEndBlock(listTO.getTotalPage()); 
			 }
			
			
		} catch (SQLException e) {
			System.out.println("[에러] " + e.getMessage());
		} finally {
			if(rs != null) try { rs.close(); } catch(SQLException e) {} 
			if(pstmt != null) try { pstmt.close(); } catch(SQLException e) {} 
			if(conn != null) try { conn.close(); } catch(SQLException e) {} 			
	}
		return listTO;
	}

list1.jsp

<%
int cpage = 1;
// cpage값이 넘겨져오면 세팅해달라 / 
if (request.getParameter("cpage") != null && !request.getParameter("cpage").equals("")) {
	cpage = Integer.parseInt(request.getParameter("cpage"));
}

	BoardListTO listTO = new BoardListTO();
	listTO.setCpage(cpage);
	
	BoardDAO dao = new BoardDAO();
	listTO = dao.boardList(listTO);

	//선언 후 페이지를 구성하기 위한 모든 요소를 가져옴
	int recordPerPage = listTO.getRecordPerPage();

	int totalRecord = listTO.getTotalRecord();
	
	int totalPage = listTO.getTotalPage();
	
	int blockPerPage = listTO.getBlockPerPage();
	
	int startBlock = listTO.getStartBlock();
	
	int endBlock = listTO.getEndBlock();

	ArrayList<BoardTO> boardLists = listTO.getBoardList();

	StringBuilder sbHtml = new StringBuilder();

	// 원하는 개수 만큼 읽기위해 for문 사용
	// rs.next()가 false가 되는순간 끝난다.
	for(BoardTO to : boardLists) {
		
		String seq = to.getSeq();
		String subject = to.getSubject();
		String writer = to.getWriter();
		String wdate = to.getWdate();
		String hit = to.getHit();
		int wgap = to.getWgap();
		
		sbHtml.append("<tr>");
		sbHtml.append("<td>&nbsp;</td>");
		sbHtml.append("<td>" + seq + "</td>");

		sbHtml.append("<td class='left'>");
		sbHtml.append("<a href='board_view1.jsp?seq=" + seq + "'>" + subject + "</a>");
		if (wgap == 0) {
			sbHtml.append("&nbsp;<img src='../../images/icon_new.gif' alt='NEW'>");
		}
		sbHtml.append("</td>");
		sbHtml.append("<td>" + writer + "</td>");
		sbHtml.append("<td>" + wdate + "</td>");
		sbHtml.append("<td>" + hit + "</td>");
		sbHtml.append("<td>&nbsp;</td>");
		sbHtml.append("</tr>");
	}
%>

다른 것은 아까것과 동일!

profile
끄적끄적
post-custom-banner

0개의 댓글