초보 개발자의 기록

객체 본문

JAVA/JSP

객체

bambinodeveloper 2020. 12. 6. 22:42
728x90

유지보수성을 고려?

웹, 응용 모두 사용가능한 상태의 객체

 

CRUD를 전담하는 객체: DAO,VO(DTO)

package board.gui;

public enum Pages {
	BoardList, BoardWrite, BoardContent 
}

쿼리문을 먼저 작성하며 코드의 순서를 생각해서 작성해야함

public void update(){}

1> 쿼리문 작성String sql ="UPDATE notice SET author=?, title=?, content=? WHERE notice_id=?";

2> 데이터 베이스 접속 Connection

                              Connection con = null;

3> 쿼리문 수행 객체 PreparedStatement

                           PreparedStatement pstmt = null;

4> 선언한 순서대로 메모리에 올림

     con = dbManager.getConnection();

     pstmt = con.prepareStatement(sql);

5> pstmt - try{

                  pstmt = con.prepareStatement(sql);  // 6> 준비

                  pstmt.setString(1, notice.getAuthor)()); // 8> 바인드 변수

                  pstmt.setString(2, notice.getTitle());

                  pstmt.setString(3, notice.getContent());

                  pstmt.setString(4, notice.getNotice_id());

                  int result = pstmt.executeQuery(); // 9> 쿼리수행  

               }catch (SQLException e){

                  e.printStackTrace();

               }

               return result; // 10> result 반환

7> 한건의 데이터 가져오기 public void update(Notice notice){} //VO가져오기

11> result 반환시 지역변수 접근 불가능하므로, try 문 바깥으로 int result 올림

       int result = 0;

       result = pstmt.executeQuery();

12> public int update(Notice notice){} //int반환

13> finally{

         dbManager.release(con, pstmt);

         }

 

Pages.java

package board.gui;

public enum Pages {
	BoardList, BoardWrite, BoardContent 
}

 

DBManager.java

/*
데이터베이스 접속 및 해제와 관련된 코드가 너무 중복되므로 , 공통의 로직으로 분리시켜 재사용하기 위함
*/
package db;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBManager {
	String driver = "org.mariadb.jdbc.Driver";
	String url = "jdbc:mariadb://localhost:3307/db1202";
	String user = "root";
	String password = "1234";

	// 접속객체 얻기
	public Connection getConnection() {
		Connection con = null; // return 시키기 위해
		try {
			Class.forName(driver); // 드라이버 로드!
			System.out.println("드라이버 로드 성공");

			// 접속 시도
			con = DriverManager.getConnection(url, user, password);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("드라이버를 로드할 수 없네요");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}

	// 자원해제
	public void release(Connection con) { // 쿼리문 수행 안했을때
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void release(Connection con, PreparedStatement pstmt) {// DML용
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void release(Connection con, PreparedStatement pstmt, ResultSet rs) { // select용
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

BoardContent.java

package board.gui;

import java.awt.Dimension;

import javax.security.auth.callback.ConfirmationCallback;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import board.model.Notice;
import board.model.NoticeDAO;

public class BoardContent extends Page {
	JTextField t_author;
	JTextField t_title;
	JTextArea area;
	JScrollPane scroll;
	JButton bt_list, bt_edit, bt_del;
	Notice notice; //VO
	NoticeDAO noticeDAO; //DAO

	public BoardContent(BoardMain boardMain) {
		super(boardMain);

		// 생성
		t_author = new JTextField();
		t_title = new JTextField();
		area = new JTextArea();
		scroll = new JScrollPane(area);
		bt_list = new JButton("목록으로");
		bt_edit = new JButton("수정");
		bt_del = new JButton("삭제");
		noticeDAO = new NoticeDAO(); // DAO생성

		// 스타일
		t_author.setPreferredSize(new Dimension((int) this.getPreferredSize().getWidth() - 10, 25));
		t_title.setPreferredSize(new Dimension((int) this.getPreferredSize().getWidth() - 10, 25));
		scroll.setPreferredSize(new Dimension((int) this.getPreferredSize().getWidth() - 10, 500));

		// 조립
		add(t_author);
		add(t_title);
		add(scroll);
		add(bt_list);
		add(bt_edit);
		add(bt_del);

		// 목록버튼에 리스너 연결
		bt_list.addActionListener((e) -> {
			boardMain.showPage(Pages.valueOf("BoardList").ordinal());
		});

		// 수정버튼에 리스너 연결
		bt_edit.addActionListener((e) -> {
			if (JOptionPane.showConfirmDialog(BoardContent.this, "수정하시겠습니까?") == JOptionPane.OK_OPTION) {
				edit();
			}
		});

		// 삭제버튼에 리스너 연결
		bt_del.addActionListener((e) -> {
			if (JOptionPane.showConfirmDialog(BoardContent.this, "삭제하시겠습니까?") == JOptionPane.OK_OPTION) {
				del();
			}
		});
	}

	public void del() {
		// 삭제하고 목록보여주기
		int result = noticeDAO.delete(notice.getNotice_id());
		if (result == 0) {
			JOptionPane.showMessageDialog(this, "삭제실패");
		} else {
			JOptionPane.showMessageDialog(this, "삭제성공");
			BoardList boardList = (BoardList) boardMain.pageList[Pages.valueOf("BoardList").ordinal()];
			boardList.getList(); //데이터가져오기
			boardList.table.updateUI(); //화면갱신
			boardMain.showPage(Pages.valueOf("BoardList").ordinal());

		}
	}

	public void edit() {
		// DAO를 이용하여 수정작업 수행
		// 작성자, 제목, 내용만 교체
		notice.setAuthor(t_author.getText()); // 새로운 값
		notice.setTitle(t_title.getText());
		notice.setContent(area.getText());

		int result = noticeDAO.update(notice);
		if (result == 0) {
			JOptionPane.showMessageDialog(this, "수정실패");
		} else {
			JOptionPane.showMessageDialog(this, "수정성공");
		}
	}

	// 컴포넌트에 데이터 채워넣기
	// 이 메서드를 호출하는 자는, 한건의 데이터를 VO에 담아서 호출하면 된다!
	public void setData(Notice notice) {
		this.notice = notice;// 나중에 사용할 것을 대비해서 보관해놓기!
		t_author.setText(notice.getAuthor());
		t_title.setText(notice.getTitle());
		area.setText(notice.getContent());
	}

}

 

NoticeDAO.java

/*
 * DAO란? 
 *-Data Access Object를 의미하는 어플리케이션의 설계분야 용어
 *-Data Access 란 데이터베이스와의 CRUD 작업을 전담한다는 의미
 *CRUD(Create=insert Read=select Update Delete)
 * */

package board.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import db.DBManager;

public class NoticeDAO {
	DBManager dbManager = new DBManager();

	// 재사용성 고려하지 않은 swing만의 로직 작성
	// insert는 글 한건 ~ 하나의 VO
	public int regist(Notice notice) {
		Connection con = null;
		PreparedStatement pstmt = null;
		int result = 0; // 글 등록 후 그 결과값 보관

		con = dbManager.getConnection();

		String sql = "INSERT INTO notice(author, title, content) VALUES(?,?,?)";
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, notice.getAuthor()); // 작성자
			pstmt.setString(2, notice.getTitle()); // 제목
			pstmt.setString(3, notice.getContent()); // 내용

			result = pstmt.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbManager.release(con, pstmt);
		}
		return result;
	}

	// 모든 레코드 가져오기!
	public ArrayList<Notice> selectAll() {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ArrayList<Notice> list = new ArrayList<Notice>(); // rs를 대체할 녀석

		String sql = "SELECT * FROM notice order by notice_id desc";

		con = dbManager.getConnection();
		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();

			// rs는 레코드가 복수개 이므로, 즉 여러개 이므로, VO또한 여러개가 필요하도
			// 이 VO를 한꺼번에 모아서 반환해야하므로 집합형 자료형이 필요하다!
			// 객체를 모아놓은 집합을 지원하는 프레임웍은 CollectionFramework이므로,
			// 이 중 하나의 api를 이용해본다

			while (rs.next()) {
				Notice notice = new Notice(); // 텅빈 empty상태의 vo 생성
				// notice에 rs의 정보를 모두~ 옮겨심자
				notice.setNotice_id(rs.getInt("notice_id"));
				notice.setAuthor(rs.getString("author"));
				notice.setTitle(rs.getString("title"));
				notice.setContent(rs.getString("content"));
				notice.setRegdate(rs.getString("regdate"));
				notice.setHit(rs.getInt("hit"));

				// notice변수가 사라지기 전에, 얼른 list에 담자
				list.add(notice);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbManager.release(con, pstmt, rs);
		}
		return list; // rs가 아닌 ArrayList를 반환하자
	}

	// 게시물 1건 가져오기(상세보기)
	public Notice select(int notice_id) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Notice notice = null; // rs대신 데이터 1건을 담을 객체

		String sql = "SELECT * FROM notice WHERE notice_id=?";

		con = dbManager.getConnection(); // 접속객체 얻기
		try {
			pstmt = con.prepareStatement(sql); // 쿼리준비
			pstmt.setInt(1, notice_id); // 바인드 변수값 지정
			rs = pstmt.executeQuery();// 쿼리실행

			// 지금 탄생한 rs는 곧 죽는다 따라서 rs를 대체할 객체가 필요하다
			// rs는 레코드 한건을 담는 객체이므로, 레코드 1건을 담아 전달용으로 사용되는 VO를 이용하자
			if (rs.next()) {// 레코드가 존재하는 것임! 따라서 이때 VO를 올리자!
				notice = new Notice(); // 텅빈 empty상태의 vo 생성
				// notice에 rs의 정보를 모두~ 옮겨심자
				notice.setNotice_id(rs.getInt("notice_id"));
				notice.setAuthor(rs.getString("author"));
				notice.setTitle(rs.getString("title"));
				notice.setContent(rs.getString("content"));
				notice.setRegdate(rs.getString("regdate"));
				notice.setHit(rs.getInt("hit"));
			}

			// 조회수 증가
			sql = "UPDATE notice SET hit=hit+1 WHERE notice_id=?";
			pstmt = con.prepareStatement(sql); //원래 pstmt는 쿼리문마다 하나씩 필요함 
			pstmt.setInt(1, notice_id);
			pstmt.executeUpdate();
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			dbManager.release(con, pstmt, rs);
		}
		return notice;
	}

	// 게시물 1건 수정
	// 잘모를경우 반환을 void로 해두고 마지막에 변경해도됨
	public int update(Notice notice) {
		Connection con = null;
		PreparedStatement pstmt = null;
		int result = 0;

		String sql = "UPDATE notice SET author=?, title=?, content=? WHERE notice_id=?";

		con = dbManager.getConnection();
		try {
			pstmt = con.prepareStatement(sql); // 준비
			pstmt.setString(1, notice.getAuthor());
			pstmt.setString(2, notice.getTitle());
			pstmt.setString(3, notice.getContent());
			pstmt.setInt(4, notice.getNotice_id());
			result = pstmt.executeUpdate(); // 쿼리 수행

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbManager.release(con, pstmt);
		}
		return result;
	}

	// 삭제하기
	public int delete(int notice_id) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = "DELETE  FROM notice WHERE notice_id=?";
		int result = 0;

		con = dbManager.getConnection();
		try {
			pstmt = con.prepareStatement(sql); // 준비
			pstmt.setInt(1, notice_id);
			result = pstmt.executeUpdate(); // 수행
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbManager.release(con, pstmt);
		}
		return result;
	}
}

 

edit.jsp

<%@page import="board.model.Notice"%>
<%@page import="board.model.NoticeDAO"%>
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="db.DBManager"%>
<%@ page import="java.sql.*"%>
<%@ include file="/inc/lib.jsp"%>
<%
	/*
	수정 요청을 처리하는 jsp ... 수정 후 상세보기 페이지로 전환할 것이므로,
	디자인이 필요없고 오직 db로직만 있으면 됨
	*/
	request.setCharacterEncoding("utf-8"); //전송 파라미터들에 대한 인코딩 처리(받기전에 처리하자)
	String author  = request.getParameter("author"); //작성자
	String title  = request.getParameter("title"); //제목
	String content  = request.getParameter("content"); //내용
	String notice_id  = request.getParameter("notice_id"); //notice_id
	
	Notice notice = new Notice(); //empty상태임
	notice.setAuthor(author);
	notice.setTitle(title);
	notice.setContent(content);
	notice.setNotice_id(Integer.parseInt(notice_id));
	
	NoticeDAO noticeDAO = new NoticeDAO();
	
	int result = noticeDAO.update(notice); //DML쿼리수행

	if(result==0){
		out.print(getMsgBack("수정실패"));
	}else{
		out.print(getMsgURL("수정성공","/board/detail.jsp?notice_id="+notice_id));
	}
%>

 

delete.jsp

<%@page import="board.model.NoticeDAO"%>
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="db.DBManager"%>
<%@ page import="java.sql.*"%>
<%@ include file="/inc/lib.jsp"%>
<%
	String notice_id = request.getParameter("notice_id"); //웹에서 주고받는 모든 데이터는 문자
	NoticeDAO noticeDAO = new NoticeDAO();
	
	int result = noticeDAO.delete(Integer.parseInt(notice_id)); //DML수행

	if(result==0){
		out.print(getMsgBack("삭제실패"));
	}else{
		out.print(getMsgURL("삭제성공","/board/list.jsp"));
	}
%>
728x90
반응형

'JAVA > JSP' 카테고리의 다른 글

이미지 업로드- commons(Apache)  (0) 2020.12.08
이미지 업로드-cos.jar(Oreilly)  (0) 2020.12.07
게시판만들기(EditPlus)  (0) 2020.12.06
로그인폼 만들기  (0) 2020.12.04
JSP 내장객체(Built-In Object)  (0) 2020.12.03