앞서 만든 sql을 자바와 연결
- DB를 jsp에서 접근하는 방법
- 자바빈즈
package day10;
//create table student1 (
// name varchar2(100),
// kor number,
// eng number,
// mat number
// );
public class Student1 {
private String name;
private int kor;
private int eng;
private int mat;
public Student1() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return kor;
}
public void setKor(int kor) {
this.kor = kor;
}
public int getEng() {
return eng;
}
public void setEng(int eng) {
this.eng = eng;
}
public int getMat() {
return mat;
}
public void setMat(int mat) {
this.mat = mat;
}
}
- JSP에서 연결
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="day10.Student1" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex01.jsp</title>
<style type="text/css">
table {
border: 2px solid black;
border-collapse: collapse;
}
thead th {
background-color: #dadada;
}
td, th {
padding: 10px 20px;
border: 1px solid greay;
}
</style>
</head>
<body>
<h1>Database의 내용을 jsp에서 table로 출력하기</h1>
<hr>
<table>
<thead>
<tr>
<th>NAME</th>
<th>KOR</th>
<th>ENG</th>
<th>MAT</th>
</tr>
</thead>
<tbody>
<%
// sqlplus c##itbank/it@192.168.1.100:1521/xe
String sql = "select * from student1";
String url = "jdbc:oracle:thin:@192.168.1.100:1521:xe";
String user = "c##itbank";
String password = "it";
Class.forName("oracle.jdbc.driver.OracleDriver"); // ojdbc8.jar
// DB 연결할때 고정적으로 사용하는 구문
Connection conn = DriverManager.getConnection(url, user, password); // 연결
Statement stmt = conn.createStatement(); // 상태
ResultSet rs = stmt.executeQuery(sql); // 결과
while(rs.next()) { // sc.hasNextLine(); 다음줄이 있으면 true 없으면 false 한줄당 가져옴.
String name = rs.getString("name"); // 현재 줄에서 name의 값을 문자열로 가져온다
int kor = rs.getInt("kor"); // 현재 줄에서 kor의 값을 정수로 가져온다
int eng = rs.getInt("eng"); // 현재 줄에서 eng의 값을 정수로 가져온다
int mat = rs.getInt("mat"); // 현재 줄에서 mat의 값을 정수로 가져온다
%>
<tr>
<td><%=name %></td>
<td><%=kor %></td>
<td><%=eng %></td>
<td><%=mat %></td>
</tr>
<%
} //end of while
rs.close();
stmt.close();
conn.close();
// 만약, 연결을 닫지 않으면, 실행할때마다 연결이 누적되어 오라클에 접속하지 못할 수도 있다
%>
</tbody>
</table>
</body>
</html>
- 실행결과
- DAO를 이용하여 DB 접근
- DAO (data access object)는 모든 데이터베이스 관련 애플리케이션에서 반드시 존재하는 클래스로서 데이터베이스의 데이터에 접근하기 위한 객체이다.
- DTO (data transfer object)는 회원 테이블의 정보를 자바에서 얻어오기 전에 회원 정보를 저장할 공간을 위한 준비과정으로 VO, 자바 빈과 동일하다.
- Student1DAO
package day10;
// DAO : Data Access Object, 데이터에 접근하는 객체
// DTO : Data Transfer Object, 데이터를 전송하기 위한 객체 (자바 빈즈)
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DriverManager;
public class Student1DAO {
private Connection conn;
private Statement stmt;
private ResultSet rs;
private final String url = "jdbc:oracle:thin:@192.168.1.100:1521:xe";
private final String user = "c##itbank";
private final String password = "it";
public Student1DAO() { // DAO 객체를 생성하면 conn이 준비된 상태다
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
System.out.println("DAO 생성자 예외 발생 : " + e);
} catch (ClassNotFoundException e) {
System.out.println("지정한 클래스를 찾을 수 없습니다 : " + e);
}
}
// 지정한 테이블의 모든 relation을 object로 변환하여 list에 담아서 변환하는 함수
public ArrayList<Student1> selectList() {
ArrayList<Student1> list = new ArrayList<Student1>();
String sql = "select * from student1";
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
Student1 ob = new Student1();
ob.setName(rs.getString("name"));
ob.setKor(rs.getInt("kor"));
ob.setEng(rs.getInt("eng"));
ob.setMat(rs.getInt("mat"));
list.add(ob);
}
} catch (SQLException e) {
// e.printStackTrace();
System.out.println("selectList에서 예외 발생 : " + e);
} finally {
try { if(rs != null) rs.close(); } catch(Exception e) {}
try { if(stmt != null) stmt.close(); } catch(Exception e) {}
try { if(conn != null) conn.close(); } catch(Exception e) {}
}
return list;
}
}
- ex02.jsp(DAO에서 가져온 DB를 JSP에서 출력)
<%@page import="day10.Student1"%>
<%@page import="java.util.ArrayList"%>
<%@page import="day10.Student1DAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex02.jsp</title>
<style type="text/css">
table {
border: 2px solid black;
border-collapse: collapse;
}
thead th {
background-color: #dadada;
}
td, th {
padding: 10px 20px;
border: 1px solid greay;
}
</style>
</head>
<body>
<h1>자바 객체를 이용하여 데이터를 불러오기</h1>
<hr>
<table>
<thead>
<tr>
<th>NAME</th>
<th>KOR</th>
<th>ENG</th>
<th>MAT</th>
</tr>
</thead>
<tbody>
<%
Student1DAO dao = new Student1DAO();
ArrayList<Student1> list = dao.selectList();
for(Student1 st : list) {
%>
<tr>
<td><%=st.getName() %></td>
<td><%=st.getKor() %></td>
<td><%=st.getEng() %></td>
<td><%=st.getMat() %></td>
</tr>
<%
}
%>
</tbody>
</table>
</body>
</html>
- 실행결과
- EL태그 + usebean(자바빈이 생성)을 활용하여 출력
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ex03.jsp</title>
</head>
<style type="text/css">
table {
border: 2px solid black;
border-collapse: collapse;
}
thead th {
background-color: #dadada;
}
td, th {
padding: 10px 20px;
border: 1px solid greay;
}
</style>
<body>
<h1>EL, JSTL을 적용한 코드</h1>
<hr>
<jsp:useBean id="dao" class="day10.Student1DAO" />
<table>
<thead>
<tr>
<th>NAME</th>
<th>KOR</th>
<th>ENG</th>
<th>MAT</th>
</tr>
</thead>
<c:forEach var="st" items="${dao.selectList() }">
<tr>
<td>${st.name }</td>
<td>${st.kor }</td>
<td>${st.eng }</td>
<td>${st.mat }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
- 실행결과
3가지 방법 모두 같은 화면을 출력한다.
'개발자 > JSP' 카테고리의 다른 글
[JDBC] 시퀀스를 활용하여 idx값 출력 (제약조건++) (0) | 2022.12.09 |
---|---|
[SQL] DB Table 제약조건 (0) | 2022.12.09 |
[JSP] 세션(session) (0) | 2022.12.05 |
[JSP] 쿠키(Cookie) (0) | 2022.12.02 |
[JSP]Attribute 속성 활용 (0) | 2022.11.28 |