5월 12일 (금) - []
Javascript - Ecmascript
- HTML
- *.js
- 프로그래밍 언어 = 자바와 비슷
- let / const / 함수 / 객체
- 기본객체 / BOM / DOM(★)
JSP를 통한 자료
1. CSV ( Comma Seperator ) : 값, 값, ...
2. XML
3. JSON
새 워크스페이스 생성
Window - Preferences - Web - CSS Files / HTML Files / JSP Files - Encoding UTF-8 설정
폰트체, 폰트 설정
Apache-tomcat 서버 등록
◈ CSV File 테스트
▶ data_csv1.jsp 파일 생성 및 코드 작성 / 실행
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%>
HTML5 + CSS3 입문,삼국미디어,유비,30000원
Javascript + JQuery 입문,삼국미디어,관우,32000원
Node.js 프로그래밍,삼국미디어,장비,22000원
HTML5 프로그래밍,삼국미디어,조자룡,30000원
▶ data.xml 파일 생성 및 코드 작성 / 실행
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book>
<name>HTML5 + CSS3 입문</name>
<publisher>삼국미디어</publisher>
<author>유비</author>
<price>30000원</price>
</book>
<book>
<name>Javascript + JQuery 입문</name>
<publisher>삼국미디어</publisher>
<author>관우</author>
<price>32000원</price>
</book>
<book>
<name>Node.js 프로그래밍</name>
<publisher>삼국미디어</publisher>
<author>장비</author>
<price>22000원</price>
</book>
<book>
<name>HTML5 프로그래밍</name>
<publisher>삼국미디어</publisher>
<author>조자룡</author>
<price>30000원</price>
</book>
</books>
▶ xml.jsp 파일 생성 및 코드 작성 / 실행
<%@ page language="java" contentType="text/xml; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<books>
<book>
<name>HTML5 + CSS3 입문</name>
<publisher>삼국미디어</publisher>
<author>유비</author>
<price>30000원</price>
</book>
<book>
<name>Javascript + JQuery 입문</name>
<publisher>삼국미디어</publisher>
<author>관우</author>
<price>32000원</price>
</book>
<book>
<name>Node.js 프로그래밍</name>
<publisher>삼국미디어</publisher>
<author>장비</author>
<price>22000원</price>
</book>
<book>
<name>HTML5 프로그래밍</name>
<publisher>삼국미디어</publisher>
<author>조자룡</author>
<price>30000원</price>
</book>
</books>
데이터베이스 테이블 books 만들기
- 데이터베이스 -u project -p project 접속
create table books (
seq int not null primary key auto_increment,
name varchar(100),
publisher varchar(20),
author varchar(10),
price int
);
DB에 데이터 넣기
insert into books values ( 1, 'HTML5 + CSS3 입문', '삼국미디어', '유비', 30000 );
insert into books values ( 2, 'Javascript + JQuery 입문', '삼국미디어', '관우', 32000 );
insert into books values ( 3, 'Node.js 프로그래밍', '삼국미디어', '장비', 22000 );
insert into books values ( 4, 'HTML5 프로그래밍', '삼국미디어', '조자룡', 30000 );
xml2.jsp 생성
json1.jsp 생성 및 코드 작성
The JSON Validator
JSONLint is the free online validator and json formatter tool for JSON, a lightweight data-interchange format. You can format json, validate json, with a quick and easy copy+paste.
jsonlint.com
- json1.jsp에서 작성한 코드를 붙여넣고 Validate JSON 클릭
- Results에 에러 없이 valid JSON 이 출력되어야 한다.
▶ json3.jsp 파일 생성 후 코드 작성 및 실행
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@ page import="org.json.simple.JSONArray" %>
<%@ page import="org.json.simple.JSONObject" %>
<%
JSONArray arr = new JSONArray();
for( int i=1; i<=3; i++ ) {
JSONObject obj = new JSONObject();
obj.put( "name", "책이름" + i );
obj.put( "publisher", "출판사" + i );
obj.put( "author", "저자" + i );
obj.put( "price", "가격" + i );
arr.add( obj );
}
out.println( arr );
%>
▶ 출력된 내용을 복사 후 jsonlint 사이트에 붙여넣고 Validate JSON 클릭
동기 : 요청을 하고 응답을 받을 때 까지 대기
비동기 : 스레드의 개념. 요청을 하면 응답은 별도로 오기 때문에 추가 작업을 할 수 있음
AJAX 예제 1
ajax01.jsp 파일 생성 후 코드 작성
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- ajax01.jsp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'btn1' ).onclick = function() {
// alert( '버튼 클릭' );
const request = new XMLHttpRequest();
// false : 동기 / true : 비동기
request.open( 'get', 'csv1.jsp', true );
request.send();
console.log( request.responseText );
};
document.getElementById( 'btn2' ).onclick = function() {
const request = new XMLHttpRequest();
console.log( "1" );
request.onreadystatechange = function() {
// console.log( request.readyState );
if( request.readyState == 4 ) {
if( request.status == 200 ) {
console.log( "2" );
console.log( request.responseText );
} else {
alert ( "페이지 오류" );
}
}
};
request.open( 'get', 'csv1.jsp', true );
request.send();
console.log( "3" );
// console.log( request.responseText );
};
};
</script>
</head>
<body>
<button id="btn1">요청하기</button>
<button id="btn2">요청하기</button>
</body>
</html>
ajax 예제 2
ajax02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- ajax02.jsp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'btn' ).onclick = function() {
const request = new XMLHttpRequest();
request.onreadystatechange = function() {
if( request.readyState == 4 ) {
if( request.status == 200 ) {
// console.log( request.responseText );
// document.getElementById( 'ta' ).value = request.responseText.trim();
// table 구조로 데이터 출력
const data = request.responseText.trim();
const rowdatas = data.split( '\n' );
console.log( rowdatas.length );
console.log( rowdatas[0] );
let result = '<table border="1">';
for( let i=0; i<rowdatas.length; i++ ) {
let coldatas = rowdatas[i].split( ',' );
result += '<tr>';
result += '<td>' + coldatas[0] + '</td>';
result += '<td>' + coldatas[1] + '</td>';
result += '<td>' + coldatas[2] + '</td>';
result += '<td>' + coldatas[3] + '</td>';
result += '</tr>';
}
result += '</table>';
// console.log( result );
document.getElementById( 'result' ).innerHTML = result;
} else {
alert ( "페이지 오류" );
}
}
};
request.open( 'get', 'csv1.jsp', true );
request.send();
};
};
</script>
</head>
<body>
<button id="btn">요청하기</button>
<br /><hr /><br />
<textarea id="ta" rows="4" cols="100"></textarea>
<br /><hr /><br />
<div id="result">
</div>
</body>
</html>
XML 데이터 가져와서 처리하기
xml2.jsp (에러)
<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.naming.Context"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.SQLException"%>
<%@page import="javax.naming.NamingException"%>
<%@ page language="java" contentType="text/xml; charset=UTF-8" trimDirectiveWhitespaces="true"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
StringBuilder sbXml = new StringBuilder();
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource dataSource = (DataSource) envContext.lookup("jdbc/mariadb2");
conn = dataSource.getConnection();
String sql = "select * from books";
pstmt = conn.prepareStatement( sql );
rs = pstmt.executeQuery();
sbXml.append( "<books>" );
while( rs.next() ) {
sbXml.append( "<book>" );
sbXml.append( "<name>" + rs.getString( "name" ) + "</name>");
sbXml.append( "<publisher>" + rs.getString( "publisher" ) + "</publisher>" );
sbXml.append( "<author>" + rs.getString( "author" ) + "</author>" );
sbXml.append( "<price>" + rs.getInt( "price" ) + "</price>" );
sbXml.append( "<book>" );
}
sbXml.append( "</book>" );
} catch ( NamingException e ) {
System.out.println( "[에러] " + e.getMessage() );
} catch ( SQLException e ) {
System.out.println( "[에러] " + e.getMessage() );
}finally {
if( pstmt != null ) try { pstmt.close(); } catch ( SQLException e ) {}
if( rs != null ) try { rs.close(); } catch ( SQLException e ) {}
}
%>
</body>
</html>
ajax03.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- ajax02.jsp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'btn' ).onclick = function() {
const request = new XMLHttpRequest();
request.onreadystatechange = function() {
if( request.readyState == 4 ) {
if( request.status == 200 ) {
// 문자열
// console.log( typeof request.responseText );
// XML 객체
// console.log( typeof request.responseXML );
// console.log( request.responseXML );
const xmlData = request.responseXML;
const names = xmlData.getElementsByTagName( 'name' );
// console.log( names );
// console.log( names.length );
// console.log( names[0] );
// console.log( names[0].innerHTML );
const publishers = xmlData.getElementsByTagName( 'publisher' );
const authors = xmlData.getElementsByTagName( 'author' );
const prices = xmlData.getElementsByTagName( 'price' );
let result = '<table border="1">';
for( let i=0; i<names.length; i++ ) {
result += '<tr>';
result += '<tr>' + names[i].innerHTML + '</td>';
result += '<tr>' + publishers[i].innerHTML + '</td>';
result += '<tr>' + authors[i].innerHTML + '</td>';
result += '<tr>' + prices[i].innerHTML + '</td>';
result += '</tr>';
}
result += '</table>';
document.getElementById( 'result' ).innerHTML = result;
} else {
alert ( "페이지 오류" );
}
}
};
request.open( 'get', 'xml2.jsp', true );
request.send();
};
};
</script>
</head>
<body>
<button id="btn">요청하기</button>
<br /><hr /><br />
<textarea id="ta" rows="4" cols="100"></textarea>
<br /><hr /><br />
<div id="result">
</div>
</body>
</html>
JSON 데이터 가져와서 처리하기
jsp3.jsp (에러)
<%@ page language="java" contentType="text/plain; charset=UTF-8"
pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>
<%@ page import="javax.naming.InitialContext"%>
<%@ page import="javax.naming.Context"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="javax.naming.NamingException"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="javax.sql.DataSource"%>
<%@ page import="org.json.simple.JSONArray" %>
<%@ page import="org.json.simple.JSONObject" %>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
JSONArray jsonArray = new JSONArray();
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup( "java:comp/env" );
DataSource dataSource = (DataSource) envCtx.lookup( "jdbc/mariadb2" );
conn = dataSource.getConnection();
while( rs.next() ) {
JSONObject obj = new JSONObject();
obj.put( "name", rs.getString( "name" ) );
obj.put( "publisher", rs.getString( "publisher" ) );
obj.put( "author", rs.getString( "author" ) );
obj.put( "price", rs.getString( "price" ) );
jsonArray.add( obj );
}
} catch ( NamingException e ) {
System.out.println( "[에러] " + e.getMessage() );
} catch ( SQLException e ) {
System.out.println( "[에러] " + e.getMessage() );
} finally {
if( rs != null ) rs.close();
if( pstmt != null ) pstmt.close();
if( conn != null ) conn.close();
}
out.println( jsonArray );
%>
ajax04.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- ajax02.jsp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'btn' ).onclick = function() {
const request = new XMLHttpRequest();
request.onreadystatechange = function() {
if( request.readyState == 4 ) {
if( request.status == 200 ) {
const data = request.responseText.trim();
const jsonData = JSON.parse( data );
// console.log( data );
// console.log( jsonData );
// console.log( jsonData[0] );
// console.log( jsonData[0].name );
let result = '<table border="1">';
for( let i=0; i<jsonData.length; i++ ) {
result += '<tr>';
result += '<td>' + jsonData[i].name + '</td>';
result += '<td>' + jsonData[i].publisher + '</td>';
result += '<td>' + jsonData[i].author + '</td>';
result += '<td>' + jsonData[i].price + '</td>';
result += '</tr>';
}
result += '</table>';
document.getElementById( 'result' ).innerHTML = result;
} else {
alert ( "페이지 오류" );
}
}
};
request.open( 'get', 'json3.jsp', true );
request.send();
};
};
</script>
</head>
<body>
<button id="btn">요청하기</button>
<br /><hr /><br />
<textarea id="ta" rows="4" cols="100"></textarea>
<br /><hr /><br />
<div id="result">
</div>
</body>
</html>
영화 순위 / 이름 주간 박스오피스 출력
ajax05.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>
<script type="text/javascript">
window.onload = function() {
document.getElementById('btn').onclick = function() {
const request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
const xmlData = request.responseXML;
const weeklyBoxOffices = xmlData.getElementsByTagName('weeklyBoxOffice');
const ranks = xmlData.getElementsByTagName('rank');
const moviename = xmlData.getElementsByTagName('movieNm');
let result = '<table border="1">';
for (let i = 0; i < weeklyBoxOffices.length; i++) {
result += '<tr>';
result += '<td>' + ranks[i].innerHTML + '</td>';
result += '<td>' + moviename[i].innerHTML + '</td>';
result += '</tr>';
}
result += '</table>';
document.getElementById('result').innerHTML = result;
} else {
alert('페이지 오류');
}
}
};
request.open('GET', 'http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchWeeklyBoxOfficeList.xml?key=f5eef3421c602c6cb7ea224104795888&targetDt=20120101', true);
request.send();
};
};
</script>
</head>
<body>
<button id="btn">요청하기</button>
<br />
<textarea id="ta" rows="4" cols="100"></textarea>
<div id="result"></div>
</body>
</html>