티스토리 뷰

JSP

Http통신을 이용한 JSON 받아오기

개발로퍼 2016. 11. 25. 15:09

Http통신을 이용하여 JSON형태를 받아올 때 사용한다.





Http Request

var httpRequest = null;
// XMLHttpRequest 얻기
function getHttpRequest(){
	var httpReq = null;
	try{
		var httpReq = new XMLHttpRequest();	
	} catch (e){
		httpReq = null;
	}

	return httpReq;
}

// httpRequest 를 얻고 콜백함수 등록
function reqHttpData(url, callback){
	if(httpRequest == null)
		httpRequest = getHttpRequest();
	if(httpRequest == null)
		return;

	httpRequest.open("GET", url, true);
	httpRequest.onreadystatechange = callback;
	httpRequest.send(null);
}


http통신으로 먼저 서버와 연결시킨다.



Onload();

window.onload = init;

function init(){
	var url = "./json.jsp";
	reqHttpData(url, onLoadHttpData1);
}

function onLoadHttpData1(){
	if(httpRequest.readyState != 4)
	return;
	parseJsonData1(httpRequest.responseText);
}

function parseJsonData1(data){
	var array = eval("("+data+")");
	var output = "";

	output += "";

	for(var i=0;i";
		output += array.department[i].dep_name;
		output += "";
	}
	
	document.getElementById("department").innerHTML = output;
}


위 예제는 select box에 db에 포함된 값을 뿌려주는 구문이다.

body에 onload를 사용하여 실행하여도 되지만, 여러개의 스크립트가 onload해야할 경우도 있기 때문에 script안에서 onload를 실행하였다.


json형식을 data로 받아와 json을 array에 담고 "department" ID객체의 select box에 하나씩 뿌려주는 구문.


응용편(팝업이용)

	
	
가맹점 목록 검색 결과
function parseJsonData1(data){
	var array = eval("("+data+")");
	var output = "";
	
	output += "<table class='table table-bordered'>";
	output += "<thead><tr>";
	output += "<th width='30%'>지점명</th>";
	output += "<th width='30%'>가맹점 CODE</th>";
	output += "<th width='20%'>브랜드</th>";
	output += "<th width='20%'>지역</th>";
	output += "</tr></thead><tbody>";

	for(var i=0;i<array.branch.length;i++){
		output += "<tr class='text-center'><td><a href='#' onclick='datalist(\""+array.branch[i].f_idx+"\");'>"+array.branch[i].f_branch+"</a></td>"; 
		output += "<td>"+array.branch[i].f_code+"</td>";
		output += "<td>"+array.branch[i].f_brand+"</td>";
		output += "<td>"+array.branch[i].f_region+"</td>";
		output += "</tr>";
	}
	output += "</tbody></table>";

	document.getElementById("customerlist").innerHTML = output;
}

function datalist(f_idx){
	var url = encodeURI("branch_search_json2.jsp?f_idx="+f_idx);

	reqHttpData(url, onLoadHttpData2);
}

function onLoadHttpData2(){
	if(httpRequest.readyState != 4)
		return;
	parseJsonData2(httpRequest.responseText);
}

function parseJsonData2(data){
	var array = eval("("+data+")");
	
	var f_idx = array.f_idx;
	var f_code = array.f_code;
	var f_branch = array.f_branch;
		
	opener.document.getElementById("f_idx").value = f_idx;
	opener.document.getElementById("f_code").value = f_code;
	opener.document.getElementById("f_branch").value = f_branch;
	
	
	window.close();
}

팝업창을 띄우면서 Table형식으로 1차 JSON을 뿌려주면서 검색된 값이 선택될시에 opener에 자동으로 값이 박히게 한다.


응용편2 (중복검색)

function save(){
	if(document.getElementById("text").value.trim() == ""){
		alert("입력해주세요.");
		document.getElementById("text").focus();
		return false;
	}
	
	var log_id = document.getElementById("log_id").value;
	var url = "./check.jsp?log_id="+log_id;
	
	reqHttpData(url, onLoadHttpData1);
}

function onLoadHttpData1(){
	if(httpRequest.readyState != 4)
	return;
	parseJsonData1(httpRequest.responseText);
}

function parseJsonData1(data){
	var array = eval("("+data+")");
	var count = array.count;

	if(count == 0){
		document.frm1.action = "employee_insert_ok.jsp";
		document.frm1.encoding = "multipart/form-data";
		document.frm1.method = "post";
		document.frm1.submit();
	}else{
		alert("중복된 LoginID 입니다.");
		document.getElementById("log_id").focus();
		return false;
	}
}


json.jsp

JSONObject jsonMain = new JSONObject();
JSONArray jArray = new JSONArray();
JSONArray jArray2 = new JSONArray();

String sql = null;

try{
	conn = DriverManager.getConnection(jdbcUrl, dbid, dbPwd);

	sql = "select * from sub_department";
	
	stmt = conn.createStatement();
	rs = stmt.executeQuery(sql);
	int i = 0;
	
	while(rs.next()){
		JSONObject jObject = new JSONObject();
	
		jObject.put("dep_idx", rs.getString("dep_idx"));
		jObject.put("dep_name", rs.getString("dep_name"));
		jObject.put("dep_num", rs.getString("dep_num"));
		
		jArray.add(i, jObject);
		
		i = i + 1;	
	}

	jsonMain.put("department", jArray);
	
	
	sql = "select * from sub_rank";
	
	rs = stmt.executeQuery(sql);
	int j = 0;
	
	while(rs.next()){
		JSONObject jObject = new JSONObject();
	
		jObject.put("r_idx", rs.getString("r_idx"));
		jObject.put("r_name", rs.getString("r_name"));
		jObject.put("r_num", rs.getString("r_num"));
		
		jArray2.add(j, jObject);
		
		j = j + 1;	
	}

	jsonMain.put("rank", jArray2);
	
	
	out.println(jsonMain.toJSONString());
	out.flush();

} catch(Exception e){
	e.printStackTrace();
} 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){}
}


branch_search_json.jsp

JSONObject jsonMain = new JSONObject();
JSONArray jArray = new JSONArray();

String f_branch = request.getParameter("f_branch");
String sql = null;

try{
	conn = DriverManager.getConnection(jdbcUrl, dbid, dbPwd);

	sql = "select * from franchise where f_branch like '%"+f_branch+"%'";
	
	stmt = conn.createStatement();
	rs = stmt.executeQuery(sql);
	int i = 0;
	
	while(rs.next()){
		JSONObject jObject = new JSONObject();
	
		jObject.put("f_idx", rs.getString("f_idx"));
		jObject.put("f_branch", rs.getString("f_branch"));
		jObject.put("f_code", rs.getString("f_code"));
		jObject.put("f_brand", rs.getString("f_brand"));
		jObject.put("f_region", rs.getString("f_region"));
		
		jArray.add(i, jObject);
		
		i = i + 1;	
	}

	jsonMain.put("branch", jArray);
	out.println(jsonMain.toJSONString());
	out.flush();

} catch(Exception e){
	e.printStackTrace();
} 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){}
}


branch_search_json2.jsp

DecimalFormat df = new DecimalFormat("#,##0");

JSONObject jsonMain = new JSONObject();
JSONArray jArray = new JSONArray();

String f_idx = request.getParameter("f_idx");

try{
	conn = DriverManager.getConnection(jdbcUrl, dbid, dbPwd);

	sql = "select * from franchise where f_idx='"+f_idx+"'";
	
	stmt = conn.createStatement();
	rs = stmt.executeQuery(sql);

	while(rs.next()){
		JSONObject jObject = new JSONObject();
	
		jObject.put("f_idx", rs.getString("f_idx"));
		jObject.put("f_branch", rs.getString("f_branch"));
		jObject.put("f_code", rs.getString("f_code"));
		jObject.put("f_brand", rs.getString("f_brand"));
		jObject.put("f_region", rs.getString("f_region"));
		jObject.put("f_barcode", rs.getString("f_barcode"));
		jObject.put("f_department", rs.getString("f_department"));
		jObject.put("f_store", rs.getString("f_store"));
		jObject.put("f_management", rs.getString("f_management"));
		jObject.put("f_open", rs.getString("f_open"));
		jObject.put("f_log", rs.getString("f_log"));
		jObject.put("f_membership", df.format(rs.getInt("f_membership")));
		jObject.put("f_deposit", df.format(rs.getInt("f_deposit")));
		jObject.put("f_loyalty", df.format(rs.getInt("f_loyalty")));
		jObject.put("f_loan", df.format(rs.getInt("f_loan")));
		jObject.put("f_loan_interest", df.format(rs.getInt("f_loan_interest")));
		
		out.println(jObject.toJSONString());
		out.flush();
	}
} catch(Exception e){
	e.printStackTrace();
} 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){}
}



check.jsp

JSONObject jsonMain = new JSONObject();
JSONArray jArray = new JSONArray();

String log_id = request.getParameter("log_id");
String sql = null;

try{
	conn = DriverManager.getConnection(jdbcUrl, dbid, dbPwd);

	sql = "select count(*) from login where log_id ='"+log_id+"'";
	
	stmt = conn.createStatement();
	rs = stmt.executeQuery(sql);

	while(rs.next()){
		JSONObject jObject = new JSONObject();
	
		jObject.put("count", rs.getInt(1));

		out.println(jObject.toJSONString());
		out.flush();
	}
} catch(Exception e){
	e.printStackTrace();
} 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){}
}


'JSP' 카테고리의 다른 글

JSP paging(pagenation) 페이징 소스  (2) 2017.03.11
Session 관리하기  (0) 2016.12.01
금액) 숫자 세자리마다 , 넣어주기  (0) 2016.10.25
다음 우편번호 주소 API 사용하기  (1) 2016.10.21
댓글
최근에 올라온 글
«   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
Total
Today
Yesterday