(jsp/servlet)문의사항 게시판 프로젝트!!

SoonMin·2021년 3월 21일
0

개발환경

  • Server OS : Mac OS
  • Language : JAVA 1.8
  • WEB Server : Apache
  • WAS : Tomcat8
  • DB : MySQL

드디어 내가 생각했던 기능 구현을 모두 마쳤다 ㅠㅠ 기능들을 구현하는 세세한 과정들을 일일이 블로그에 못올려서 아쉽지만 아직은 개발이 너무 미숙해서 블로그와 병행해서 하기가 힘들었다는 변명을....




프로젝트를 진행하면서 가장 어려웠던 부분은??


누군가 나에게 위와같이 물어본다면 나는 1.관리자 게시판2.답글구현 이라고 말하고싶다..

1.관리자 게시판(3.에서 다시 재수정 완료)

회원페이지를 구현할땐 아래에 ★ 표시 메소드에서 처럼 id값을 얻어와서 페이지에 해당 id만 뿌려주는 식으로 했다. 그리고 id값을 통해 닉네임을 얻어서 게시판에 닉네임이 표현되게 만들었다.

관리자 페이지에선 모든 유저의 데이터가 보여야하고 회원페이지와 마찬가지로 닉네임이 보이게 하려 했었다. 모든 유저의 데이터를 가져오는건 쉬웠지만 닉네임까지 가져오는건 약간의 멘붕이였다...

그래서 약간의 꼼수를 부려서 Notice DTO에 Member의 닉네임을 저장하는 멤버 변수를 하나 만들었다. 아래에 ♣︎ 에서 처럼 Member DAO에 있던 메소드를 가져와서 id값을 얻어와서 닉네임까지 얻을수 있게 만들었다.

(3.관리자 게시판에서 닉네임을 보여주는거에서 실수를 했다.)

굳이 Member DAO 객체를 불러와서 id값으로 닉네임을 뽑아주는 함수를 부를 필요 없이 에초에 쿼리에서 해결을 하면 됐었다.. 뭔가 찝찝했었는데 기본적인 inner join이 떠올라서 코드 수정을 해봤다.
쿼리문은 아래와 같다.

그리고 아래와같이 DAO코드도 보기좋게 개선이 된거 같다.

	// 관리자용 
	public List<NoticeDTO> getAllBoard(int startRow, int endRow){
		
		List<NoticeDTO> list = new ArrayList<NoticeDTO>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		String sql = "select * from(select * from writer order by ref desc, re_step asc) as tb limit ?,?";

		conn = getConnection();

		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, startRow-1);
			pstmt.setInt(2, endRow - (startRow-1));
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				MemberDAO dao = MemberDAO.getInstance();
				NoticeDTO dto = new NoticeDTO();
				
				dto.setId(rs.getInt("ID"));
				dto.setTitle(rs.getString("TITLE"));
				dto.setWriter_id(rs.getString("WRITER_ID"));
				dto.setContent(rs.getString("CONTENT"));
				dto.setRegdate(rs.getDate("REGDATE"));
				dto.setFiles(rs.getString("FILES"));
				dto.setRef(rs.getInt("REF"));
				dto.setRe_step(rs.getInt("RE_STEP"));
				dto.setRe_level(rs.getInt("RE_LEVEL"));
				dto.setName(rs.getString("NAME"));
				
				list.add(dto);

			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs != null) rs.close();
				if(rs != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return list;
	}
	

2.답글구현

답글구현은 다른 기능들을 다 마친후 마지막에 하려고 안하고 있었다. 그런데 여기서 문제가 생겼다.. 게시판테이블의 자식테이블을 하나더 만들어야 한다는 것이였다ㅠㅠㅠ
테이블을 하나 더 만들어서 진행하기엔 내 프로젝트가 꼬여버릴거 같다는 불안감에 나는 기존의 게시판 테이블에 ref(답글을 달 id값을 얻음),re_step(답글 순서),re_level(들여쓰기 뎁스) 이렇게 세개의 컬럼을 추가했다.

하지만, 또 문제가 생겨버렸다ㅠㅜ 답글을 달아버리면 관리자 게시판에 해당 글이 나와버린다는 것이였다. 내가 원하는건 관리자가 문의사항에 댓글을 달면 관리자 게시판에 보이지 않고 회원게시판에만 표시되는것이였다.
그래도 이 문제는 금방 해결되었다. 서블릿에서 처리하지 않고 게시판글을 보여주는 jsp에 jstl 사용해서 조건을 걸어줘서 보이지 않게 해줬다.



프로젝트를 진행하면서 느낀점


간단한 프로젝트였지만 우여곡절이 너무 많았다. 중간에 포기하고 싶었지만 그래도 끝까지 부여 잡으면서 결국 내가 생각한 기능들을 다 구현하긴 했다.
한가지 아쉬운점은 기능들을 너무 하드코딩으로 구현한게 아닐까? 라는 생각이 든다.
공부를 더 열심히해서 기능적으로도 완벽하고 코드도 좀더 깔끔하게 짜보고싶다.




프로젝트 진행 과정!!


문의사항 게시판 프로젝트를 진행하며 테이블은 두개를 사용하기로 결정을 했다. 하나는 회원정보를 관리하는 테이블과 나머지 하나는 게시판글을 관리하는 테이블이다. 테이블 구조는 아래와 같다.
			  <MEMBER TABLE>
              
              
+---------+-------------+------+-----+-------------------+-------------------+
| Field   | Type        | Null | Key | Default           | Extra             |
+---------+-------------+------+-----+-------------------+-------------------+
| UID     | varchar(20) | NO   | PRI | NULL              |                   |
| PWD     | varchar(50) | NO   |     | NULL              |                   |
| NAME    | varchar(50) | NO   | UNI | NULL              |                   |
| ADDRESS | varchar(50) | NO   |     | NULL              |                   |
| TEL     | varchar(20) | NO   |     | NULL              |                   |
| REGDATE | timestamp   | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+---------+-------------+------+-----+-------------------+-------------------+
			  <NOTICE TABLE>
+-----------+---------------+------+-----+-------------------+-------------------+
| Field     | Type          | Null | Key | Default           | Extra             |
+-----------+---------------+------+-----+-------------------+-------------------+
| ID        | int           | NO   | PRI | NULL              | auto_increment    |
| TITLE     | varchar(100)  | NO   |     | NULL              |                   |
| WRITER_ID | varchar(50)   | NO   |     | NULL              |                   |
| CONTENT   | mediumtext    | NO   |     | NULL              |                   |
| REGDATE   | timestamp     | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
| FILES     | varchar(1000) | YES  |     | NULL              |                   |
| REF       | int           | YES  |     | NULL              |                   |
| RE_STEP   | int           | YES  |     | NULL              |                   |
| RE_LEVEL  | int           | YES  |     | NULL              |                   |
+-----------+---------------+------+-----+-------------------+-------------------+

우선 테이블과 프론트의 구성을 다 마치고 DTO와 DAO코드 작성을 했다.
DAO는 정확히 어떤 메소드들이 필요한지 감이 안잡혀서 일단 기능들을 구현하면서 필요한것이 생기면 그때그때 만드는식으로 진행을 했다.

package com.notice.web.model;

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

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

public class NoticeDAO {

private static NoticeDAO dao;
private NoticeDAO() {}
public static NoticeDAO getInstance() {
	if(dao == null) {
		dao = new NoticeDAO();
	}
	return dao;
} // getInstance


private static Connection getConnection(){
	Connection conn = null;
	
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/MysqlDB");
			conn = ds.getConnection();
		}catch(NamingException e) {
			e.printStackTrace();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}  // getConnection


public int insert(String title, String writerid, String content, String files) {
	int result = 0;
	Connection con = null;
	PreparedStatement st = null;
	ResultSet rs = null;
	String sql = "SELECT MAX(REF) FROM NOTICE";
	
	int ref = 0;
	int re_step = 1;
	int re_level = 1;
	
	con = getConnection();
	
	try {
		st = con.prepareStatement(sql);
		rs = st.executeQuery();
		
		if(rs.next()) {
			ref = rs.getInt(1) + 1;
		}
		st.close();
		
		
		String sql2 = "INSERT INTO NOTICE VALUES(0,?,?,?,default, ?,?,?,?)";
		st = con.prepareStatement(sql2);
		st.setString(1,title);
		st.setString(2, writerid);
		st.setString(3, content);
		st.setString(4,files);
		st.setInt(5, ref);
		st.setInt(6, re_step);
		st.setInt(7, re_level);
		
		result = st.executeUpdate();
		
	}catch(SQLException e) {
		e.printStackTrace();
	}finally {
		try {
			if(st != null) {st.close();}
			if(rs != null) {rs.close();}
			if(con != null) {con.close();}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	return result;
	
} // insert



// 답변글 DB에 등록하기
// method 이름 + 매개변수 : reInsertBoard(BoardDTO dto)
// return type : void
public void reInsertBoard(NoticeDTO dto) {
	Connection conn = null;
	PreparedStatement pstmt = null;
	
	String sql1 = "UPDATE NOTICE SET RE_LEVEL = RE_LEVEL + 1 WHERE REF=? AND RE_LEVEL > ?";
	String sql2 = "INSERT INTO NOTICE VALUES(0,?,?,?,default, ?,?,?,?)";
	
	int ref = dto.getRef();
	int re_step = dto.getRe_step();
	int re_level = dto.getRe_level();
	
	conn = getConnection();
	
	try {
		pstmt = conn.prepareStatement(sql1);
		pstmt.setInt(1, ref);
		pstmt.setInt(2, re_level);
		pstmt. executeUpdate();
		pstmt.close();

		pstmt = conn.prepareStatement(sql2);
		pstmt.setString(1, dto.getTitle());
		pstmt.setString(2,dto.getWriter_id());
		pstmt.setString(3, dto.getContent());
		pstmt.setString(4, dto.getFiles());
		pstmt.setInt(5, ref); 
		pstmt.setInt(6, re_step + 1);
		pstmt.setInt(7, re_level + 1);
		pstmt. executeUpdate();
		
	} catch (SQLException e) {
		e.printStackTrace();
	}finally {
		try {
			if(pstmt != null) pstmt.close();
			if(conn != null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
} // reInsertBoard()


// 관리자용 전체 게시글의 개수 알아보기
	public int getAllCount() {
		int count = 0;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "SELECT COUNT(*) FROM notice ";
		
		conn = getConnection();
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				count = rs.getInt(1);
			}
			
		} 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 count;
	}//getAllCount
	
	
	
	
// 해당 아이디 게시글의 개수 알아보기
public int getAllCount(String WriterId) {
	int count = 0;
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String sql = "SELECT COUNT(*) FROM notice where writer_id = ? ";
	
	conn = getConnection();
	try {
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, WriterId);
		rs = pstmt.executeQuery();
		
		if(rs.next()) {
			count = rs.getInt(1);
		}
		
	} 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 count;
}//getAllCount

★// 한 화면 당 10개의 게시글 출력하기 public List getAllBoard(String WriterId,int startRow, int endRow){

List list = new ArrayList(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql ="SELECT @ROWNUM := @ROWNUM + 1 AS ROWNUM,TB.* " + " FROM ( " + " SELECT * FROM notice where writer_id = ? ORDER BY REF DESC, RE_STEP ASC " + " ) AS TB " + " ,( " + " SELECT @ROWNUM := 0 " + " ) AS SELROW " + "LIMIT ?,?"; conn = getConnection();
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, WriterId);
			pstmt.setInt(2, startRow-1);
			pstmt.setInt(3, endRow - (startRow-1));
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				
				NoticeDTO dto = new NoticeDTO();
				
				dto.setId(rs.getInt("ID"));
				dto.setTitle(rs.getString("TITLE"));
				dto.setWriter_id(rs.getString("WRITER_ID"));
				dto.setContent(rs.getString("CONTENT"));
				dto.setRegdate(rs.getDate("REGDATE"));
				dto.setFiles(rs.getString("FILES"));
				dto.setRef(rs.getInt("REF"));
				dto.setRe_step(rs.getInt("RE_STEP"));
				dto.setRe_level(rs.getInt("RE_LEVEL"));

				list.add(dto);

			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs != null) rs.close();
				if(rs != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return list;
	}
	
	// 관리자용 리스트
	public List<NoticeDTO> getAllBoard(int startRow, int endRow){
		
		List<NoticeDTO> list = new ArrayList<NoticeDTO>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql ="SELECT @ROWNUM := @ROWNUM + 1 AS ROWNUM,TB.*  " + 
				"	FROM (  " + 
				"		  SELECT * FROM notice ORDER BY REF DESC, RE_STEP ASC " + 
				"		  ) AS TB  " + 
				"		,(  " + 
				"			SELECT @ROWNUM := 0  " + 
				"		 )  AS SELROW " + 
				"LIMIT ?,?";

		conn = getConnection();

		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, startRow-1);
			pstmt.setInt(2, endRow - (startRow-1));
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				MemberDAO dao = MemberDAO.getInstance();
				NoticeDTO dto = new NoticeDTO();
				
				dto.setId(rs.getInt("ID"));
				dto.setTitle(rs.getString("TITLE"));
				dto.setWriter_id(rs.getString("WRITER_ID"));
				dto.setContent(rs.getString("CONTENT"));
				dto.setRegdate(rs.getDate("REGDATE"));
				dto.setFiles(rs.getString("FILES"));
				dto.setRef(rs.getInt("REF"));
				dto.setRe_step(rs.getInt("RE_STEP"));
				dto.setRe_level(rs.getInt("RE_LEVEL"));
				

♣︎// id값으로 유저 닉네임 가져오기 dto.setName(dao.CheckUserName(rs.getString("writer_id")));

list.add(dto);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs != null) rs.close();
				if(rs != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return list;
	}
	

	
	
	public List<NoticeDTO> getNoticeWriterid(String writer_id){
		List<NoticeDTO> list = new ArrayList<NoticeDTO>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql ="select * from notice where writer_id = ?";
		
		conn = getConnection();

		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, writer_id);
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				
				NoticeDTO dto = new NoticeDTO();
				
				dto.setId(rs.getInt("ID"));
				dto.setTitle(rs.getString("TITLE"));
				dto.setWriter_id(rs.getString("WRITER_ID"));
				dto.setContent(rs.getString("CONTENT"));
				dto.setRegdate(rs.getDate("REGDATE"));
				dto.setFiles(rs.getString("FILES"));

				list.add(dto);

			}
			
		} 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 list;
	}
	
	
	public void updateBoard(String title, String content,int id) {
		int result;
		Connection con = null;
		PreparedStatement st = null;
		
		String sql = "update notice set title = ?, content = ? where id = ?";
		
		con = getConnection();
		
		try {
			st = con.prepareStatement(sql);
			st.setString(1,title);
			st.setString(2, content);
			st.setInt(3, id);
			
			result = st.executeUpdate();
			
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(st != null) {st.close();}
				if(con != null) {con.close();}
			}catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
	

	public NoticeDTO getNoticeId(int idkey) {
		NoticeDTO dto = new NoticeDTO();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		String sql = "SELECT * FROM NOTICE WHERE ID = ?";
		
		conn = getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1,idkey);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				dto.setId(rs.getInt("ID"));
				dto.setTitle(rs.getString("TITLE"));
				dto.setWriter_id(rs.getString("WRITER_ID"));
				dto.setContent(rs.getString("CONTENT"));
				dto.setRegdate(rs.getDate("REGDATE"));
				dto.setFiles(rs.getString("FILES"));
			}
		}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 dto;
	} //id에 해당하는 레코드 하나만 얻어오기

	
	//게시글 삭제
	public void deleteRecord(int idkey) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = "DELETE FROM NOTICE WHERE ID=?";
		conn = getConnection();
		
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, idkey);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	// 선택한 게시글 하나만 불러오기
	// method 이름과 매개변수 : getOneBoard(int num)
	// return type : board dto
	public NoticeDTO getOneBoard(int num) {
		
		NoticeDTO dto = new NoticeDTO();
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM NOTICE WHERE ID = ?";
		
		conn = getConnection();
		
		try {
			// 매개변수로 전달받은 num에 해당하는 게시글을 하나 select 하기.
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				dto.setId(rs.getInt("ID"));
				dto.setTitle(rs.getString("TITLE"));
				dto.setWriter_id(rs.getString("WRITER_ID"));
				dto.setContent(rs.getString("CONTENT"));
				dto.setRegdate(rs.getDate("REGDATE"));
				dto.setFiles(rs.getString("FILES"));
				dto.setRef(rs.getInt("REF"));
				dto.setRe_step(rs.getInt("RE_STEP"));
				dto.setRe_level(rs.getInt("RE_LEVEL"));
				
			}
			
			
		} 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 dto;
	}

}

package com.notice.web.model;

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

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

public class MemberDAO {

private static MemberDAO dao;

private MemberDAO() {}

public static MemberDAO getInstance() {
	if(dao == null) {
		dao = new MemberDAO();
	}
	return dao;
} // getInstance


private static Connection getConnection(){
	Connection conn = null;
	
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/MysqlDB");
			conn = ds.getConnection();
		}catch(NamingException e) {
			e.printStackTrace();
		}catch(SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}  // getConnection


  // 회원가입할 때 
  // 사용자가 입력한 id가 DataBase에 있는지 없는지 알아보기 
  public int confirmId(String id) {
  	int result = 0;
  	
  	Connection conn = null;
  	PreparedStatement pstmt = null;
  	ResultSet rs = null;
  	
  	String sql = "SELECT ID FROM MEMBER WHERE UID=?";
  	
  	try {
			conn = getConnection();
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,  id);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {  // DataBase에 등록된 아이디
				result = 1;
			}else {  // DataBase에 등록되지 않은 아이디
				result = 0;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) {rs.close();}
				if(pstmt != null) {pstmt.close();}
				if(conn != null) {conn.close(); System.out.println("DB Disconnected !!");}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
  	
  	return result;
  } // confirmId
  
  
  // 회원 등록할 때 입력한 값을 DB에 저장하기 : insert
  public int insert(MemberDTO dto) {
  	int result = 0;
  	
  	Connection conn = null;
  	PreparedStatement pstmt = null;
  
  	String sql = "INSERT INTO MEMBER VALUES (?, ?, ?, ?, ?, default)";
    
  	conn = getConnection();
  	
  	try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, dto.getUid());
			pstmt.setString(2, dto.getPwd());
			pstmt.setString(3, dto.getName());
			pstmt.setString(4, dto.getAddress());
			pstmt.setString(5, dto.getTel());
			result = pstmt.executeUpdate();
			
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		} finally {
			try {
				if(pstmt != null) {pstmt.close();}
				if(conn != null) {conn.close(); System.out.println("DB Disconnected !!");}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
  	
  	return result;
  	
  } // insert
  
  
  // 로그인할 때 id와 password가 맞는지 알아보기
  public int check(String id, String Password) {
  	// 실패하는 값으로 초기화해 놓기
  	int result = 0;
  	
  	Connection conn = null;
  	PreparedStatement pstmt = null;
  	ResultSet rs = null;
  	
  	String sql = "SELECT PWD FROM MEMBER WHERE UID=?";
  	
  	conn = getConnection();
  	
  	try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			
			if(rs.next()) { // 아이디가 DB에 있는 경우  
				//비밀번호 체
				 if(rs.getString("pwd").equals(Password)) {
				    // 로그인 성공 : 아이디와 비밀번호가 맞는 경우
						result = 1;
				 }else {  // 아이디는 맞으나 비밀번호가 다름
						result = 0;
					}
			}else {
				// 입력한 아이디가 DB에 없는 경우
				result = -1;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) {rs.close();}
				if(pstmt != null) {pstmt.close();}
				if(conn != null) {conn.close(); System.out.println("DB Disconnected !!");}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
  	
    return result;
  	
  }  // check
  
  // 해당 id로 가입한 유저 닉네임 가져오
  public String CheckUserName(String id) {
	  	
	  	Connection conn = null;
	  	PreparedStatement pstmt = null;
	  	ResultSet rs = null;
	  	
	  	String name = null;
	  	
	  	String sql = "select name from MEMBER m where uid = ?";
	  	
	  	conn = getConnection();
	  	
	  	try {
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, id);
				rs = pstmt.executeQuery();
				
				if(rs.next()) { 
					name = rs.getString("name");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if(rs != null) {rs.close();}
					if(pstmt != null) {pstmt.close();}
					if(conn != null) {conn.close(); System.out.println("DB Disconnected !!");}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
	  	
	    return name;
	  	
	  }  // check

}

0개의 댓글