글쓰기, 글목록

문이빈·2023년 9월 5일
0
----------------MemberDAO.java----------------

package member.dao;

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

import member.bean.MemberDTO;

public class MemberDAO {

	private String driver = "oracle.jdbc.driver.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:xe";
	private String username = "c##java";
	private String password = "1234";
	
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	public MemberDAO() {
		try{
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public void getConnection() {
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isExistId(String id){
		boolean exist = false;
		String sql = "select * from member where id = ?";
		getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()) exist = true;
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return exist;
	}
	
	public void write(MemberDTO memberDTO) {
		String sql = "insert into member values(?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";
		getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql); //생성
			
			pstmt.setString(1, memberDTO.getName());
			pstmt.setString(2, memberDTO.getId());
			pstmt.setString(3, memberDTO.getPwd());
			pstmt.setString(4, memberDTO.getGender());
			pstmt.setString(5, memberDTO.getEmail1());
			pstmt.setString(6, memberDTO.getEmail2());
			pstmt.setString(7, memberDTO.getTel1());
			pstmt.setString(8, memberDTO.getTel2());
			pstmt.setString(9, memberDTO.getTel3());
			pstmt.setString(10, memberDTO.getZipcode());
			pstmt.setString(11, memberDTO.getAddr1());
			pstmt.setString(12, memberDTO.getAddr2());
			
			pstmt.executeUpdate();//실행			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public MemberDTO login(String id, String pwd){
		MemberDTO memberDTO = null;
		String sql = "SELECT * FROM MEMBER WHERE ID=? AND PWD=?";
		getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				memberDTO = new MemberDTO();
				memberDTO.setName(rs.getString("name"));
				memberDTO.setId(rs.getString("id"));
				memberDTO.setPwd(rs.getString("pwd"));
				memberDTO.setGender(rs.getString("gender"));
				memberDTO.setEmail1(rs.getString("email1"));
				memberDTO.setEmail2(rs.getString("email2"));
				memberDTO.setTel1(rs.getString("tel1"));
				memberDTO.setTel2(rs.getString("tel2"));
				memberDTO.setTel3(rs.getString("tel3"));
				memberDTO.setZipcode(rs.getString("zipcode"));
				memberDTO.setAddr1(rs.getString("addr1"));
				memberDTO.setAddr2(rs.getString("addr2"));
			}//if
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
		
		return memberDTO;
	}
}

----------------login.jsp----------------

<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="member.bean.MemberDTO"%>
<%@ page import="member.dao.MemberDAO"%>

<%
//데이터
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");

// DB
MemberDAO memberDAO = new MemberDAO();
MemberDTO memberDTO = memberDAO.login(id, pwd);

// 응답
request.setAttribute("name", "?");
request.setAttribute("pwd", "?");

%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% if(memberDTO == null) {
	response.sendRedirect("loginFail.jsp");
   }else{
	// response.sendRedirect("loginOk.jsp?name="+ URLEncoder.encode(name, "UTF-8"));
	
	// 쿠키
	/* 
	Cookie cookie = new Cookie("memName", name);
	cookie.setMaxAge(3*60*10); 						// 초 단위 - 30분 뒤 쿠키값 사라짐 
	response.addCookie(cookie); // 클라이언트에 저장
	
	Cookie cookie2 = new Cookie("memId", id);
	cookie2.setMaxAge(3*60*10);						// 초 단위 - 30분 뒤 쿠키값 사라짐 
	response.addCookie(cookie2); // 클라이언트에 저장 
	*/
	
	// 세션
	// HttpSession session = request.getSession();// 세션 생성 -> 내장객체 session이라는 객체가 있어서 Duplicate 오류
	session.setAttribute("memName", memberDTO.getName());
	session.setAttribute("memId", id);
	session.setAttribute("memEmail", memberDTO.getEmail1()+"@"+memberDTO.getEmail2());
	
	// session.setAttribute("memDTO", memberDTO); DTO 전체를 통으로 넘길 수 있음.
	
	
	response.sendRedirect("loginOk.jsp");
} %>
<!-- response.sendRedirect("loginOk.jsp");는 데이터를 넘길 수 없어서 주소로 넘겨주면 된다. -->
</body>
</html>

----------------index.jsp----------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>*** 메인화면 ***</h1>

<!-- memId 세션이 없으면 회원가입 로그인이 뜨게 -->
<% if(session.getAttribute("memId") == null){%>
<h3><a href="/memberJSP/member/writeForm.jsp">회원가입</a></h3> <!-- (앞에 http://localhost:8080 )절대번지 -->
<h3><a href="./member/loginForm.jsp">로그인</a></h3>			 <!-- 상대번지 -->

<%}else{%>
<!-- memId 세션이 있으면 로그아웃이 뜨게 -->
<h3><a href="./member/logout.jsp">로그아웃</a></h3>
<h3><a href="./board/boardWriteForm.jsp">글쓰기</a></h3>
<%}%>

<h3><a href="">목록</a></h3>

</body>
</html>

----------------boardWriteForm.jsp----------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse: collapse;
	padding: 10px;
}
#content{
	width: 300px;
	height: 400px;
}
#subjectDiv, contentDiv{
	color: red;
}

</style>
</head>
<body>
<!-- <form id = "boardWriteForm" method="post" action="boardWrite.jsp"> -->
<form id = "boardWriteForm" action="boardWrite.jsp">
<h3>글쓰기</h3>
	<table border="1" cellspacing ="0" cellpadding ="5">
		<tr>
			<th width="100" align ="center">글제목</th>
			<td>
				<input type="text" id="subject" name="subject">
				<div id="subjectDiv"></div>
			</td>
		</tr>
		
		<tr>
			<th>글내용</th>
			<td>
				<textarea id="content" name="content" rows="10" cols="40"></textarea>
				<div id="contentDiv"></div>
			</td>
		</tr>

		<tr>
			<td colspan="2" align="center">
				<input type="button" id="writeBtn" value="글쓰기">
				<input type="reset" value="다시작성">
			</td>
		</tr>
	</table>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.7.0.min.js"></</script>
<script src="../js/boardWrite.js"></script>
</body>
</html>

----------------boardWrite.jsp----------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="board.dao.BoardDAO"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>

<%
//데이터
request.setCharacterEncoding("UTF-8"); //한글처리 - post일 경우
String subject = request.getParameter("subject");
String content = request.getParameter("content");

String id = (String)session.getAttribute("memId");
String name = (String)session.getAttribute("memName");
String email = (String)session.getAttribute("memEmail");

Map<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("email", email);
map.put("subject", subject);
map.put("content", content);


//DB
BoardDAO boardDAO = new BoardDAO();
boardDAO.boardWrite(map);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%-- <h3>작성하신 글이 등록되었습니다.</h3> --%>

<script type="text/javascript">
/* window.onload=function(){
		alert("작성하신 글이 등록되었습니다."); - boardWrite.js에 써서
*/
	
	// 목록으로 이동 (아직까지 안해서 이렇게만 써놓을게)
}
</script>
</body>
</html>

----------------boardWrite.js----------------

$(function(){
		$('#writeBtn').click(function(){
		$('#subjectDiv').empty();
		$('#contentDiv').empty();
		
		if($('#subject').val()==''){
			$('#subjectDiv').text('제목을 입력하세요.');
			$('#subject').focus();
			
		}else if($('#content').val()==''){
			$('#contentDiv').text('내용을 입력하세요.');
			$('#content').focus();
			
		}else{
			//$('#boardWriteForm').submit();
			
			$.ajax({   // boardWrite에 갔다 와라 - 항상 이 자리로 돌아와라 -> 화면이동 없음
				type: 'post', // boardWriteForm에 method를 post방식을 빼버려도됨
				url: 'boardWrite.jsp',
				data: {
					'subject': $('#subject').val(),
					'content': $('#content').val()
				},
				success: function(){
					alert("작성하신 글을 저장하였습니다.")
				},
				error: function(){
					console.log(e);
				}
			}); 
			
		}
	});
});

----------------BoardDAO.java----------------

package board.dao;

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

public class BoardDAO {

	private String driver = "oracle.jdbc.driver.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:xe";
	private String username = "c##java";
	private String password = "1234";
	
	private Connection conn;
	private PreparedStatement pstmt;
	
	public BoardDAO() {
		try{
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public void getConnection() {
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void boardWrite(Map<String, String> map) {
		String sql = "insert into board(seq,id,name,email,subject,content,ref)"
				   + "values(seq_board.nextval,?,?,?,?,?,seq_board.currval)";
		getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql); //생성
			
			pstmt.setString(1, map.get("id"));
			pstmt.setString(2, map.get("name"));
			pstmt.setString(3, map.get("email"));
			pstmt.setString(4, map.get("subject"));
			pstmt.setString(5, map.get("content"));
			
			pstmt.executeUpdate(); //실행
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

CREATE TABLE board(
     seq NUMBER NOT NULL,                -- 글번호 (시퀀스 객체 이용)
     id VARCHAR2(20) NOT NULL,           -- 아이디
     name VARCHAR2(40) NOT NULL,         -- 이름
     email VARCHAR2(40),                 -- 이메일
     subject VARCHAR2(255) NOT NULL,     -- 제목
     content VARCHAR2(4000) NOT NULL,    -- 내용 

     ref NUMBER NOT NULL,                 -- 그룹번호
     lev NUMBER DEFAULT 0 NOT NULL,       -- 단계
     step NUMBER DEFAULT 0 NOT NULL,      -- 글순서
     pseq NUMBER DEFAULT 0 NOT NULL,      -- 원글번호
     reply NUMBER DEFAULT 0 NOT NULL,     -- 답변수

     hit NUMBER DEFAULT 0,                -- 조회수
     logtime DATE DEFAULT SYSDATE
 );

-- 시퀀스
CREATE SEQUENCE seq_board  NOCACHE NOCYCLE;

commit;


글목록

----------------index.jsp----------------

<h3><a href="./board/boardList.jsp?pg=1">목록</a></h3>

----------------BoardWirte.js----------------

success: function(){
					alert("작성하신 글을 저장하였습니다.");
					location.href='/boardList.jsp?pg=1';
                    
----------------boardList.java----------------

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="board.dao.BoardDAO"%>
<%@ page import="board.bean.BoardDTO"%>
<%@ page import="java.util.List" %>
<%@ page import="java.text.SimpleDateFormat" %>

<%
// 데이터
int pg = Integer.parseInt(request.getParameter("pg"));

// 1페이지당 5개씩만 꺼내올거임
int endNum = pg*5;
int startNum = endNum-4;

// DB
BoardDAO boardDAO = new BoardDAO();
List<BoardDTO> list = boardDAO.getBoardList(startNum, endNum);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse: collapse;
}
th, td{
  padding: 5px;
}
</style>
</head>
<body>
<% if(list != null){ %>
<table border="1" frame="hsides" rules="rows">
	<thead>
		<tr>
			<th width="100">글번호</th>
			<th width="400">제목</th>
			<th width="150">작성자</th>
			<th width="150">작성일</th>
			<th width="100">조회수</th>
		</tr>
	</thead>
	
	<tbody>
		<%for(BoardDTO boardDTO : list){ %>
		<tr>
	        <td align="center"><%= boardDTO.getSeq() %></td>
	        <td><%= boardDTO.getSubject() %></td>
	        <td align="center"><%= boardDTO.getId() %></td>
	        <td align="center"><%= new SimpleDateFormat("yyyy.MM.dd").format(boardDTO.getLogtime()) %></td>
	        <td align="center"><%= boardDTO.getHit() %></td>
		</tr>
		<%} %>
	</tbody>
</table>
<%} %>
</body>
</html>

----------------BoardDTO.java----------------

package board.bean;

import java.util.Date;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class BoardDTO {
	private int seq;
	private String id;
	private String name;
	private String email;
	private String subject;
	private String content;
	private int ref;
	private int lev;
	private int step;
	private int pseq;
	private int reply;
	private int hit;
	private	Date logtime;
}

----------------BoardDAO.java----------------

package board.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 java.util.List;
import java.util.Map;

import board.bean.BoardDTO;

public class BoardDAO {

	private String driver = "oracle.jdbc.driver.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:xe";
	private String username = "c##java";
	private String password = "1234";
	
	
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	public BoardDAO() {
		try{
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public void getConnection() {
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void boardWrite(Map<String, String> map) {
		String sql = "insert into board(seq,id,name,email,subject,content,ref)"
				   + "values(seq_board.nextval,?,?,?,?,?,seq_board.currval)";
		getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql); //생성
			
			pstmt.setString(1, map.get("id"));
			pstmt.setString(2, map.get("name"));
			pstmt.setString(3, map.get("email"));
			pstmt.setString(4, map.get("subject"));
			pstmt.setString(5, map.get("content"));
			
			pstmt.executeUpdate(); //실행
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public List<BoardDTO> getBoardList(int startNum, int endNum){
		List<BoardDTO> list = new ArrayList<BoardDTO>();
		String sql = "select * from"
				+ "(select rownum rn, tt.* from "
				+ "(select * from board order by seq desc)tt"
				+ ")where rn >= ? and rn <= ?;";
		getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setInt(1, startNum);
			pstmt.setInt(2, endNum);
			
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				BoardDTO boardDTO = new BoardDTO();
				boardDTO.setSeq(rs.getInt("seq"));
				boardDTO.setId(rs.getString("id"));
				boardDTO.setName(rs.getString("name"));
				boardDTO.setEmail(rs.getString("email"));
				boardDTO.setSubject(rs.getString("subject"));
				boardDTO.setContent(rs.getString("content"));
				boardDTO.setRef(rs.getInt("ref"));
				boardDTO.setLev(rs.getInt("lev"));
				boardDTO.setStep(rs.getInt("step"));
				boardDTO.setPseq(rs.getInt("pseq"));
				boardDTO.setReply(rs.getInt("reply"));
                boardDTO.setHit(rs.getInt("hit"));
				boardDTO.setLogtime(rs.getDate("logtime"));
				
				list.add(boardDTO);
			}//while
			
		} catch (SQLException e) {
			e.printStackTrace();
			list = null;
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
}

page2


Connection Pool

: 서버에 미리 Connection 를 설정해 놓는 것

: 데이터베이스와 연결된 커넥션을 미리 만들어서 풀(Pool)속에 저장해 두고 있다가 필요할 때 커넥션을 풀에서 가져다 쓰고 다시 풀에 반환(close) 하는 기법

: Connection의 내용이 바뀌면 서버만 수정해주면 된다

: 풀속에 미리 커넥션이 생성 되어있기 때문에 커넥션을 생성하는데 드는 연결시간이 소비되지 않는다

: 커넥션을 계속해서 재사용하기 때문에 생성되는 커넥션 수는 많지 않다

: 오라클 주소, 드라이버, ID, PW를 서버에 숨겨 놓음으로 보안에 좋다

: 서버의 Connection 들을 얻어오려면 javax.sql.DataSource 를 이용

: server.xml 에서<Context></Context>에 추가해야하는데 따로 context.xml를 만들어서 사용해보자

  • 필요한 라이브러리
    commons-collections-3.2.1.jar
    commons-dbcp-1.4.jar
    commons-pool-1.6.jar
    -> tomcat 안에 다 들어있음
  1. 서버 끄고

에 context.xml 파일 생성

server.xml 파일에서
<Context docBase="memberJSP" path="/memberJSP" reloadable="true" source="org.eclipse.jst.jee.server:memberJSP"/></Host>을 복사해오기

클라이언트는 DataSource를 따라가야함 절대로 Connection Pool에 직접 갈 수 없다.

----------------context.xml----------------

<?xml version="1.0" encoding="UTF-8"?>
<Context docBase="memberJSP" 
		 path="/memberJSP" 
		 reloadable="true" 
		 source="org.eclipse.jst.jee.server:memberJSP">
		 
<Resource name="jdbc/oracle" <!-- 이름은 아무렇게나 -->
		 type="javax.sql.DataSource" <!-- 은행 여직원 -->
		 driverClassName="oracle.jdbc.driver.OracleDriver" 
		 url="jdbc:oracle:thin:@localhost:1521:xe"
		 username="c##java"
		 password="1234"
		 maxACtive="20"
		 maxIdle="3"
		 removeAbandoned="true" />
</Context>

함으로서 dao 에서 적은것이 필요없어짐 -> 다시 새로 적었음

----------------MemberDAO.java----------------

package member.dao;

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

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

import member.bean.MemberDTO;

public class MemberDAO {

	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private DataSource ds;
	
	public MemberDAO() {
		try {
			Context context = new InitialContext();
			ds = (DataSource)context.lookup("java:comp/env/jdbc/oracle"); 
            // Tomcat 일 경우에만 java:comp/env/ 접두사 꼭 들어가야됨
            
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isExistId(String id){
		boolean exist = false;
		String sql = "select * from member where id = ?";
		
		try {
			conn = ds.getConnection(); 
            /DataSource로 부터 Connection을 가져온다. try catch 안으로 
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()) exist = true;
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return exist;
	}
	
	public void write(MemberDTO memberDTO) {
		String sql = "insert into member values(?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";
		
		
		try {
			conn = ds.getConnection();
			
			pstmt = conn.prepareStatement(sql); //생성
			
			pstmt.setString(1, memberDTO.getName());
			pstmt.setString(2, memberDTO.getId());
			pstmt.setString(3, memberDTO.getPwd());
			pstmt.setString(4, memberDTO.getGender());
			pstmt.setString(5, memberDTO.getEmail1());
			pstmt.setString(6, memberDTO.getEmail2());
			pstmt.setString(7, memberDTO.getTel1());
			pstmt.setString(8, memberDTO.getTel2());
			pstmt.setString(9, memberDTO.getTel3());
			pstmt.setString(10, memberDTO.getZipcode());
			pstmt.setString(11, memberDTO.getAddr1());
			pstmt.setString(12, memberDTO.getAddr2());
			
			pstmt.executeUpdate();//실행			
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public MemberDTO login(String id, String pwd){
		MemberDTO memberDTO = null;
		String sql = "SELECT * FROM MEMBER WHERE ID=? AND PWD=?";
		
		try {
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				memberDTO = new MemberDTO();
				memberDTO.setName(rs.getString("name"));
				memberDTO.setId(rs.getString("id"));
				memberDTO.setPwd(rs.getString("pwd"));
				memberDTO.setGender(rs.getString("gender"));
				memberDTO.setEmail1(rs.getString("email1"));
				memberDTO.setEmail2(rs.getString("email2"));
				memberDTO.setTel1(rs.getString("tel1"));
				memberDTO.setTel2(rs.getString("tel2"));
				memberDTO.setTel3(rs.getString("tel3"));
				memberDTO.setZipcode(rs.getString("zipcode"));
				memberDTO.setAddr1(rs.getString("addr1"));
				memberDTO.setAddr2(rs.getString("addr2"));
			}//if
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
		
		return memberDTO;
	}
}

BoardDAO도 같은 형식으로 바꿔줌.

----------------BoardDAO.java----------------

package board.dao;

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

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

import board.bean.BoardDTO;

public class BoardDAO {

	
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	private DataSource ds;
	
	public BoardDAO() {
		try {
			Context context = new InitialContext();
			ds = (DataSource)context.lookup("java:comp/env/jdbc/oracle");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public void boardWrite(Map<String, String> map) {
		String sql = "insert into board(seq,id,name,email,subject,content,ref)"
				   + "values(seq_board.nextval,?,?,?,?,?,seq_board.currval)";
		
		
		try {
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(sql); //생성
			
			pstmt.setString(1, map.get("id"));
			pstmt.setString(2, map.get("name"));
			pstmt.setString(3, map.get("email"));
			pstmt.setString(4, map.get("subject"));
			pstmt.setString(5, map.get("content"));
			
			pstmt.executeUpdate(); //실행
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public List<BoardDTO> getBoardList(int startNum, int endNum){
		List<BoardDTO> list = new ArrayList<BoardDTO>();
		 String sql = "select * from"
	                + "(select rownum rn, tt.* from"
	                + "(select * from board order by seq desc)tt"
	                + ") where rn>=? and rn<=?";
		
		
		try {
			conn = ds.getConnection();
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setInt(1, startNum);
			pstmt.setInt(2, endNum);
			
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				BoardDTO boardDTO = new BoardDTO();
				boardDTO.setSeq(rs.getInt("seq"));
				boardDTO.setId(rs.getString("id"));
				boardDTO.setName(rs.getString("name"));
				boardDTO.setEmail(rs.getString("email"));
				boardDTO.setSubject(rs.getString("subject"));
				boardDTO.setContent(rs.getString("content"));
				boardDTO.setRef(rs.getInt("ref"));
				boardDTO.setLev(rs.getInt("lev"));
				boardDTO.setStep(rs.getInt("step"));
				boardDTO.setPseq(rs.getInt("pseq"));
				boardDTO.setReply(rs.getInt("reply"));
                boardDTO.setHit(rs.getInt("hit"));
				boardDTO.setLogtime(rs.getDate("logtime"));
				
				list.add(boardDTO);
			}//while
			
		} catch (SQLException e) {
			e.printStackTrace();
			list = null;
		} finally {
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
}

숙제 : 작성한 글 확인

0개의 댓글