DB에 있는 모든 점수 데이터를 가져오는 로직 구현
ArrayList를 만들어서 점수들이 모인 객체를 모아주는 저장소 생성 ← KEY!
score DAO
// 점수 목록 조회 메소드
// 점수 목록을 모두 조회하기 때문에 특정 조건을 걸 매개변수가 존재하지 x
public List<ScoreVO> selectAll() {
List<ScoreVO> scoreList = new ArrayList<>();
String sql = "SELECT * FROM scores ORDER BY id ASC;";
try {
// 드라이버 연결
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
// 쿼리 실행
while (rs.next()) {
ScoreVO vo = new ScoreVO(rs.getInt("id"), rs.getString("name"), rs.getInt("Kor"), rs.getInt("Eng"),
rs.getInt("Math"), rs.getInt("Total"), rs.getDouble("Avg"));
scoreList.add(vo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return scoreList;
}
score_list.jsp
DateBase에 저장되어 있는 값을 가져와서 출력
<%@page import="kr.co.jsp.score.model.ScoreVO"%>
<%@page import="java.util.List"%>
<%@page import="kr.co.jsp.score.model.ScoreDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
// DB테이블에 존재하는 모든 학생의 점수를 현재 JSP 파일로 가지고 와서
// 테이블 태그로 출력
// DAO에게 조회를 요청하는 로직을 만들면 됨
ScoreDAO dao = ScoreDAO.getInstance();
// ScoreDAO는 객체를 생성할 수 없으므로 static의 특징으로 scoreDAO 값을 가져옴
List<ScoreVO> scoreList = dao.selectAll();
System.out.println(scoreList);
// dao.selectAll()은 List<ScoreVO>타입의 모든 score 데이터를 모두 리턴
%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> 학생들의 전체 성적 조회</h1>
<form action="search.jsp">
검색 : <input type = "text" name = "keyword" placeholder = "검색할 이름을 입력">
<input type = "submit" value = "검색">
</form>
<!-- 이름을 search.jsp에 보내서 값을 바탕으로 sql 수행하면 될 듯? -->
<table border = "1">
<tr>
<th>id</th>
<th>name</th>
<th>Kor</th>
<th>Eng</th>
<th>Math</th>
<th>Total</th>
<th>Avg</th>
<th>비고</th>
</tr>
<% for (ScoreVO scores : scoreList) { // 향상 for문을 사용해 직접 값에 접근 %>
<tr>
<td><%= scores.getId() %></td>
<td><%= scores.getName() %></td>
<td><%= scores.getKor() %></td>
<td><%= scores.getEng() %></td>
<td><%= scores.getMath() %></td>
<td><%= scores.getTotal() %></td>
<td><%= scores.getAvg() %></td>
<td>
<a href = "delete.jsp?id=<%=scores.getId()%>">[삭제]</a>
<!-- 삭제를 클릭하면 delete.jsp에 id값도 같이 보냄 -->
</td>
</tr>
<%} %>
</table>
<br>
<a href = "insert_form.jsp">새로운 점수 등록하기</a>
</body>
</html>
table에 링크를 걸어 ?를 통해 값을 전달
전달 받은 아이디를 바탕으로 DELETE 연산을 수행
score DAO
public boolean delete(int num) {
boolean flag = false;
String sql = "DELETE FROM scores WHERE id = ?";
try {
// 드라이버 연결
conn = getConnection();
pstmt = conn.prepareStatement(sql);
// 쿼리 실행
// ?에 값을 넣어줌
pstmt.setInt(1, num);
// 실행
int rn = pstmt.executeUpdate();
if (rn == 1) {
flag = true;
}
// rn이 1이면 삭제 성공 했으므로 true로 바꿔줌
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return flag;
}
delete.jsp
<%@page import="kr.co.jsp.score.model.ScoreDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/*
파라미터 데이터(int)를 얻어오신 후 DAO에게 삭제 요청 해 주시면 됩니다.
(DAO의 주소값 받아와서 메서드 호출)
public boolean delete(???) <- DAO 클래스에 선언하세요.
삭제가 완료되면 score_list.jsp로 이동.
삭제가 실패해도 score_list.jsp로 이동.
삭제가 성공했는지, 실패했는지의 여부를 script 태그를 이용하여
경고창으로 알려 주세요.
location.href="URL" -> 이걸로 이동시키기.
*/
/*
id를 일단 받아온 뒤 id를 가지고 where로 이용해 삭제
삭제가 완료되면 삭제완료
삭제가 완료되지 않으면 삭제완료 X
*/
int id = Integer.parseInt(request.getParameter("id"));
// ?도 get이나 post처럼 파라미터를 받아올 수 있음
System.out.println(id);
// id 받아올 수 있는 것 확인
//ScoreDAO dao = ScoreDAO.getInstance();
//boolean check_delete = dao.delete(id);
//if (check_delete == true) {
if (ScoreDAO.getInstance().delete(id)) {
%>
<script>
alert("삭제 처리를 성공하였습니다.")
location.href = "score_list.jsp";
</script>
<%} else {%>
<script>
alert("삭제 처리를 실패하였습니다.")
location.href = "score_list.jsp";
</script>
<% } %>
이름을 매개 값으로 받음
매개 값인 이름을 통해 DAO에 개별 search를 할 수 있는 로직을 구현하여 search.jsp에 리턴
주의 : setString()은 ‘ ‘이 포함되므로 DAO의 search 함수에 매개 값으로 보낼 때 %를 붙여서 보냄
리턴 값을 table로 search.jsp에 표시
score DAO
public List<ScoreVO> search(String name) {
List<ScoreVO> scoreList = new ArrayList<>();
String sql = "SELECT * FROM scores WHERE name LIKE ?";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
// ?에 값을 넣어줌
rs = pstmt.executeQuery();
// 쿼리 실행
while (rs.next()) {
ScoreVO vo = new ScoreVO(
rs.getInt("id"), rs.getString("name"), rs.getInt("Kor"), rs.getInt("Eng"),
rs.getInt("Math"), rs.getInt("Total"), rs.getDouble("Avg"));
scoreList.add(vo);
// 값을 가져와서 리스트에 객체형태로 저장
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return scoreList;
search.jsp
<%@page import="kr.co.jsp.score.model.ScoreVO"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="kr.co.jsp.score.model.ScoreDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
String keyword = request.getParameter("keyword");
// score_list에서 보낸 keyword라는 이름을 가진 값을 가져옴
// 김이라고만 입력해도 김씨가 다 나오거나 길동이라는 이름이 다 나오게 함
// LIKE % " "%를 사용해서 찾으면 될 듯?
// 틀렸네...
// pstmt.setString()은 ?를 채워줄 때 ''도 채워서 넣어주기 때문에 오류남
// ?에 %keyword% 이렇게 넣으면 될 듯
String included_keyword = "%" + keyword + "%";
/*
SQL문에서 LIKE 절을 사용할 때 %를 ?에 직접 붙이면 정상 동작이 안됨
?를 채울 때 pstmt객체의 setString()을 이용해서 채우는데
setString()은 ''를 자동으로 추가해줌
그렇기 때문에 %가 '' 안으로 들어가지 못하는 상황이 발생
SQL에는 ?만 사용하고 보내는 값에 %를 붙여서 보내면 됨
*/
/*
DAO클래스에 search라는 이름의 메서드를 선언해서 검색 결과를 리턴하세요.
리턴된 결과를 테이블 형식으로 body 내부에 출력해 주시면 되겠습니다.
테이블 형식은 score_list.jsp에 있는 테이블을 참조하세요.
검색 결과가 없다면 브라우저 화면에 테이블 대신 '검색 결과가 없습니다.'
라고 출력하시고 목록으로 돌아갈 수 있는 링크를 추가하세요.
*/
%>
<%
ScoreDAO dao = ScoreDAO.getInstance();
List<ScoreVO> conditional_search = dao.search(included_keyword);
%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
if (conditional_search.size() > 0){ %>
<table border = "1">
<tr>
<th>id</th>
<th>name</th>
<th>Kor</th>
<th>Eng</th>
<th>Math</th>
<th>Total</th>
<th>Avg</th>
</tr>
<% for (ScoreVO scores : conditional_search) { // 향상 for문을 사용해 직접 값에 접근 %>
<tr>
<td><%= scores.getId() %></td>
<td><%= scores.getName() %></td>
<td><%= scores.getKor() %></td>
<td><%= scores.getEng() %></td>
<td><%= scores.getMath() %></td>
<td><%= scores.getTotal() %></td>
<td><%= scores.getAvg() %></td>
</tr>
<%} %>
</table>
<% } else {
%>
<script>
alert("검색결과가 없습니다.")
location.href = "score_list.jsp";
</script>
<%} %>
</body>
</html>