조치할 수 있는 예외 상황이 생겼을 때 예외 상황별 대응
try{
int result = 10 / 0;
System.out.println("결과: "+result);
}catch(ArithmeticException e){
System.out.println("0으로 나누면 안된다.");
}System.out.println("프로그램 종료");
- 회원만 게시글을 작성할 수 있다.
- 회원만 게시글을 조회할 수 있다.
- 자신의 게시글만 수정 또는 삭제할 수 있다.
- 회원가입 시 아이디 중복확인을 해야 한다.
- 아이디를 입력 후 다른 회원이 사용중인 아이디로 확인되면,
'이미 사용중인 아이디입니다.'라고 알려준다.- 아이디가 중복되지 않ㄴ았으면 '사용 가능한 아이디입니다.'라고 알려준다.
- 로그인 상태를 확인하기 위해 SessionStorage 클래스의 HashMap 또는 Set 타입의 멤버변수를 활용한다.
- 회원은 자신의 정보외에는 확인할 수 없다.
- 관리자는 모든 회원의 정보를 확인할 수 있다.
250411 진행사항
기존에는 Insert, Update, Delete, Select를 다른 클래스로 관리해서 각각 기능을 구현할 때마다 DB connection이 이루어져서 엄청 느렸는데, JDBCService라는 클래스로 묶어서 DB연결을 전역으로 관리하니 속도가 많이 빨라졌다.
기존에 로그인한 사람을 배열로 저장했는데, HashMap으로 변경 후 CurrentId를 유지 → 여기서 좀 막힘
로그인한 사람이 자기가 작성한 게시글만 수정, 삭제할 수 있다.
추가 수정해야할 사항
HashMap에 여러 명의 로그인 session을 어떻게 관리할지? 지금은 한명이 로그인하면 추가적으로 로그인할 수 없게 막아둔 상태
package JDBC0411;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCService_Test {
static JDBCService service;
static SessionStorage ss = new SessionStorage();
static String currentId ="";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
service = new JDBCService(); // DB 연결 및 서비스 객체 생성
Scanner sc = new Scanner(System.in);
boolean flag = true;
while (flag) {
ss.printSession(); // 현재 로그인 세션 출력
printMenu();
int input = sc.nextInt();
if (input == 0) {
flag = false;
} else {
moveMenu(input);
}
}
System.out.println("[안내] 종료하겠습니다.");
}
// 메뉴 출력
public static void printMenu() {
// 로그인되어 있는 사람이 있다면 첫번째 사람 아이디 저장
boolean flag=false;
if(!SessionStorage.map.isEmpty()) {
currentId = SessionStorage.map.keySet().iterator().next();
}
if(ss.isLogin(currentId))
flag=true;
System.out.println("====Menu====");
System.out.println("1. 회원가입");
if(flag) System.out.println("2. 로그아웃");
else System.out.println("2. 로그인");
// System.out.println("2. 로그인");
System.out.println("3. 게시글 작성");
System.out.println("4. 게시글 조회");
System.out.println("5. 게시글 수정");
System.out.println("6. 게시글 삭제");
System.out.println("------------");
System.out.println("0. 종료");
System.out.println("============");
System.out.print("메뉴 선택 > ");
}
// 메뉴 이동
public static void moveMenu(int input) throws ClassNotFoundException, SQLException {
// 로그인되어 있는 사람이 있다면 첫번째 사람 아이디 저장
String loginUserId = "";
boolean flag=false;
if(!SessionStorage.map.isEmpty()) {
loginUserId = SessionStorage.map.keySet().iterator().next();
}
if(ss.isLogin(loginUserId))
flag=true;
switch (input) {
case 1:
service.insert_Join();
break;
case 2:
if(flag) logout(loginUserId);
else login();
break;
case 3:
writeBoard();
break;
case 4:
service.select_listBoard();
break;
case 5:
service.update_Board(currentId);
break;
case 6:
service.delete_Board(currentId);
break;
default:
System.out.println("다시 선택해주세요.");
}
}
// 로그인 기능 처리
public static void login() throws ClassNotFoundException, SQLException {
service.select_listMember(); // 내부에서 로그인 처리하고 ss에 저장됨
}
public static void logout(String loginUserId) {
ss.logout(loginUserId);
System.out.println("[안내] 로그아웃 되었습니다.");
}
// 게시글 작성
public static void writeBoard() throws ClassNotFoundException, SQLException {
// 로그인 유저가 한 명만 있다고 가정 (현재 구조 기준)
// 맵에서 첫 번째 로그인 유저 ID를 가져오기
if (!SessionStorage.map.isEmpty()) {
String loginUserId = SessionStorage.map.keySet().iterator().next(); // 첫 번째 로그인 유저
if (ss.isLogin(loginUserId)) {
service.insert_Board(loginUserId);
} else {
System.out.println("[안내] 로그인 먼저 하세요.");
}
} else {
System.out.println("[안내] 로그인 먼저 하세요.");
}
}
}
package JDBC0411;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import Test.Board;
import Test.Member;
public class JDBCService {
public static SessionStorage ss;
private static Connection conn;
public static Scanner sc = new Scanner(System.in);
public static String currentId = "";
// Class 생성될 때 DB 접속
public JDBCService() throws ClassNotFoundException, SQLException {
ss = new SessionStorage();
String url = "jdbc:oracle:thin:@localhost:1521:testdb";
String user = "green";
String password = "1234";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
System.out.println("DB 연결 성공!");
}
public void insert_Join() throws SQLException {
System.out.println("[안내] 회원가입 페이지입니다.");
System.out.print("아이디 > ");
String user_id = sc.next();
System.out.print("비밀번호 > ");
String user_pw = sc.next();
System.out.print("이름 > ");
String user_name = sc.next();
System.out.print("전화번호 > ");
String user_phone = sc.next();
String query = "INSERT INTO tbl_member VALUES (?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, user_id);
pstmt.setString(2, user_pw);
pstmt.setString(3, user_name);
pstmt.setString(4, user_phone);
pstmt.setString(5, "B");
int result = pstmt.executeUpdate();
if (result == 1)
System.out.println("새로운 회원이 되신 것을 환영합니다.");
else
System.out.println("회원가입 정보를 다시 입력하세요.");
}
public void insert_Board(String user_id) throws SQLException {
System.out.println("[안내] " + user_id + "님 게시글 작성 페이지입니다.");
System.out.print("제목 > ");
String title = sc.next();
System.out.print("내용 > ");
String content = sc.next();
Statement stmt = conn.createStatement();
String bnoQuery = "SELECT NVL(MAX(bno), 0) AS max_bno FROM tbl_board";
ResultSet rs = stmt.executeQuery(bnoQuery);
rs.next();
int board_no = rs.getInt("max_bno") + 1;
String query = "INSERT INTO tbl_board (bno, title, content, writer, regdate) VALUES (?, ?, ?, ?, SYSDATE)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, board_no);
pstmt.setString(2, title);
pstmt.setString(3, content);
pstmt.setString(4, user_id);
int result = pstmt.executeUpdate();
if (result == 1)
System.out.println("게시글 작성이 완료되었습니다.");
else
System.out.println("게시글 작성을 실패했습니다.");
}
public static SessionStorage select_listMember() throws ClassNotFoundException, SQLException {
List<Member> list = new ArrayList<>(); // 3. 쿼리 실행 후 회원 정보값을 저장할 리스트
Statement stmt = conn.createStatement();
String query = "SELECT * FROM tbl_member"; // 실행할 쿼리 작성
ResultSet rs = stmt.executeQuery(query); // SELECT는 결과값을 받아줘야하고, executeQuery의 자료형은 ResultSet이다.
while(rs.next()) { // 조회 쿼리시 1개 이상의 컬럼이 나올 걸 예상해서 반복문, next()는 다음 것이 있으면 true
Member member = new Member(); // 멤버 인스턴스의 위치도 반복문 안으로 설정해줘야 한다.
String id = rs.getString("id");
String pw = rs.getString("pw");
String name = rs.getString("name");
String phone = rs.getString("phone");
String grade_temp = rs.getString("grade"); //rs가 char를 제공하지 않아서 String으로
char grade = grade_temp.charAt(0);
member.setId(id);
member.setPw(pw);
member.setName(name);
member.setPhone(phone);
member.setGrade(grade);
list.add(member);
}
select_checkMember(list);
return ss;
}
public static void select_checkMember(List<Member> list) {
//String[] loginUser = new String[2]; //////////////////////
boolean flag=false;
System.out.println("[안내] 로그인 페이지입니다.");
System.out.print("ID > ");
String user_id=sc.next();
System.out.print("PW > ");
String user_pw=sc.next();
for(Member m: list) {
if(user_id.equals(m.getId()) && user_pw.equals(m.getPw())) {
flag=true;
ss.login(user_id);
// currentId = user_id;
System.out.println("[안내] 로그인 성공!");
break;
}
}
if(!flag) System.out.println("[안내] ID와 비밀번호를 다시 확인하세요");
}
public static void select_listBoard() throws ClassNotFoundException, SQLException {
List<Board> boardList = new ArrayList<>(); // 3. 쿼리 실행 후 회원 정보값을 저장할 리스트
Statement stmt = conn.createStatement();
String query = "SELECT * FROM tbl_board"; // 실행할 쿼리 작성
ResultSet rs = stmt.executeQuery(query); // SELECT는 결과값을 받아줘야하고, executeQuery의 자료형은 ResultSet이다.
while(rs.next()) { // 조회 쿼리시 1개 이상의 컬럼이 나올 걸 예상해서 반복문, next()는 다음 것이 있으면 true
Board board = new Board(); // 멤버 인스턴스의 위치도 반복문 안으로 설정해줘야 한다.
String bno_temp= rs.getString("bno");
int bno = Integer.parseInt(bno_temp);
String title = rs.getString("title");
String content = rs.getString("content");
String writer = rs.getString("writer");
String regdate = rs.getString("regdate");
board.setBno(bno);
board.setTitle(title);
board.setContent(content);
board.setWriter(writer);
board.setRegdate(regdate);
boardList.add(board);
}
select_readBoard(boardList);
}
public static void select_readBoard(List<Board> boardList) {
System.out.println("[안내] 게시글 조회 페이지입니다.");
System.out.print("전체조회: 1 | 선택조회: 2 >");
int choice = sc.nextInt();
int choicebno;
switch(choice) {
case 1: System.out.println("모든 게시글을 조회하겠습니다.");
for(Board b: boardList)
System.out.println(b);
break;
case 2: System.out.print("몇 번 게시글을 조회하겠습니까? > ");
choicebno = sc.nextInt();
for(Board b: boardList) {
if(choicebno==b.getBno())
System.out.println(b);
}
default: System.out.println("메뉴를 잘못 선택했습니다.");
}
}
public void update_Board(String currentId) throws SQLException {
System.out.println("[안내] 게시글 수정 메뉴입니다.");
this.currentId = currentId;
if(currentId.equals(""))
System.out.println("[안내] 로그인부터 하세요.");
else {
System.out.println("몇 번 게시글을 수정하시겠습니까?");
int choice = sc.nextInt();
sc.nextLine(); // 엔터 버퍼 제거
System.out.print("제목 > ");
String title = sc.nextLine();
System.out.print("내용 > ");
String content = sc.nextLine();
String query = "UPDATE tbl_board SET title=?, content=? WHERE bno=? AND writer = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, title);
pstmt.setString(2, content);
pstmt.setInt(3, choice);
pstmt.setString(4, currentId);
int result = pstmt.executeUpdate();
if (result == 1)
System.out.println("게시글을 수정했습니다.");
else
System.out.println("자신이 작성한 게시글만 수정할 수 있습니다.");
}
}
public void delete_Board(String currentId) throws SQLException {
System.out.println("[안내] 게시글 삭제 메뉴입니다.");
this.currentId = currentId;
if(currentId.equals(""))
System.out.println("[안내] 로그인부터 하세요.");
else {
System.out.println("몇 번 게시글을 삭제하시겠습니까?");
int choice = sc.nextInt();
String query = "DELETE FROM tbl_board WHERE bno=? AND writer = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, choice);
pstmt.setString(2, currentId);
int result = pstmt.executeUpdate();
if (result == 1)
System.out.println(choice+"번 게시글을 삭제했습니다.");
else
System.out.println("자신이 작성한 게시글만 삭제할 수 있습니다.");
}
}
}
package JDBC0411;
import java.util.HashMap;
public class SessionStorage {
static HashMap<String, String> map = new HashMap<>();
public void login(String id) {
map.put(id, "in");
}
public void logout(String id) {
map.remove(id);
}
public boolean isLogin(String id) {
return "in".equals(map.get(id));
}
public void printSession() {
System.out.print("현재 로그인한 사람: ");
for (String key : map.keySet()) {
System.out.print("ID: " + key + " ");
}
System.out.println();
}
}