Asynchronous Javascript And Xml
서버와 통신하는 도중에도 조작하는 작업이 가능하다.
필요한 데이터만 요청해서 받아온다.
할 수 있는 일이 제한적이다.
back/forward 버튼, 북마크에 문제가 있다.
XMLHttpRequest
5가지의 상태를 갖는다.
- 초기상태 0
readState라는 속성 - open()으로 서버와 연결이 되면 readState값이 1이된다.
send()로 보내지면 2, 처리중일 때는 3, 서버로부터 결과값이 도착하면 4가 된다.
status 값이 200이면 완료가 된 것이다. 200이 아니면 다 에러다.
UI와 network는 main쓰레드에서 같이 돌아간다. 이것을 비동기식, 동기식으로 나눠서 network에 따로 쓰레드를 지정해 줄 수 있다.
JSON(JavaScript Object Notation)
XML은 JSON보다 무겁고 JSON은 경량화 되어 있다.
JSON은 XML보다 적은 용량으로 데이터를 교환할 수 있다.
JSON은 데이터 타입을 갖고 XML은 모두 String형 이다.
JSON에서 가장 많이 쓰는 json-simple library를 다운받아야 사용이 가능하다.
https://code.google.com/p/json-simple/
다운로드후 해당 프로젝트에 복사를 해주고 add to build path해준다.
JSON은 순서없이 관리를 하는 set구조를 가지고 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import org.json.simple.JSONObject; public class Ex1 { public static void main(String[] args) { JSONObject obj = new JSONObject(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); obj.put("nickname",null); System.out.println(obj); } } |
결과값 :
{"balance":1000.21,"is_vip":true,"num":100,"name":"foo","nickname":null}
LinkedHashMap을 이용한 출력
JSONObject를 쓴것과 다르게 값을 넣은 순서대로 출력이 가능하다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.LinkedHashMap; import java.util.Map; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class Ex1 { public static void main(String[] args) { Map obj = new LinkedHashMap(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); obj.put("nickname",null); String jsonText = JSONValue.toJSONString(obj); System.out.println(jsonText); } } |
결과값:
{"name":"foo","num":100,"balance":1000.21,"is_vip":true,"nickname":null}
JSONArray()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.util.LinkedHashMap; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class Ex1 { public static void main(String[] args) { JSONArray list = new JSONArray(); list.add("foo"); list.add(new Integer(100)); list.add(new Double(1000.21)); list.add(new Boolean(true)); list.add(null); System.out.println(list); } } |
결과값:
["foo",100,1000.21,true,null]
LinkedList사용 예제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class Ex1 { public static void main(String[] args) { LinkedList list = new LinkedList(); list.add("foo"); list.add(new Integer(100)); list.add(new Double(1000.21)); list.add(new Boolean(true)); list.add(null); String jsonText = JSONValue.toJSONString(list); System.out.println(jsonText); } } |
결과값 :
["foo",100,1000.21,true,null]
addAll()로 두 JSON합치기
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 | import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class Ex1 { public static void main(String[] args) { JSONArray list1 = new JSONArray(); list1.add("foo"); list1.add(new Integer(100)); list1.add(new Double(1000.21)); JSONArray list2 = new JSONArray(); list2.add(new Boolean(true)); list2.add(null); list2.addAll(list1); System.out.println(list2); } } |
결과값 :
[true,null,"foo",100,1000.21]
JSONObject와 JSONArray
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 | import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class Ex1 { public static void main(String[] args) { JSONArray list1 = new JSONArray(); list1.add("foo"); list1.add(new Integer(100)); list1.add(new Double(1000.21)); JSONArray list2 = new JSONArray(); list2.add(new Boolean(true)); list2.add(null); JSONObject obj = new JSONObject(); obj.put("name", "foo"); obj.put("num", new Integer(100)); obj.put("balance", new Double(1000.21)); obj.put("is_vip", new Boolean(true)); obj.put("nickname", null); obj.put("list1", list1); obj.put("list2", list2); System.out.println(obj); } } |
결과값 :
{"list1":["foo",100,1000.21],"balance":1000.21,"is_vip":true,"num":100,
"list2":[true,null],"name":"foo","nickname":null}
Ajax 를 이용한 서버와의 통신
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 | package ajax.web; import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class SimpleAjaxServelt */ public class SimpleAjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SimpleAjaxServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data = "Hi Simple Ajax Client"; data = URLEncoder.encode(data,"UTF-8").replace("+", "%20"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.print(data); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/ xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>AjaxExample</display-name> <servlet> <servlet-name>SimpleAjaxServlet</servlet-name> <servlet-class>ajax.web.SimpleAjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleAjaxServlet</servlet-name> <url-pattern>/SimpleAjaxServlet</url-pattern> </servlet-mapping> </web-app> |
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 | <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> <script type="text/javascript"> function getXMLHttpRequest(){ if(window.ActiveXObject){ try{ return new ActiveXObject("Msxml2.XMLHTTP"); // 익스플로러는 ActiveXObject를 쓴다. // 표준 방식은 XMLHttpRequest이다. }catch(e){ try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e2){ return null; } } }else if(window.XMLHttpRequest){ return new XMLHttpRequest(); }else{ return null; } } var xmlHttpRequest = getXMLHttpRequest(); function responseAjax(){ if(xmlHttpRequest.readyState==4){ // 통신완료 if(xmlHttpRequest.status==200){ // 에러가 없을때 var responseText = decodeURIComponent(xmlHttpRequest.responseText); var messageElement = document.getElementById("message"); messageElement.innerHTML = "The server said: "+responseText; } } } function sendRequest(){ var url = "http://localhost:9090/AjaxExample/SimpleAjaxServlet"; xmlHttpRequest.open("GET",url,true);// get방식 xmlHttpRequest.onreadystatechange = responseAjax; // responseAjax는 call back함수 : 명시적으로 호출하지 않고 쓰는 함수, 상황에 따라 호출 한다. xmlHttpRequest.send(null); } </script> </head> <body> <form> <input type="button" value="서버로부터 정보를 수신" onclick="sendRequest()"> </form> <p id="message"></p> </body> </html> |
AJAX를 이용한 서버와의 통신(XML사용)
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 | package ajax.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class SimpleXMLAjaxServlet extends HttpServlet { /** * @see HttpServlet#HttpServlet() */ /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("messagelist"); doc.appendChild(rootElement); Element messageElement = doc.createElement("message"); messageElement.appendChild(doc.createTextNode("Hi, Simple XML Ajax Client")); rootElement.appendChild(messageElement); response.setCharacterEncoding("utf-8"); response.setContentType("application/xml; charset=utf-8"); PrintWriter out = response.getWriter(); //transform a DOM tree to a XML Document TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); transformer.transform(source,result); }catch(ParserConfigurationException e){ e.printStackTrace(); }catch(TransformerException e){ e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } |
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 | <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> <script type="text/javascript"> function getXMLHttpRequest(){ if(window.ActiveXObject){ try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e2){ return null; } } }else if(window.XMLHttpRequest){ return new XMLHttpRequest(); }else{ return null; } } var xmlHttpRequest = getXMLHttpRequest(); function responseAjax(){ if(xmlHttpRequest.readyState == 4){ if(xmlHttpRequest.status==200){ var responseXML = xmlHttpRequest.responseXML; var messageElement = responseXML.getElementsByTagName('message')[0]; var messageText = messageElement.childNodes[0].nodeValue; var messageElement = document.getElementById("message"); messageElement.innerHTML = "The server said : "+messageText; } } } function sendRequest(){ var url = "http://localhost:9090/AjaxExample/SimpleXMLAjaxServlet"; xmlHttpRequest.open("GET",url,true); xmlHttpRequest.onreadystatechange = responseAjax; xmlHttpRequest.send(null); } </script> </head> <body> <form> <input type="button" value="서버로부터 XML 문서를 수신" onclick="sendRequest()"> <p id="message"></p> </form> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com /xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>AjaxExample</display-name> <servlet> <servlet-name>SimpleAjaxServlet</servlet-name> <servlet-class>ajax.web.SimpleAjaxServlet</servlet-class> </servlet> <servlet> <servlet-name>SimpleXMLAjaxServlet</servlet-name> <servlet-class>ajax.web.SimpleXMLAjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleAjaxServlet</servlet-name> <url-pattern>/SimpleAjaxServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>SimpleXMLAjaxServlet</servlet-name> <url-pattern>/SimpleXMLAjaxServlet</url-pattern> </servlet-mapping> </web-app> |
XML
'(Before)BitSchool' 카테고리의 다른 글
2014/06/17 Servlet,JSP웹 프로그래밍 - 쿼리 수행기 (0) | 2014.06.17 |
---|---|
2014/06/16 AJAX - JSON사용 서버와의 통신,AJAX 서버/클라이언트,서버에서 오라클하기,ajax계산기 (0) | 2014.06.16 |
2014/06/12 JavaScript - 기본함수, 사용자 함수, 이벤트 (0) | 2014.06.12 |
2014/06/11 JavaScript (0) | 2014.06.11 |
2014/06/11 XML - SAX 파서, generic오류, 생성자 자동 만들기, PULL파서 (0) | 2014.06.11 |