본문 바로가기

bitcamp/면접족보

면접족보 21/01/11_EL, JSTL, JOIN

1. EL이란?

· Expression Language의 약자로, 표현식 또는 액션태그를 대신해서 값을 표현하는 언어로 아래와 같이 사용한다.

· JSP 파일에 자바형식의 코드를 사용하는 경우보다 EL과 JSTL을 이용하는 경우 코드를 더 간결하게 작성할 수 있다.

· 내장객체로는 pageScope, requestScope, sessionScope, applicationScope, param 등이 사용된다.

 

※JSP 파일에서 "${list}" 와 같이 작성해도 오류가 발생하지 않는 이유? 
  웹브라우저에서는 html, javascrept만 받아들이기 때문에 서버에서 로딩하다가 Java 문법인 액션태그, EL, JSTL이 있다면, 

  html으로 미리 변환시켜 웹브라우저로 전송하기 때문에 오류가 발생하지 않는다.

 

2. JSTL 문법에 대하여 설명하시오.

· Jsp Standard Tag Library의 약자로, 액션태그로 해결하기 힘든 연산/조건문/반복문 부분을 담당하여 처리한다.

· Tomcat 프로그램에서는 제공하지 않는 문법이므로 lib 라이브러리 안에 파일을 복사하여 사용하거나,

  JSP 페이지에 <%@ taglib prefix="c" uri="http://java. sun. com/jsp/jstl/core" %>를 표기하여 사용하도록 한다. 필수!

 

※JSTL 태그는 아래와 같이 사용

· 출력 태그: <c:out value="출력하려는 결과값">

· 페이지 이동 태그: <c:redirect url="경로">

· 변수설정 태그: <c:set var="변수명" value="설정값" property="값" scope="범위">

· 반복문 for 태그: <c:forEach items="객체명" begin="시작" end="끝" var="변수명></c:forEach>

· 제어문 if 태그: <c:if test="조건" var="변수명" scope="범위"></c:if>

 

3. Scope에 대하여 설명하시오.

· JSP에서는 page, session, request, application 네가지 객체 범위를 제공하며, 각 객체마다 적용되는 범위가 다르다. 
 1)page : 생성된 페이지 내(현재 페이지)에서만 사용 가능
 2)session : 웹브라우저의 생명주기(설정한 시간)과 동일하게 사용 가능

 3)request : 요청된 페이지 내에서만 사용 가능(요청 받고 응답 처리가 완료되면 request 객체 소멸)

    forward의 경우? 페이지를 넘겨서 결과 값을 출력하므로 첫 번째 페이지에서 응답을 한 상태가 아니다. 

                            그러므로 두번째 페이지에서 응답 후에 객체는 소멸된다. (Scope 범위: request>page)
 4)application : 사이트 전체를 범위호 현재 사용하고 있는 어플리케이션 전체에 대해 사용 가능

    (a/b/c/d.jsp가 존재한다면 모두 사용 가능하고, 영역이 가장 넓다)

 

4. join의 종류에 대하여 설명하시오. **핵심 중의 핵심**

 · join은 두 개 이상의 테이블에 대해서 결합하여 나타낼 때 사용한다.
 1)CARTESIAN PRODUCT
   두 개 이상의 테이블이 조인될 때, 공통되는 컬럼에 의한 조인이 발생되지 않아 모든 데이터가 출력되는 경우

    select * from emp, dept;   (48개의 값이 출력, 12개(emp)에 대해서 4개(dept)를 다 적용시켜서 출력)
 2)EQUI JOIN(동등조인)
   조인 대상이 되는 두 테이블에서 공통적으로 존재하는 컬럼의 값이 일치되는 행을 연결하여 결과를 생성하는

   조인 기법 (A = B, B = C 일 때, A = C와 같다)

   select * from emp,dept where emp.deptno=dept.deptno; (사원정보를 출력할 떄, 각 사원이 소속된 부서의 상세정보 출력)
   select emp.ename, dept.dname from emo,dept where emp.deptno=dept.deptno; (위 결과에서 특정 컬럼의 정보 출력)
   select dept.dname from emp,dept where emp.deptno=dept.deptno and emp.ename = 'FORD';  
(FORD 사원의 부서명 출력)
 3)NON-EQUI JOIN(비등가조인)
   공통적으로 들어가는 컬럼이 없을 때 사용하는 조인 기법

   select * from salgrade;  (salgrade 등급 테이블을 의미)
   select ename, sal, grade from emp,salgrade where sal between losal and hisal;  (각 사원의 급여가 몇 등급인지 출력)

 4)SELF JOIN(자가조인)
   자기 자신과 조인하는 기법으로, 하나의 테이블 내에서 조인을 해야 자료를 얻을 수 있는 경우에 사용

   원하는 정보가 한 테이블에 있는 경우 사용하며, 테이블이 하나 더 존재하는 것처럼 판단되도록 테이블 별칭을 사용

   select e.ename, m.ename from emp e,emp m where e.mgr = m.empno;  (사원에 해당되는 매니저 이름을 출력)
 5)OUTER JOIN
   조인 조건에 만족하지 않는 행도 나타내는 조인 기법

   select e.ename||'의 매니저는'||m.ename||'입니다.' from emp e, emp m where e .mgr=m.empno(+);  
   (매니저가 없는 KING이 SELF JOIN 하는 경우 나타나지 않지만 +하게 되면 추가되서 출력)

 

5. 아래를 sql 문으로 처리 하시오.

1)EMP테이블을 EMPLOTEE와 MANAGER로 별칭을 지정한 후 특정 사원의 매니저가 누구인지 알아내는 쿼리문
  select EMPLOTEE.ename, MANAGER. ename from emp EMPLOTEE, emp MANAGER

     where EMPLOTEE. mgr=MANAGER. empno;
2)사원 정보를 출력할 때, 각 사원이 소속된 부서의 상세 정보를 출력하기 위해 두 개의 테이블을 조인하는 쿼리문
  select * from emp, dept where emp. deptno=dept. deptno;
3)부서의 최대값과 최소값을 구하되, 최대 급여가 2900 이상인 부서만 출력하는 쿼리문
  select deptno, max(sal), min(sal) from emp group by deptno having max(sal) >= 2900;
4)부서별 사원의 수와 커미션을 받는 사원의 수를 계산하는 쿼리문
  select deptno, count(*), count(comm) from emp group by deptno;
5)소속 부서별 급여 총액과 평균 급여를 구하는 쿼리문
  select deptno, sum(sal), avg(sal) from emp group by deptno;

 

※연습문제

♣게시판 작성에 앞서 emp list를 출력하고, 사원 정보를 입력하여 DB에 insert 하시오♣

 

<입력 화면>

 

<출력 화면>

 

 

<empView.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
48
49
50
51
52
53
54
55
56
57
 <body>
    <h1>사원 정보 입력</h1>
    <hr/>
    <form action="empInsert.jsp">
        <table>
            <tr>
                <td>사원번호</td>
                <td><input type="number" name="empno"/></td>
            </tr>
            <tr>
                <td>사원이름</td>
                <td><input type="text" name="ename"/></td>
            </tr>
            <tr>
                <td>사원직급</td>
                <td><input type="text" name="job"/></td>
            </tr>
            <tr>
                <td>매니저</td>
                <td>
                    <select name="mgr">
                        <c:forEach var="man" items="${empDao.manangerSelect()}">
                                <option value="${man.empno}"> (${man.empno})${man.ename}</option>
                        </c:forEach>
                    </select>
                </td>
            </tr>
            <tr>
                <td>입사일</td>
                <td><input type="date" name="date"/></td>
            </tr>
            <tr>
                <td>급여</td>
                <td><input type="number" name="sal"/></td>
            </tr>
            <tr>
                <td>커미션</td>
                <td><input type="number" name="comm"/></td>
            </tr>
            <tr>
                <td>부서</td>
                <td>
                    <select name="deptno">
                        <c:forEach var="dept" items="${deptDao.deptSelect()}">
                            <option value="${dept.deptno}"> (${dept.deptno})${dept.dname}</option>
                        </c:forEach>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center">
                    <input type="submit" value="입력"/>
                </td>
            </tr>
        </table>
    </form>
 </body>
cs

 

<empinsert.jsp>

1
2
3
4
5
6
7
8
9
10
 <jsp:useBean id="empDao" class="edu.bit.ex.dao.EmpDao"/>
 <jsp:useBean id="emp" class="edu.bit.ex.dto.EmpVO"/>
 <jsp:setProperty name="emp" property="*"/>
 <body>
    <c:set var="result" value="${empDao.insertEmp(emp)}" />
    <c:if test="${result > 0 }">
        <h1>정보입력이 정상적으로 처리 되었습니다.</h1>
        <a href="empList.jsp">리스트</a>
    </c:if>
 </body>
cs

 

<EmpVO.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
 public class EmpVO {
    private int empno;   
    private String ename; 
    private String job;
    private int mgr;
    private Timestamp hiredate;
    private String date;
    private int sal;
    private int comm;
    private int deptno;
 
    public EmpVO() { 
    }
 
    public EmpVO(int empno, String ename, String job, int mgr, Timestamp hiredate, int sal,
                       int comm, int deptno, String dname, String loc) {
        this.empno = empno;
        this.ename = ename;
        this.job = job;
        this.mgr = mgr;
        this.hiredate = hiredate;
        this.sal = sal;
        this.comm = comm;
        this.deptno = deptno;
    }
    
    public EmpVO(int empno, String ename) {
        this.empno = empno;
        this.ename = ename;
    }
 
    public int getEmpno() {
        return empno;
    }
    public void setEmpno(int empno) {
        this.empno = empno;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public int getMgr() {
        return mgr;
    }
    public void setMgr(int mgr) {
        this.mgr = mgr;
    }
    public Timestamp getHiredate() {
        return hiredate;
    }
    public void setHiredate(Timestamp hiredate) {
        this.hiredate = hiredate;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public int getSal() {
        return sal;
    }
    public void setSal(int sal) {
        this.sal = sal;
    }
    public int getComm() {
        return comm;
    }
    public void setComm(int comm) {
        this.comm = comm;
    }
    public int getDeptno() {
        return deptno;
    }
    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }    
 }
cs

 

<EmpDao.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
 public class EmpDao { 
    DataSource dataSource; 
    
    public EmpDao() { 
        try {
            Context context = new InitialContext(); 
            dataSource = (DataSource) context.lookup("java:comp/env/jdbc/oracle");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public ArrayList<EmpVO> manangerSelect() {
        ArrayList<EmpVO> dtos = new ArrayList<EmpVO>();
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
        
            try {
                // 커넥션풀에 있는 커넥션 메소드 호출
                connection = dataSource.getConnection();
            
                String query = "select m.EMPNO,m.ename from emp e , emp m where e.mgr = m.empno group by m.ename ,m.EMPNO";
                preparedStatement = connection.prepareStatement(query);
                resultSet = preparedStatement.executeQuery();
 
                while (resultSet.next()) {
                    int empno = resultSet.getInt("empno");
                    String ename = resultSet.getString("ename");
 
                    EmpVO dto = new EmpVO(empno, ename);
                    dtos.add(dto);
                }
 
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(resultSet != null) resultSet.close();
                    if(preparedStatement != null) preparedStatement.close();
                    if(connection != null) connection.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
          return dtos;
    }
    
    public int insertEmp(EmpVO emp) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
 
        int result = -1;
        try {
            connection = dataSource.getConnection();
            
            String query = "insert into emp values(?,?,?,?,?,?,?,?)";
            preparedStatement = connection.prepareStatement(query);
            
            preparedStatement.setInt(1,emp.getEmpno() );
            preparedStatement.setString(2, emp.getEname());
            preparedStatement.setString (3, emp.getJob());
            preparedStatement.setInt(4, emp.getMgr());            
            preparedStatement.setDate(5,Date.valueOf(emp.getDate()));            
            preparedStatement.setInt(6, emp.getSal());
            preparedStatement.setInt(7, emp.getComm());
            preparedStatement.setInt(8, emp.getDeptno());
            
            result = preparedStatement.executeUpdate();
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    public ArrayList<EmpListVO> empList() {
        ArrayList<EmpListVO> dtos = new ArrayList<EmpListVO>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            connection = dataSource.getConnection();
            
            String query = "select e.empno, e.ename, e.job, p.ename as mgr, e.hiredate, " +
                                "e.sal, nvl(e.comm, 0) as comm, e.deptno, d.dname, d.loc " +
                                "from emp e, emp p, dept d " +
                                "where e.mgr = p.empno and e.deptno = d.deptno " +
                                "order by e.ename";
 
            preparedStatement = connection.prepareStatement(query);
            resultSet = preparedStatement.executeQuery();
 
            while (resultSet.next()) {
                int empno = resultSet.getInt("empno");
                String ename = resultSet.getString("ename");
                String job = resultSet.getString("job");
                String mgr = resultSet.getString("mgr");
                Timestamp hiredate = resultSet.getTimestamp("hiredate");
                int sal = resultSet.getInt("sal");
                int comm = resultSet.getInt("comm");
                int deptno = resultSet.getInt("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                
                EmpListVO dto = new EmpListVO(empno,ename,job,mgr,hiredate,sal,comm,deptno,dname,loc);
                dtos.add(dto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(resultSet != null) resultSet.close();
                if(preparedStatement != null) preparedStatement.close();
                if(connection != null) connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return dtos;
    }    
 }
 
cs


<emplist.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
 <%
    request.setCharacterEncoding("utf-8");
 %>
 <jsp:useBean id="empDao" class="edu.bit.ex.dao.EmpDao"/>
 <!DOCTYPE html>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>EMP 직원 리스트 출력</title>
   <style>
      table{width:100%;}
   </style>
 </head>
 <body>
    <h1>EMP 테이블 직원 목록</h1>
    <table border="1">
        <tr>
            <th>사원번호</th> <!-- empno -->
            <th>사원이름</th> <!-- ename -->
            <th>직급(업무)</th> <!-- job -->
            <th>상사(이름)</th> <!-- mgr -->
            <th>입사일</th> <!-- hiredate -->
            <th>급여</th> <!-- sal -->
            <th>커미션</th> <!-- comm -->
            <th>부서번호</th> <!-- deptno -->
            <th>부서이름</th> <!-- dname -->
            <th>부서위치</th> <!-- loc -->
            <th>관리</th>
        </tr>
            
        <c:forEach var="empList" items="${empDao.empList()}">
            <tr>
                <td>${empList.empno }</td>
                <td>${empList.ename }</td>
                <td>${empList.job }</td>
                <td>${empList.mgr }</td>
                <td>${empList.hiredate }</td>
                <td>${empList.sal }</td>
                 <td>${empList.comm }</td>
                <td>${empList.deptno }</td>
                <td>${empList.dname }</td>
                <td>${empList.loc }</td>
            </tr>
        </c:forEach>            
    </table>
 </body>
 </html>
cs