본문 바로가기
코딩/수업 정리

21.01.11 Mon [034]

by 6^6 2021. 1. 11.
728x90

JSP

jsp_lecture_23

실무에선 <%= %>이거 안씀 스클립어쩌구.

이제 EL이거 씀

EL 표현식

${value} (<%=value %> 와 같은 뜻)

EL의 액션태그

${memver.name} 은 ${member.getName} 을 호출하는것

[el.jsp]
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>

    ${10}<br />
    ${99.99}<br />
    ${"ABC"}<br />
    ${true}<br />
</body>
</html>
//10
//99.99
//ABC
//true

↓연산도 가능하다

[eloperator.jsp]
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>

    ${ 1+2 } <br />
    ${ 1-2 } <br />
    ${ 1*2 } <br />
    ${ 1/2 } <br />
    ${ 1>2 } <br />
    ${ 1<2 } <br />
    ${ (1>2) ? 1 : 2 } <br />
    ${ (1>2) || (1<2) } <br />

</body>
</html>
//3
//-1
//2
//0.5
//false
//true
//2
//true
[Memberinfo.java] class-package명 edu.bit.ex
package edu.bit.ex;

public class Memberinfo {
    private String name;
    private String id;


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPw() {
        return pw;
    }
    public void setPw(String pw) {
        this.pw = pw;
    }
    private String pw;


}
[el.jsp]-Webcontent
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <jsp:useBean id="member" class="edu.bit.ex.Memberinfo" scope="page" />
     <jsp:setProperty name="member" property="name" value="홍길동" />
      <jsp:setProperty name="member" property="id" value="abc" />
       <jsp:setProperty name="member" property="pw" value="123" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
이름 : <jsp:getProperty name="member" property="name"/><br />
아이디 : <jsp:getProperty name="member" property="id"/><br />
비밀번호 : <jsp:getProperty name="member" property="pw"/><br />
<hr />
이름 : ${member.name}<br /><!-- name을 바로 갖고 오는게 아니라 외부에서 갖고오는것!  -->
아이디 : ${member.id}<br />
비밀번호 : ${member.pw}

</body>
</html>

똑같이 출력!

param, paramValues, initParam, cookie 사용예제

[result.jsp] -WebContent
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    <%
    String id = request.getParameter("id");
    String pw = request.getParameter("pw");    
    %>

    <기존방법> <br />
    아이디 : <%=id %><br />
    비밀번호 : <%=pw %><br />
    <hr />
    <'el방법><br />
    아이디 : ${param.id} <br />
    비밀번호 : ${param.pw}<br />
    <hr />
    <'el방법 다른 방식> <br />
    아이디 : ${param["id"]}<br />
    비밀번호 : ${param["pw"]}<br />


</body>
</html>
[objectel.jsp]-WebContent
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="result.jsp" method="get">
아이디 : <input type="text" name="id"><br />
비밀번호 : <input type="password" name="pw"><br />
<input type="submit" value="login">
</form>
</body>
</html>

↓출력화면

가장 중요한 Scope 4가지

<jsp:useBean id="member" class="edu.bit.ex.Memberinfo" scope="page" /> 같은 쓰임새로!

1. pageScope

2. requestScope

3. sessionScope

4. applicationScope

scope="page"

이 객체가 쓸수있는 범위는 그 현재 자기자신 page전체를 뜻한다.

el로 쓸땐 ${pageScope.page_name} 으로 쓴다.

scope="application"

여러 project [a.jsp , b.jsp, c.jsp, d.jsp]가 있다고 했을때, a b c d.jsp 전체다 갖다 쓸 수 있다는 뜻(영역이 가장 넓다)

scope="session"

시간을 뜻한다. (cookie할때 배움) 30분지정하면 30분만 사용가능

session은 웹브라우저 당 1개씩있다.

sessionID(4byte) 이해하는것이 중요

가장중요한

scope="request"

r

[objectel.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="result.jsp" method="get">
        <input type="submit" value="결과">
    </form>
    <% /* 4가지 내장객체. 객체니까 메모리에 올라가있다는 뜻. 
    4개의 객체를 기본적으로 jsp에서 제공해준다는 뜻. 
    el로 표현하는 방법 외우기*/

    /* name에 value값 담은것 */

    application.setAttribute("application_name", "application_value");    
    session.setAttribute("session_name", "session_value");    
    pageContext.setAttribute("page_name", "pageContext_value");
    request.setAttribute("request_name", "request_value");    
    %>

    <!-- 전체영역에서 적용되니까 출력o --> 
    ${applicationScope.application_name}<br>

    <!-- 접속하자마자 30분이니까 출력o -->
    ${sessionScope.session_name}<br>

    <!-- 자기페이지니까 출력o -->
    ${pageScope.page_name}<br>

    <!-- request는 출력o  -->
    ${requestScope.request_name}<br>

</body>
</html>
[result.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

    <!-- 전체영역에서 적용되니까 출력o --> 
    ${applicationScope.application_name}<br>

    <!-- 접속하자마자 30분이니까 출력o -->
    ${sessionScope.session_name}<br>

    <!-- 자기페이지가 아니니까 출력x -->
    ${pageScope.page_name}<br>

    <!-- request는 출력x -->
    ${requestScope.request_name}

</body>
</html>

[result.jsp]에서 request 는 왜 출력이 안될까?

request는 response해서 응답한번했으면 사라진다.

따라서 request는 응답주기 전까지만 살아있다.

[objectel.jsp]에 <jsp:forward page="result.jsp"/> 를 추가하면

result.jsp로 넘어간 request는 출력된다.(응답주기 전까지 살아있기 때문에)

만약<jsp:redict page="result.jsp"/>해주면 request는 출력되지않는다.

이게 forward와 redirect의 차이임

jsp_lecture_24

라이브러리이기 때문에 다운받아야한다.

tomcat.apache.org/taglibs/standard/

[

Apache Taglibs - Apache Standard Taglib: JSP[tm] Standard Tag Library (JSTL) implementations

](https://tomcat.apache.org/taglibs/standard/)

선생님이 주신 jstl.jar파일과 statnderd.jar파일을 WebContent- WEB-INF- lib폴더 안에 넣기

lib.zip
0.35MB

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> .jsp 에 이거 넣기!

*기본 출력

[jstl.jsp] - WebContent
<%@ 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>Insert title here</title>
</head>
<body>


    <c:set var="varName" value="varValue" />
    <!-- var="변수명" value="변수값" -->
    <!-- var varName = varValue; 와 같은뜻  -->

    vatName : <c:out value="${varName}" />
    <!-- value에 varName을 출력해라 라는뜻. -->

</body>
</html>

↓출력화면

*remove

<%@ 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>Insert title here</title>
</head>
<body>


    <c:set var="varName" value="varValue" />
    <!-- var="변수명" value="변수값" -->
    <!-- var varName = varValue; 와 같은뜻  -->

    vatName : <c:out value="${varName}" />
    <!-- value에 varName을 출력해라 라는뜻. -->

    <br />
    <!-- remove 추가 -->
    <c:remove var="varName" />
    vatName : <c:out value="${varName}" />


</body>
</html>

↓출력화면

*예외처리

<%@ 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>Insert title here</title>
</head>
<body>


    <c:set var="varName" value="varValue" />
    <!-- var="변수명" value="변수값" -->
    <!-- var varName = varValue; 와 같은뜻  -->

    varName : <c:out value="${varName}" />
    <!-- value에 varName을 출력해라 라는뜻. -->

    <!-- 예외처리 추가. try까지 안해도됨 -->
    <br />
    <c:catch var="error">
    <%=2/0 %>
    </c:catch>
    <br />
    <c:out value="${error}"/>


</body>
</html>

↓출력화면

DB

<group by 에서 분류하는 having>

그룹 지어진 부서별 평균 급여가 2000이상인 부서의 번호화 부서별 평균 급여를 출력하는 쿼리문

*select deptno, avg(sal) from emp group by deptno having AVG(sal)>2000; *

*group by에서는 비교할때 where 이 아니라 having을 쓴다. *

 

부서의 최대값과 최소값을 구하되, 최대 급여가 2900 이상인 부서만 출력하는 쿼리문

select deptno, max(sal), min(sal) from emp group by deptno having max(sal)>=2900;

 

 

핵심 중 핵심 join 5가지

1. CARTESIAN PRODUCT (발생 가능한 모든 경우의 수를 다 뽑아내는 것.)

 select * from emp, dept;

컬럼수가 emp수 X dept수 로 곱해져서 출력. → join 결과가 의미를 가지려면 where절에 올바른 join 조건을 지정해야한다.

 select dname,ename from dept, emp where emp.ename = 'ALLEN';
 //이름이 ALLEN 인 사람의 부서명을 출력해 보는 쿼리문

2. EQUI JOIN

 select emp.ename, dept.dname from emp, dept where emp.deptno = dept.deptno;
 //emp의 deptno와 dept의  deptno가 일치하는것만 뽑음

cartesian product 에서 여러 테이블로 나뉘어진 데이터를 조회하기 위해 사용하는데,
Where 공통된 테이블 조건을 사용한다.
emp와 dept 와 공통된 테이블인 deptno를 이용해
WHERE emp.deptno = dept.deptno 라고 사용한다.
그냥 where deptno 는 출력오류. where 뒤엔 무조건 조건절이 와야한다.

 select d.dname,e.ename from dept d, emp e where e.deptno = d.deptno and emp.ename = 'KING';
 //e,d 이렇게 이름을 줄 수도 있다. 

3. NON-EQUI JOIN(비등가 조인)

두 테이블에 중복인 컬럼없이 다른 조건을 join할 때 쓴다.

 select ename, sal, grade from salgrade,emp where sal between losal and hisal;
 //각 사원이 급여가 몇 등급인지 살펴보는 쿼리문
 //위에서 부서이름까지 같이 나오게 하려면?
 SELECT ename,sal,grade,dname
 FROM salgrade,emp,dept
 WHERE sal BETWEEN losal AND hisal
  AND emp.deptno = dept.deptno;

4. SELF JOIN
자기 자신과 join하는 기법이다.

select e.ename, m.ename from emp e, emp m where e.empno=m.mgr;
//각 사원의 매니저 이름을 뽑아내라
//위의 코드 응용
select e.ename ||'의 매니저는 '|| m.ename from emp e, emp m where e.empno=m.mgr;

오늘의 문제

1.el 이란 무엇인가?
Exxpression Language. 표현식 또는 액션 태그를 대신해서 값을 표현.
EL 표현식
${value} <%=value %> 와 같은 뜻이다.
${ 1+2 }와 같은 연산도 가능하다.

 

 

 

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

jstl은 jsp에 HTML태그와 같이 사용되어 가독성이 떨어지는 단점을 보완한 태그 라이브러리이다.
jstl.jar파일과 statnderd.jar파일을 lib폴더 안에 넣어야 사용 가능하다.

 

JSTL 5가지 라이브러리
"Core, XML Processing, I18N formatting, SQL, Functions"

 

 

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

scopt 4가지 종류 - 내장객체이다. 기본적으로 jsp에서 제공해줌.

<jsp:useBean id="member" class="edu.bit.ex.Memberinfo" scope="page" /> 
와 같은 쓰임새로 사용

-pageScope
scope="page" 뜻
이 객체가 쓸수있는 범위는 그 현재 자기자신 page전체를 뜻한다.
el로 쓸땐 ${pageScope.page_name} 으로 쓴다.

-applicationScope
scope="application"뜻
여러 project [a.jsp , b.jsp, c.jsp, d.jsp]가 있다고 했을때, a b c d.jsp 전체다 갖다 쓸 수 있다는 뜻(영역이 가장 넓다)

-sessionScope
scope="session" 뜻
시간을 뜻한다. (cookie할때 배움) 30분지정하면 30분만 사용가능
session은 웹브라우저 당 1개씩있다.
sessionID(4byte) 이해하는것이 중요

-requestScope★★★
scope="request"뜻
request는 response해서 응답한번했으면 사라진다.
따라서 request는 응답주기 전까지만 살아있다.

 

 

 

4. join의 종류에 대하여 설명하시오.

emp와 dept 둘 다 같이 출력하고 싶을 때 join을 쓴다.

-CARTESIAN PRODUCT (발생 가능한 모든 경우의 수를 다 뽑아내는 것.)

select * from emp, dept;

컬럼수가 emp수 X dept수 로 곱해져서 출력. → join 결과가 의미를 가지려면 where절에 올바른 join 조건을 지정해야한다.

-EQUI JOIN

cartesian product 에서 여러 테이블로 나뉘어진 데이터를 조회하기 위해 사용하는데,

Where 공통된 테이블 조건을 사용한다.

emp와 dept 와 공통된 테이블인 deptno를 이용해

where emp.deptno = dept.deptno 라고 사용한다.

그냥 where deptno 는 출력오류. where 뒤엔 무조건 조건절이 와야한다.

-NON-EQUI JOIN
두 테이블에 중복인 컬럼없이 다른 조건을 join할 때 쓴다.

select ename, sal, grade from salgrade,emp where sal between losal and hisal;
//각 사원이 급여가 몇 등급인지 살펴보는 쿼리문
//위에서 부서이름까지 같이 나오게 하려면?
SELECT ename,sal,grade,dname
FROM salgrade,emp,dept
WHERE sal BETWEEN losal AND hisal
    AND emp.deptno = dept.deptno;

-SELF JOIN
자기 자신과 join하는 기법이다.

select e.ename, m.ename from emp e, emp m where e.empno=m.mgr;
//각 사원의 매니저 이름을 뽑아내라
//위의 코드 응용
select e.ename ||'의 매니저는 '|| m.ename from emp e, emp m where e.empno=m.mgr;

-OUTER JOIN

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


-EMP테이블을 EMPLOTEE와 MANAGER로 별칭을 지정한 후 특정 사원의 매니저가 누구인지 알아내는 쿼리문

//(BLAKE 사원의 매니저가 누구인지 알아내시오)
select employee.ename, manager.ename 
from emp employee,emp manager
where employee.empno = manager.mgr
and employee.ename='BLAKE';


-사원 정보를 출력할 때, 각 사원이 소속된 부서의 상세 정보를 출력하기 위해 두 개의 테이블을 조인하는 쿼리문

SELECT * FROM EMP, DEPT WHERE EMP.DEPTNO = DEPT.DEPTNO;


-부서의 최대값과 최소값을 구하되, 최대 급여가 2900 이상인 부서만 출력하는 쿼리문

select deptno, min(sal), max(sal) from emp group by deptno having max(sal) >=2900; 


-부서별 사원의 수와 커미션을 받는 사원의 수를 계산하는 쿼리문

select deptno, count(*) as "부서별 사원 수", count(comm) as "커미션 받는 사원 수" 
from emp
group by deptno;

 

 


-소속 부서별 급여 총액과 평균 급여를 구하는 쿼리문

select deptno, sum(sal) as "급여 총액", avg(sal) as "평균 급여"  from emp
group by deptno;

 

 

 

 

1. 다음을 프로그래밍 하시오.

-객체를 생성하도록 할것

-조건 객체 및 el 또는 jstl을 사용해 볼 것.

[SubjectMain.html] - WebContent
<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<style>
h1 {
    color: blue;
}

table {
    border: 0.5px solid blue;
    color: blue;
}
</style>


<body>
    <h1>성적입력</h1>
    <form action="Subjectjsp.jsp" method="get">

        <table border="1">
            <tr>
                <td colspan="2">학번</td>
                <td><input type="text" name="id"></td>
            </tr>

            <tr>
                <td rowspan="3">과목</td>
                <td>Java</td>
                <td><input type="text" name="java"></td>
            </tr>

            <tr>
                <td>Database</td>
                <td><input type="text" name="database"></td>
            </tr>

            <tr>
                <td>JSP</td>
                <td><input type="text" name="jsp"></td>
            </tr>

            <tr>
                <td><input type="submit" value="전송"></td>
            </tr>
        </table>
    </form>
</body>
</html>
[Subjectjsp.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<style>
div {
    color: red;
    border: 1px solid red;
}
</style>



<body>


    <table border="1">
        <tr>
            <td colspan="2">학번</td>
            <td style="font-weight: bold">${param.id}</td>
        </tr>

        <tr>
            <td rowspan="3">과목</td>
            <td>Java</td>
            <td style="font-weight: bold">${param.java}</td>
        </tr>

        <tr>
            <td>Database</td>
            <td style="font-weight: bold">${param.database}</td>
        </tr>

        <tr>
            <td>JSP</td>
            <td style="font-weight: bold">${param.jsp}</td>
        </tr>


        <tr>
            <td colspan="2">평균점수</td>
            <td style="font-weight: bold"><div>${(param.jsp+param.java+param.database)/3.0}</div></td>
        </tr>

        <tr>
            <td>
            <a href="SubjectMain.html"><input type="submit" value="입력화면"></a>
            </td>
        </tr>

    </table>

</body>
</html>

↓출력화면

2. 위를 프로그래밍 하시오

-객체로 만들며, 쿼리는 insert문을 사용하시면 됩니다.

728x90

'코딩 > 수업 정리' 카테고리의 다른 글

21.01.13 Wed [036]  (0) 2021.01.13
21.01.12 Tue [035]  (0) 2021.01.12
21.01.08 Fri [033]  (0) 2021.01.08
21.01.07 Thu [032]  (0) 2021.01.07
21.01.06 Wed [031]  (0) 2021.01.06

댓글