티스토리 뷰

이번 포스팅에서는 DBMS와 JSP를 연동해서 HR 계정의 Employee테이블 내용을 웹에 출력해볼 것이다.

지금까지는 sql developer 내에서 쿼리를 날려보았지만 이제는 JSP파일 내에서 쿼리를 날려 DB에 접근할 것이다. 

Java 에서 데이터베이스에 접근하는 것을 Connection이라고 한다.
Java에는 이를 지원해주는 API가 있는데 JDBC라고 부른다.

JDBC란?
자바 프로그램 내에서 데이터베이스 질의문 즉,SQL을 실행하기 위한 자바 API(application programming interface)이다.

JDBC에서는 3가지 주요 API가 있다.
1. Connection         
  - DB와 연결

2. PreparedStatement           
  - Query 실행

3. Result Set          
  - 결과를 얻음


구현체(Implement class)
API에는 인터페이스만 있기 때문에 구현체가 필요하다.
Connection의    구체적인 활동을 적어둠
Statement의     구체적인 활동을 적어둠
Result Set의    구체적인 활동을 적어둠

이런 것들을 *.jar라고 한다.
ex. sql-server, mysql-connector, Oracle JDBC

 

2 tier
- 클라이언트에서 비즈니스 로직을 작성하고 데이터베이스에 저장하여 사용하는 형태이다.
- 그림처럼 클라이언트에서 서버로 직접 데이터를 입력하고 불러오는 방식이다.
- 웹스크립트 언어(JSP, PHP, ASP) 에서만 쓰인다.

 

3 tier
-
클라이언트가 미들웨어로 메시지를 주고 받으면서 데이터베이스에 저장하여 사용하는 형태이다.
- 실무에서 보통 사용하는 방법이다.


이제 개념을 다 알았다면, Oracle JDBC를 설치해보자.
링크 http://www.oracle.com/technetwork/apps-tech/jdbc-112010-090769.html 여기로 들어가서 ojdbc6 을 다운받는다.
ojbc6는 11g에 맞는거고, ojbc14는 10g에 맞는거라서 실무에서는 14를 쓰게 될 것이다.

 

다운을 받았다면 이제 STS로 들어간다. 그리고 아래 화면처럼 프로젝트와 패키지를 만들어주고, 다운받았던 ojdbc6.jar 파일을 붙여넣기 해준다.
그리고 jstl을 사용할것이기 때문에 standard.jar, jstl.jar도 함께 붙여넣기 해준다.


EmployeesVO.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.ktds.smahn.vo;
 
public class EmployeesVO {
 
    private int employeeId;
    private String firstName;
    private String email;
    private String phoneNumber;
    private String hireDate;
    private String jobId;
    private int salary;
    private double commissionPct;
    private int managerId;
    private int departmentId;
    
    //getter and setter
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    public String getHireDate() {
        return hireDate;
    }
    public void setHireDate(String hireDate) {
        this.hireDate = hireDate;
    }
    public String getJobId() {
        return jobId;
    }
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public double getCommissionPct() {
        return commissionPct;
    }
    public void setCommissionPct(double commissionPct) {
        this.commissionPct = commissionPct;
    }
    public int getManagerId() {
        return managerId;
    }
    public void setManagerId(int managerId) {
        this.managerId = managerId;
    }
    public int getDepartmentId() {
        return departmentId;
    }
    public void setDepartmentId(int departmentId) {
        this.departmentId = departmentId;
    }
    
    
    
}
 
cs

Const.java

1
2
3
4
5
6
7
8
9
10
package com.ktds.smahn.dao;
 
public interface Const {
    
    public static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:XE";
    public static final String DB_USER = "HR";
    public static final String DB_PASSWORD = "hr";
    
}
 
cs

EmployeesDAO.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.ktds.smahn.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 com.ktds.smahn.vo.EmployeesVO;
 
public class EmployeesDAO {
    
    // employee 테이블 전부 다 가지고오기
    public List<EmployeesVO> getAllEmployees(){
        
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            // catch에 들어가는 모든 것들은 아래와같이 쓴다.
            // Exception : 
            // Runtime : try-catch를 할 필요가 없다.
            throw new RuntimeException(e.getMessage(), e);
        }
        
        
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
 
        List<EmployeesVO> employees = new ArrayList<EmployeesVO>();
        
        
        try {
            // db에 연결함
            conn = DriverManager.getConnection(Const.DB_URL, Const.DB_USER, Const.DB_PASSWORD);
            
            // query를 실행할 준비를 함
            String query = " SELECT * FROM EMPLOYEES ";
            stmt = conn.prepareStatement(query);
            
            // 쿼리의 실행결과를 가져온다.
            // select 쿼리 일 때만 사용한다.
            rs = stmt.executeQuery();
            
            EmployeesVO employee = null;
            while ( rs.next() ) {
                employee = new EmployeesVO();
                employee.setEmployeeId(rs.getInt("EMPLOYEE_ID"));
                employee.setFirstName(rs.getString("FIRST_NAME"));
                employee.setLastName(rs.getString("LAST_NAME"));
                employee.setEmail(rs.getString("EMAIL"));
                employee.setPhoneNumber(rs.getString("PHONE_NUMBER"));
                employee.setHireDate(rs.getString("HIRE_DATE"));
                employee.setJobId(rs.getString("JOB_ID"));
                employee.setSalary(rs.getInt("SALARY"));
                employee.setCommissionPct(rs.getDouble("COMMISSION_PCT"));
                employee.setManagerId(rs.getInt("MANAGER_ID"));
                employee.setDepartmentId(rs.getInt("DEPARTMENT_ID"));
                
                employees.add(employee);
                
            }
            
        } 
        catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        finally {
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {}
            }
            if( stmt != null ){
                try {
                    stmt.close();
                } catch (SQLException e) {}
            }
            if( conn != null ){
                try {
                    conn.close();
                } catch (SQLException e) {}
            }
            
        }
        
        return employees;
        
    }
 
}
 
cs

 

EmployeesServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.ktds.smahn.web;
 
import java.io.IOException;
import java.util.List;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.ktds.smahn.dao.EmployeesDAO;
import com.ktds.smahn.vo.EmployeesVO;
 
/**
 * Servlet implementation class EmployeesServlet
 */
public class EmployeesServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private EmployeesDAO employeesDAO;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeesServlet() {
        super();
        employeesDAO = new EmployeesDAO();
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<EmployeesVO> employees = employeesDAO.getAllEmployees();
        request.setAttribute("allEmployees", employees);
        RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/view/emp.jsp");
        rd.forward(request, response);
    }
 
}
 
cs

 emp.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<%@ 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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 
<table>
    <tr>
        <th>EMPLOYEE_ID</th>
        <th>FIRST_NAME</th>
        <th>LAST_NAME</th>
        <th>EMAIL</th>
        <th>PHONE_NUMBER</th>
        <th>JOB_ID</th>
        <th>HIRE_DATE</th>
        <th>JOB_ID</th>
        <th>SALARY</th>
        <th>COMMISSION_PCT</th>
        <th>MANAGER_ID</th>
        <th>DEPARTMENT_ID</th>
    </tr>
 
<c:forEach items ="${ allEmployees }" var ="emp" >
    <tr>
        <td>${emp.employeeId }</td>
        <td>${emp.firstName }</td>
        <td>${emp.lastName }</td>
        <td>${emp.email }</td>
        <td>${emp.phoneNumber }</td>
        <td>${emp.jobId }</td>
        <td>${emp.hireDate }</td>
        <td>${emp.jobId }</td>
        <td>${emp.salary }</td>
        <td>${emp.commissionPct }</td>
        <td>${emp.managerId }</td>
        <td>${emp.departmentId }</td>
        
 
</c:forEach>
</table>
</body>
</html>
cs

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>HumanResource</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>EmployeesServlet</display-name>
    <servlet-name>EmployeesServlet</servlet-name>
    <servlet-class>com.ktds.smahn.web.EmployeesServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeesServlet</servlet-name>
    <url-pattern>/emp</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>DepartmentsServlet</display-name>
    <servlet-name>DepartmentsServlet</servlet-name>
    <servlet-class>com.ktds.smahn.web.DepartmentsServlet</servlet-class>
  </servlet>
</web-app>
cs

 

 

이제 코드를 다 적었다면 서버를 실행하고 http://localhost:8080/HumanResource/emp 로 접속하여 결과화면을 보자.


이렇게 출력이 된다.!!!! 성공~~

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함