728x90
수업내용
1교시 (09:30-10:20)
- 지난 시간 복습
- leap_test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var year = new Date().getFullYear();
console.log("year >>> : " + year);
alert("year >>> : " + year);
var month = new Date().getMonth();
console.log("month >>> : " + month);
alert("month >>> : " + month);
month = month + 1;
console.log("month >>> : " + month);
alert("month >>> : " + month);
var day = new Date(year, month, 0).getDate();
console.log("day >>> : " + day);
alert("day >>> : " + day);
</script>
</head>
<body>
</body>
</html>
- leap_year_2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var year = new Date().getFullYear();
alert(year);
$('#mbirth').change(function(){
$('#mbirth').empty();
for (c=0; c<12; c++) {
var option = $("<option value=" + "'" + c + "'" + ">" + c + "</option>");
$('#mbirth_1').append(option);
}
});
$("#mbirth_1").change(function(){
var y = $("#mbirth").val();
var m = $("#mbirth_1").val();
var d = new Date(y, m, 0).getDate();
$("#mbirth_2").empty();
for (c=0; c < d; c++) {
var option = $("<option value=" + "'" + c + "'" + ">" + c + "</option>");
$("#mbirth_2").append(option);
}
});
});
</script>
</head>
<body>
<select class="mbirth" name="mbirth" id="mbirth" style="width:100px">
<option value="2022">2022</option>
<option value="2022">2021</option>
<option value="2022">2020</option>
<option value="2022">2019</option>
<option value="2022">2018</option>
</select>
<select class="mbirth_1" name="mbirth_1" id="mbirth_1" style="width:100px">
</select>
<select class="mbirth_2" name="mbirth_2" id="mbirth_2" style="width:100px">
</select>
</body>
</html>
2교시 (10:30-11:20)
- xml 설명
3교시 (11:30-12:20)
- xml
이클립스에서 xml 문서를 만드는 방법
----------------------------
kos_xml - 우클릭 - new - other
select wizard - xml - 검색
XML - XML File 선택 - Next
test.xml
<?xml : xml 시작 표시
<%@ : jsp 시작 표시
<html>
<script
<style
SGML
html : 하이퍼 텍스트 Markup Language
태그로 구성되어 있다, 만들어진 태그를 사용한다.
4.01 : 82ea
5.0 : 102ea
xml : eXtensible Markup Language
태그로 구성 되어 있다, 사용자 정의로 만든 태그를 사용한다.
1. 데이터로 사용한다.
xml, json, yaml(yml: 야믈) 등
2. DTD, XSD 로 xml 규칙을 만든다.
DTD : 문서 타입 정의 : Document Type Definition
*.dtd
XSD : xml 스키마 정의 : XML Schema Definition
xmlns:xs:XSD 요소와 타입에 사용할 W3C의 XML 스키마 네임스페이슬 명시
xmlns:기분 XML 스키마 네임스페이스 명시
*.xsd
3. 환경 설정 파일로 사용한다.
server.xml, web.xml, context.xml
spring-servlet.xml, servlet-context.xml
xml을 파서가 읽어준다.
-----------------
Window 10 파서 위치
C:\Windows\System32
msxm13.dll
msxm13r.dll
msxm16.dll
msxm16r.dll
크롬 웹브라우저에 xml을 읽어주는 파서가 있다.
ie 웹브라우저에 xml을 읽어주는 파서가 있다.
jdk에서 지원하는 파서
-------------------
org.w3c.dom.* : 돔파서 : xml 문서 전체를 한번에 읽어서 동작한다.
org.xml.sax.* : 삭스 파서 : xml 문서에서 엘리먼트에 이벤트가 동작할 때 읽어서 동작한다.
javaScript 에서 지원하는 파서
DOMParser 객체
vender 들이 만들 파서를 사용한다.
Oracle, Sun, Ms, Google ....
xml 작성 규칙은
---------------
문서의 헤더를 갖는다.
<?xml version="1.0" encoding="UTF-8"?>
루트 태그를 갖는다.
<사용자정의 태그이름></사용자정의 태그이름>
태그는 배열로 되어있다.
========================================
XML을 데이터로 사용할 때는
태그의 길이(LEVEL)를 동일하게 사용한다.
좋은 예:
<ROOT>
<LEVEL1>
<LEVEL2>
</LEVEL2>
</LEVEL1>
<LEVEL1>
<LEVEL2>
</LEVEL2>
</LEVEL1>
</ROOT>
나쁜 예:
<ROOT>
<LEVEL1>
<LEVEL2>
</LEVEL2>
</LEVEL1>
<LEVEL1>
<LEVEL2>
<LEVEL3>
</LEVEL3>
</LEVEL2>
</LEVEL1>
</ROOT>
========================================
------------------------------------------
1. 사용자가 만들어 사용할 수 있는 태그 스크립트이다.
2. xml을 만들 때는 DTD 문법으로 태그 규칙을 정할 수 있다.
3. xml에서는 root 태그는 하나만 존재해야 한다.
4. root 태그를 기준으로 하위 태그들의 계층 구조를 정확하게 알고 있어야 한다.
모든 태그 스크립트도 마찬 가지이다.
5. xml 파일을 읽을 때는 root 태그 기준으로 배열로 처리 된다. (html도 같다.)
xml 파일을 읽을 때는 파서(Parser)를 사용해야 한다.
xml Parser
DOM Parser : 문서 전체를 맨 처음 한 번에 메모리에 올려 놓고 읽는 방식
SAX Parser : 문서 전체가 아니고 이벤트 중심으로 읽어오는 방식
------------------------------------------
4교시 (12:30-13:20)
- hello_0.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- xml 문서에서는 항상 루트 태그가 1개만 존재해야 한다. -->
<xmlroottag>
<dept1tag>
<dept2tag>
<dept3tag>
Hello XML 11!!!!!
</dept3tag>
</dept2tag>
</dept1tag>
<dept1tag>
<dept2tag>
<dept3tag>
Hello XML 22!!!!!
</dept3tag>
</dept2tag>
</dept1tag>
<dept1tag>
<dep2tag>
<dept3tag>
Hello XML 33!!!!!
</dept3tag>
</dep2tag>
</dept1tag>
</xmlroottag>
- hello_1.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- xml 문서에서는 항상 루트 태그가 1개만 존재해야 한다. -->
<kosmo108>
<title>과정 이름</title>
<delivery>2022년01월24일 ~ 2022년07월20일</delivery>
<total>23</total>
<user>
<name>신진제</name>
<gender>남자</gender>
<age>26</age>
</user>
<user>
<name>김민</name>
<gender>남자</gender>
<age>32</age>
</user>
<user>
<name>홍길동1</name>
<gender>남자</gender>
<age>27</age>
</user>
<user>
<name>홍길동</name>
<gender>남자</gender>
<age>30</age>
</user>
<user>
<name>김유진</name>
<gender>여자</gender>
<age>22</age>
</user>
<user>
<name>하연재</name>
<gender>남자</gender>
<age>21</age>
</user>
</kosmo108>
<!--
RESTful API 사용 :
HTTP 프로토콜의 GET 방식
http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=108
data.go.kr 회원가입
국가에서 민간에게
국가에서 보유하고 있는 공공정보를 민간에게 제공하는 행위
전세계 73개국에서 공공기간정보를 민간에게 제공한다.
민간정보를 사용할 수 있다.
-->
- hello_2.xml
<?xml version="1.0" encoding="UTF-8"?>
<dictionary>
<term>
<entry>볼드</entry>
<description>
<![CDATA[
글씨를 굵은 글씨로 강조한다. <b>...</b> 태그를 사용한다. <b> 대신 <strong>을 사용해도 된다.
]]>
</description>
</term>
<term>
<entry>볼드</entry>
<description>
글씨를 굵은 글씨로 강조한다. %lt;b%gt;...%lt;/b%gt; 태그를 사용한다. %lt;b%gt; 대신 %lt;strong%gt;를 사용해도 된다.
</description>
</term>
</dictionary>
- hello_3.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
<dictionary>
<term>
<entry>볼드</entry>
<description>
글씨를 굵은 글씨로 강조한다. <b>...</b> 태그를 사용한다. <b> 대신 <strong>을 사용해도 된다.
</description>
</term>
</dictionary>
-->
<!--
CDATA : Character Data : 씨데이터 섹션
<![CDATA[ ]]>
-->
<dictionary>
<term>
<entry>볼드</entry>
<description>
<![CDATA[
글씨를 굵은 글씨로 강조한다. <b>...</b> 태그를 사용한다. <b> 대신 <strong>을 사용해도 된다.
]]>
</description>
</term>
</dictionary>
5교시 (14:30-15:20)
- test_parser.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>XML Parser</title>
<style type="text/css"></style>
<script>
function parseText() {
var xmlText, xmlParser, xmlDoc;
// xmlText 자바스크립트 변수
// xmlTest 자바 스크립트 변수에 문자열을 대입하는 것
// "<country><name>korea</name><capital>seoul</capital></county>"
xmlText = "<country>"
+ "<name>korea</name>"
+ "<capital>seoul</capital>"
+ "</country>"
// 자바스크립트에서 DOMParser 객체를 인스턴스 함
xmlParser = new DOMParser();
// .parseFromString() 함수에서 자바스크립트 변수에 담겨 있는 문자열을 xml 파일 형식으로 파싱을 한다.
// xmlDoc 자바스크립트 변수에 xml 형식의 문서가 대입된다. : 여기서부터 xml 문서이다.
xmlDoc = xmlParser.parseFromString(xmlText, "text/xml");
// 자바스크립트 함수와 xml 파서 함수를 사용해서 xml에서 데이터를 추출한다.
document.getElementById("text").innerHTML =
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue
+ "의 수도는 " +
xmlDoc.getElementsByTagName("capital")[0].childNodes[0].nodeValue + " 입니다.";
}
</script>
</head>
<body>
<h3>문자열 파싱</h3>
<hr>
<button onclick="parseText()">파싱하기!</button>
<p id="text"></p>
</body>
</html>
6교시 (15:30-16:20)
- test_xml.xml
<?xml version="1.0" encoding="UTF-8"?>
<country>
<name>korea</name>
<capital>seoul</capital>
</country>
- test_xml.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import = "java.io.BufferedReader" %>
<%@ page import = "java.io.InputStreamReader" %>
<%@ page import = "java.net.URL" %>
<%
String strHtml = "";
String strLine = "";
try {
String strUrl = "http://localhost:8088/KosMember/kos_xml/test_xml.xml";
BufferedReader br = new BufferedReader(
new InputStreamReader((new URL(strUrl)).openConnection().getInputStream(), "UTF-8"));
while ((strLine = br.readLine()) != null) {
strHtml += strLine;
}
System.out.println(strHtml);
br.close();
} catch (Exception e) {
throw e;
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XML PARSING</title>
<!-- jQuery CDN 불러오기 -->
<Script src="http://code.jquery.com/jquery-latest.min.js"></Script>
<script type="text/javascript">
$(document).ready(function(){
var xmlText, xmlParser, xmlDoc;
xmlText = '<%= strHtml %>';
alert(xmlText);
xmlParser = new DOMParser();
xmlDoc = xmlParser.parseFromString(xmlText, "text/xml");
alert(xmlDoc);
$("#parseText").click(function(){
document.getElementById("text").innerHTML =
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue
+ "의 수도는 " +
xmlDoc.getElementsByTagName("capital")[0].childNodes[0].nodeValue + " 입니다.";
});
$("#parseFind").click(function(){
var name = $(xmlDoc).find("name").text();
var capital = $(xmlDoc).find("capital").text();
alert(name + " 의 수도는 " + capital + " 입니다.");
});
});
</script>
</head>
<body>
<h3>XML 데이터 파싱하기</h3>
<hr>
<button id="parseText">DOM Parser로 XML 파싱하기 </button>
<button id="parseFind">find() 함수로 파싱하기 </button>
<p id="text"></p>
</body>
</html>
7교시 (16:30-17:20)
- db.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orclKSY00
username=scott
password=tiger
- DBPropertyConn.java
package a.b.c.test.xml;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public abstract class DBPropertyConn {
// Connection 연결하는 함수 만들기
public static Connection getConnection() {
String path = "C:\\00.KOSMO108\\30.Web\\eclipse_web_1_work\\KosMember\\src";
Connection conn = null;
try {
FileReader fr = new FileReader(path + "/" + "db.properties");
Properties prop = new Properties();
prop.load(fr);
// DataSource 정보 : 데이터베이스 연결 정보
String JDBC_DRIVER = prop.getProperty("driver");
String JDBC_URL = prop.getProperty("url");
String JDBC_USER = prop.getProperty("username");
String JDBC_PASSWORD = prop.getProperty("password");
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
} catch (Exception e) {
System.out.println("데이터베이스 연결에 문제가 있어요 >>> : " + e.getMessage());
}
return conn;
}
// select
public static void conClose(Connection conn, PreparedStatement pstmt, ResultSet rsRs) {
try {
if (rsRs != null) try {rsRs.close(); rsRs = null; } catch (Exception ex) {}
if (pstmt != null) try {pstmt.close(); pstmt = null; } catch (Exception ex) {}
if (conn != null) try {conn.close(); conn = null; } catch (Exception ex) {}
} catch (Exception e2) {}
}
// insert, update, delete
public static void conClose(Connection conn, PreparedStatement pstmt) {
try {
if (pstmt != null) try {pstmt.close(); pstmt = null; } catch (Exception ex) {}
if (conn != null) try {conn.close(); conn = null; } catch (Exception ex) {}
} catch (Exception e2) {}
}
}
- OracleXmlTest.java
package a.b.c.test.xml;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class OracleXmlTest {
public static final String XML_FILE_PATH = "C:\\00.KOSMO108\\30.Web\\eclipse_web_1_work\\KosMember\\WebContent\\kos_xml";
public static final String XML_PROLOG = "<?xml version='1.0' encoding='UTF-8'?>"; // 선언부
public String getXml(final String tableName) throws Exception {
System.out.println("String tableName >>> : " + tableName);
Connection conn = null;
Statement stmt = null;
ResultSet rsRs = null;
ResultSetMetaData resultMeta = null;
int colCount = 0;
StringBuffer strBuffer = new StringBuffer(XML_PROLOG);
try {
// /src/db.properties 파일을 읽어서 데이터소스를 만들어 jdbc를 연결한다.
conn = DBPropertyConn.getConnection();
stmt = conn.createStatement();
rsRs = stmt.executeQuery("SELECT * FROM " + tableName);
resultMeta = rsRs.getMetaData();
colCount = resultMeta.getColumnCount();
System.out.println(tableName + " 테이블 컬럼 카운트 >>> : " + colCount);
strBuffer.append("\n");
strBuffer.append("<" + tableName.toUpperCase() + ">");
strBuffer.append("\n");
while (rsRs.next()) {
strBuffer.append("<" + "ROW" + ">");
for (int i=0; i < colCount; i++) {
strBuffer.append("<" + resultMeta.getColumnName(i+1) + ">");
strBuffer.append(rsRs.getString(i+1));
strBuffer.append("</" + resultMeta.getColumnName(i+1) + ">");
strBuffer.append("\n");
}
strBuffer.append("</" + "ROW" + ">");
}
strBuffer.append("</" + tableName.toUpperCase() + ">");
strBuffer.append("\n");
} catch (SQLException e) {
System.out.println(" getXML() : " + e);
} finally {}
return strBuffer.toString();
}
public static boolean xmlParse(String fileName, String xmlVal) {
boolean bool = false;
try {
BufferedWriter bw = new BufferedWriter(
new FileWriter(OracleXmlTest.XML_FILE_PATH + "/" + fileName.toLowerCase() + ".xml"));
bw.write(xmlVal);
bw.flush();
bw.close(); // 무조건 닫아줘야 한다.
bool = true;
} catch (IOException e) {
System.err.println(e);
}
return bool;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
OracleXmlTest ox = new OracleXmlTest();
Scanner sc = new Scanner(System.in);
System.out.println("테이블 이름을 KEY-IN 하시오 >>> : ");
String tableName = sc.next();
if (tableName.length() > 0) {
final String fileName = tableName;
String xmlVal = ox.getXml(fileName);
System.out.println("Oracle String Data를 xml로 생성 >>> : \n" + xmlVal);
if (xmlVal != null && xmlVal.length() > 0) {
boolean bool = xmlParse(fileName, xmlVal);
if(bool) {
System.out.println(OracleXmlTest.XML_FILE_PATH + " 디렉토리에 " + fileName + ".xml 파일이 잘 생성 되었습니다. ");
} else {
System.out.println(" 파일이 생성되지 않았습니다. ");
}
}
} else {
System.out.println("java OracleXmlTest 테이블 이름");
}
} catch(Exception e) {
System.out.println("e.getMessage() >>> : " + e.getMessage());
}
}
}
8교시 (17:30-18:30)
- OracleMetaTest.java
package a.b.c.test.xml;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class OracleMetaTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
try {
conn = DBPropertyConn.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM DEPT");
ResultSetMetaData rsm = rs.getMetaData();
System.out.print("\n ResultSetMetaData rsm >>> : " + rsm + "\n");
System.out.println("===============================");
int colCount = rsm.getColumnCount();
System.out.println("\n rsm.getColumnCount() >>> : " + colCount + "\n");
System.out.println("===============================");
for (int i=1; i <= colCount; i++) {
System.out.print(rsm.getColumnName(i) + "\t\t");
}
System.out.println("===============================");
while (rs.next()) {
for (int i=1; i <= colCount; i++) {
System.out.print(rs.getNString(i) + "\t\t");
}
System.out.println("");
}
} catch (SQLException e) {}
}
}
Notes
728x90