'프로그래밍 > Library' 카테고리의 다른 글
[Subversion] 오리지널 서브버젼 이클립스 플러그인 (0) | 2009.08.28 |
---|---|
[Subclipse] ignore (0) | 2009.04.02 |
[MD5] MD5 암호화 (0) | 2009.03.13 |
[BASE64] BASE64 인코딩 (0) | 2009.02.27 |
[가니메데] 이클립스 가니메데에서 WTP사용하기 (0) | 2009.02.03 |
[Subversion] 오리지널 서브버젼 이클립스 플러그인 (0) | 2009.08.28 |
---|---|
[Subclipse] ignore (0) | 2009.04.02 |
[MD5] MD5 암호화 (0) | 2009.03.13 |
[BASE64] BASE64 인코딩 (0) | 2009.02.27 |
[가니메데] 이클립스 가니메데에서 WTP사용하기 (0) | 2009.02.03 |
import java.security.*; public class SecurityUtil { /** * byte[] ret = HashUtil.digest("MD5", "abcd".getBytes()); * 처럼 호출 */ public static byte[] digest(String alg, byte[] input) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(alg); return md.digest(input); } public static String getCryptoMD5String(String inputValue) throws Exception { if( inputValue == null ) throw new Exception("Can't conver to Message Digest 5 String value!!"); byte[] ret = digest("MD5", inputValue.getBytes()); String result = Base64Util.encode(ret); return result; } } |
import sun.misc.*; import java.io.*; /** * * Filename : Base64Util.java * Class : Base64Util * Function : Base64 Encoding/Decoding을 수행하는 클래스 * Comment : * History : 2000-08-16 2:48오후 * * @version 1.0 * @author carouser */ public class Base64Util { public Base64Util() {} /** * Base64Encoding을 수행한다. binany in ascii out * * @param encodeBytes encoding할 byte array * @return encoding 된 String */ public static String encode(byte[] encodeBytes) { BASE64Encoder base64Encoder = new BASE64Encoder(); ByteArrayInputStream bin = new ByteArrayInputStream(encodeBytes); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = null; try{ base64Encoder.encodeBuffer(bin, bout); } catch(Exception e) { System.out.println("Exception"); e.printStackTrace(); } buf = bout.toByteArray(); return new String(buf).trim(); } /** * Base64Decoding 수행한다. binany out ascii in * * @param strDecode decoding할 String * @return decoding 된 byte array */ public static byte[] decode(String strDecode) { BASE64Decoder base64Decoder = new BASE64Decoder(); ByteArrayInputStream bin = new ByteArrayInputStream(strDecode.getBytes()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = null; try { base64Decoder.decodeBuffer(bin, bout); } catch(Exception e) { System.out.println("Exception"); e.printStackTrace(); } buf = bout.toByteArray(); return buf; } } |
[Subclipse] ignore (0) | 2009.04.02 |
---|---|
[firebug] 파이어버그 가이드 (0) | 2009.03.20 |
[BASE64] BASE64 인코딩 (0) | 2009.02.27 |
[가니메데] 이클립스 가니메데에서 WTP사용하기 (0) | 2009.02.03 |
[Cognos] 기본개념 (0) | 2009.01.29 |
key=value로 이루어져 있는 프라퍼티 값들을 통해서 스트럿츠2의 동작을 제어하게 된다.
struts.properties 파일은 struts2-core-2.x.jar 의 org/apache/struts2/default.properties 에 있는 디폴트 값을 오버라이드 할 수 있는데 그때는 디폴트값과 다른 것만 설정하면 된다.
struts.i18n.reload=true #properties 파일들을 수정하고 저장하면,다음 요청에 변경사항이 반영됨을 볼 수 있음. struts.devMode=true struts.configuration.xml.reload=true struts.continuations.package=org.apache.struts2.showcase struts.custom.i18n.resources=globalMessages struts.url.http.port=9090 struts.action.extension=action struts.serve.static=true struts.serve.static.browserCache=false struts.multipart.maxSize=2097252 #디폴트로 임시디렉토리 지정. 최대 사이즈 지정 |
[Struts2] 링크들 (0) | 2009.04.07 |
---|---|
[iBatis] There is no DAO implementation found for... (0) | 2009.04.06 |
[펌] Spring 2.0과 Ruby(JRuby)의 연동 (0) | 2007.11.28 |
[펌] Introduction to Hibernate 2 (0) | 2007.11.28 |
[펌] Hibernate 3.02 Reference Document 한글 버전 (0) | 2007.11.28 |
StringReader sr = new StringReader(sb.toString()); InputSource xmlSource = new InputSource(sr); ret = xpath.evaluate("//GetLASeR/RET", xmlSource); // 여기까지는 가능 ret = xpath.evaluate("//GetLASeR/RET", xmlSource); // 여기서 예외발생 - Stream closed. |
// 검색 원본 InputSource 객체 생성 - 검색 원본이 XML문서 파일이므로. InputSource xmlSource = new InputSource("WebContent/ch13/bml.xml"); System.out.println("--책 아이디로 제목 찾기"); String title = xpath.evaluate("/booklist/book/title[../@id='b2']", xmlSource); System.out.println(title); System.out.println("--책 아이디로 book 엘리먼트 찾기"); Node nBook = (Node) xpath.evaluate("/booklist/book[@id='b2']", xmlSource, XPathConstants.NODE); Element eBook = (Element) nBook; System.out.println(eBook.getAttribute("kind")); |
[jdom] jdom을 이용한 XML 문서 생성하기 (0) | 2010.09.03 |
---|---|
[json] org.json.* 사용하기 (0) | 2010.04.20 |
[XPath] String으로 InputSource 생성하기 (0) | 2009.03.02 |
[에러] javax.xml.xpath.XPathFactory 사용 시, newInstance() 생성이 안될 때 (0) | 2009.03.02 |
06 XML 마지막날. (0) | 2007.11.28 |
[json] org.json.* 사용하기 (0) | 2010.04.20 |
---|---|
[XPath] StringReader를 이용한 InputSource 를 소스로 해서, XPath.evaluate() 시 에러 (0) | 2009.03.03 |
[에러] javax.xml.xpath.XPathFactory 사용 시, newInstance() 생성이 안될 때 (0) | 2009.03.02 |
06 XML 마지막날. (0) | 2007.11.28 |
05 스키마... (0) | 2007.11.28 |
[XPath] StringReader를 이용한 InputSource 를 소스로 해서, XPath.evaluate() 시 에러 (0) | 2009.03.03 |
---|---|
[XPath] String으로 InputSource 생성하기 (0) | 2009.03.02 |
06 XML 마지막날. (0) | 2007.11.28 |
05 스키마... (0) | 2007.11.28 |
04 DTD... (0) | 2007.11.28 |
[firebug] 파이어버그 가이드 (0) | 2009.03.20 |
---|---|
[MD5] MD5 암호화 (0) | 2009.03.13 |
[가니메데] 이클립스 가니메데에서 WTP사용하기 (0) | 2009.02.03 |
[Cognos] 기본개념 (0) | 2009.01.29 |
[EXCEL] 셀 범위로 드롭다운 목록 만들기 (0) | 2009.01.29 |
<tomcat-users> <user name="tomcat" password="tomcat" roles="tomcat,manager" /> <user name="role1" password="tomcat" roles="role1" /> <user name="both" password="tomcat" roles="tomcat,role1" /> <!-- Define new user name and password with the role --> <user name="wsuser" password="wspwd" roles="wsuser" /> </tomcat-users> |
<Security-constraint> <web-resource-collection> <web-resource-name>Protected</web-resource-name> <!-- specify the directory for restricted Web Services application --> <url-pattern>/protected/*</url-pattern> </web-resource-collection> <auth-constraint> <!-- specify the role name of the new user added in step 2 --> <role-name>wsuser</role-name> </web-resource-collection> <auth-constraint> </security-constraint> <!-- Define the Login Configuration for this Application --> <login-config> <auth-method>BASIC</auth-method> <realm-name>Protected Web Services</realm-name> </login-config> <!-- 이거 없으면 경고문 나옴. --> <security-role> <role-name>wsuser</role-name> </security-role> |
import org.apache.axis.client.Call; import org.apache.axis.client.Service; import javax.xml.namespace.QName; public class TestClient { public static void main(String [] args) { try { String endpoint = "http://localhost:8080/axis/protected/EchoService.jws"; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpoint) ); call.setOperationName(new QName("echoString")); call.setUsername("wsuser"); call.setPassword("wspwd"); String ret = (String) call.invoke( new Object[] { "Hello!" } ); System.out.println("Sent 'Hello!', got '" + ret + "'"); } catch (Exception e) { System.err.println(e.toString()); } } } |
// HTTP BASIC-AUTH String userPassword = "wsuser" + ":" +"wspwd"; // USERNAME:PASSWORD //// Encode the bytes of the string //String encoding = new sun.misc.BASE64Encoder().encodeBuffer(userPassword.getBytes()); //// Set the "Authorization" request property for the URLConnection //uc.setRequestProperty("Authorization","Basic " + encoding.substring(0, encoding.length() - 2)); // chuck로 인해 줄바꿈 문자 삭제. PW가 길면 문제. String encoding = new String(Base64.encodeBase64(userPassword.getBytes(), false)); // false - chunk하지 않는다(chuck하면 76자 단위로 줄바꿈) uc.setRequestProperty("Authorization","Basic " + encoding); |
[jQuery] select option (0) | 2009.05.14 |
---|---|
[JavaScript] language="JavaScript" type="text/javascript" (0) | 2009.04.07 |
[Servlet] Servlet에서 request의 input stream을 이용해서 읽어들일 때 (0) | 2009.02.19 |
[펌] Getting the Requesting URL in a Servlet (0) | 2009.02.19 |
[스터디] Ajax 마스터하기, Part 11: 서버 측의 JSON (0) | 2009.02.16 |
[java] 소스 분석 (0) | 2009.09.06 |
---|---|
[HttpURLConnection] POST로 파라미터 넘기기 (0) | 2009.07.27 |
CLASSPATH (0) | 2009.01.06 |
HttpURLConnection 사용례 (0) | 2009.01.06 |
[펌] HttpURLConnection 을 이용하세요 (0) | 2009.01.02 |
PrintWriter pw = new PrintWriter(uc.getOutputStream()); // pw.write("url="+url); pw.write(sb.toString()); pw.flush(); pw.close(); |
// String a = request.getParameter("//DATETIME[@type='T' and @qualifier='DOCUMENT']/YEAR"); // 이건 특수문자에 띄어쓰기까지 있어서 데이터를 념겨받을 수 없다 // String a = request.getParameter("sap_element_01"); // String b = request.getParameter("sap_element_02"); // String c = request.getParameter("sap_element_03"); // System.out.println(a); BufferedReader br = request.getReader(); String str; StringBuffer sb = new StringBuffer(); while((str = br.readLine()) != null) { sb.append(str); } br.close(); PrintWriter w = response.getWriter(); w.println(request.getParameter("sap_element_01") + " " + request.getParameter("sap_element_02") + " " + request.getParameter("sap_element_03")); w.flush(); w.close(); |
[JavaScript] language="JavaScript" type="text/javascript" (0) | 2009.04.07 |
---|---|
[HTTP] HTTP BASIC-AUTH (0) | 2009.02.27 |
[펌] Getting the Requesting URL in a Servlet (0) | 2009.02.19 |
[스터디] Ajax 마스터하기, Part 11: 서버 측의 JSON (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 10: 데이터 전송에 JSON 사용하기 (0) | 2009.02.16 |
http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789The most convenient method for reconstructing the original URL is to use
ServletRequest.getRequestURL()
, which returns all but the
query string. Adding the query string reconstructs an equivalent of
the original requesting URL:
// http://hostname.com/mywebapp/servlet/MyServlet/a/b;c=123?d=789If the hostname is not needed,
public static String getUrl(HttpServletRequest req) {
String reqUrl = req.getRequestURL().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUrl += "?"+queryString;
}
return reqUrl;
}
ServletRequest.getRequestURI()
should be used:
// /mywebapp/servlet/MyServlet/a/b;c=123?d=789The original URL can also be reconstructed from more basic components available to the servlet:
public static String getUrl2(HttpServletRequest req) {
String reqUri = req.getRequestURI().toString();
String queryString = req.getQueryString(); // d=789
if (queryString != null) {
reqUri += "?"+queryString;
}
return reqUri;
}
// http://hostname.com:80/mywebapp/servlet/MyServlet/a/b;c=123?d=789
public static String getUrl3(HttpServletRequest req) {
String scheme = req.getScheme(); // http
String serverName = req.getServerName(); // hostname.com
int serverPort = req.getServerPort(); // 80
String contextPath = req.getContextPath(); // /mywebapp
String servletPath = req.getServletPath(); // /servlet/MyServlet
String pathInfo = req.getPathInfo(); // /a/b;c=123
String queryString = req.getQueryString(); // d=789
// Reconstruct original requesting URL
String url = scheme+"://"+serverName+":"+serverPort+contextPath+servletPath;
if (pathInfo != null) {
url += pathInfo;
}
if (queryString != null) {
url += "?"+queryString;
}
return url;
}
[HTTP] HTTP BASIC-AUTH (0) | 2009.02.27 |
---|---|
[Servlet] Servlet에서 request의 input stream을 이용해서 읽어들일 때 (0) | 2009.02.19 |
[스터디] Ajax 마스터하기, Part 11: 서버 측의 JSON (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 10: 데이터 전송에 JSON 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 9: Google Ajax Search API 사용하기 (0) | 2009.02.16 |
■ SOAP (Simple Object Access Protocol)이란 무엇인가?
SOAP이란 것은 무엇일까?
검색엔진에서 SOAP을 검색하면 무슨 비누, 향수, 샴푸등등... 이딴 것들만 검색된다.
그럼 SOAP은 세제란 뜻인가? 절대 그럴리 없다..
이 강좌가 무슨 “빨래 이런 세제를 쓰면 살균 소독까지.. ” 강좌도 아니고 무슨 비누란 말인가?
아직은 SOAP이 표준화 과정에 있고 따라서 많은 자료들이 만들어지지 못해서 이런 일이 일어나는 것 뿐이다.. "(,. )a
SOAP은 XML과 HTTP 통신을 기반으로 하여 네트워크 상에 존재하는 각종 컴포넌트간의 호출을 효율적으로 실현하기 위한 방법을 제시하는 규약이다.
말이 좀 어렵다.. 쉽게 말하면 네트워크 상에서 Client와 Service Provider간에 메시지를 요청하고 이에 응답해주는 방법을 제공하는 것이다.. 이러한 방식들은 기존의 RPC(Remote Procedure Call)라 묶여서 불려오던 것들이다.. 따라서 SOAP은 RPC의 한가지 방법이라 할 수가 있다.. 더 어려운가? ^^:
SOAP은 여러 Application Layer Protocol 들 중에 HTTP를 사용함으로써 여러 시스템간의 통신과 통합을 위한 좀더 단순하면서도 가벼운 메카니즘을 제공한다,,
이외에... HTTP를 사용하게 된 중요한 이유는 바로 방화벽에 제한을 받지 않는 범용성 때문이라 말할 수 있다.
다른 Application Layer Protocol의 경우 그들만의 약정된 TCP 또는 UDP 포트를 사용하기 때문에 인터넷상에 설치되어있는 방화벽에 많은 제약을 받게 된다.. 하지만 SOAP은 HTTP를 채택함으로써 방화벽의 제약을 받지 않고 불특정 다수의 클라이언트 또는 인터넷 상의 특정한 서버와의 RPC를 효율적으로 수행할 수 있도록 해준다.
그렇다면 보안의 문제는 아예 생각지 않는 것인가? 이렇게 생각하는 사람도 있을지 모르겠다.. SOAP은 SOAP만이 가지는 특정한 HTTP Header를 방화벽의 필터링 부분에 보냄으로써 메시지의 통과여부를 가릴 수 있게 하는 방법으로 보안이라는 문제를 해결한다.
SOAP은 현재 1.1버전이 널리 사용되고 있으며, w3c와 Microsoft등과 같은 쟁쟁한 몇몇 단체들이 모여 표준화 작업이 한창이다,, 현재는 1.2 버전까지 나온 상태이다..
자세한 내용은 www.w3c.org나 www.microsoft.com을 참조하기 바란다..
그럼 본격적으로 SOAP의 내부를 살펴보도록 하자..
SOAP은 크게 다음의 4가지로 구성되어있다..
° SOAP envelope
Message에 무엇이 있는가, 누가 무엇을 다루는가, 어떤 것이 Optional이고 mandatory인가를 나타내기 위한 전체적인 framework를 제공한다..
° SOAP encoding rules
Application에 정의된 data type들의 instance를 교환하는데 사용되는 메카니즘이다.
° SOAP RPC 표현
Remote procedure call과 response들을 나타내는데 사용되는 규약을 정의한다.
° SOAP binding
두 peer 간의 전송프로토콜을 사용하여 SOAP envelope 교환에 대한 규약을 정의한다.
위의 4가지 중에 envelope와 encoding rule은 서로 다른 namespace에 정의되어있는 XML 이며, link를 걸어놓음으로써 정의된 내용들을 사용할 수 있다.
SOAP은 Message Based Protocol이기 때문에 두 시스템간의 통합 시 쌍방 간의 Message Format만을 약속하면 되므로 통합시간 및 효율을 높일 수 있으며, 매우 간단하다.
1. SOAP Message Exchange Model
SOAP은 HTTP 통신을 위한 Webserver, XML과 Service Provider의 3가지로 구성되어있다.
|
< SOAP의 동작방식 >
1) Client가 어떤 Service Provider의 Service가 어떤 것이 있는지를 파악하기 위해 제공하는 Service의 목록을 HTTP를 통해 XML형태로 요청한다. (만약 목록을 이미 알고 있는 경우라면 이 과정은 생략가능)
2) Server는 자신이 제공하는 Service의 목록을 XML로 응답을 보낸다. (만약 목록을 이미 알고 있는 경우라면 이 과정은 생략가능)
3) 응답을 받은 Client는 그 중 자신이 원하는 Service를 알아내어 다시 Provider에 요청을 한다.
4) Provider는 받은 요청에 대한 처리를 한 후 결과를 되돌려 준다.
2. SOAP Message
다음은 HTTP Request 속에 포함된 SOAP Message의 구조이다..
POST /StockQuote HTTP/1.1
Host: www.stockquoteserver.com
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
SOAPAction: "http://example.org/2001/06/quotes"
<Envelope ...>
<Header>
......
</Header>
<Body>
<Content>
......
</Content>
</Body>
</Envelope>
° Envelope : Root Tag로써 SOAP Message가 시작됨을 나타낸다.
° Header : 가외의 정보를 나타내기 위한 것으로 생략이 가능하다.
° Body : 주 내용이 들어가는 Tag이며 다양한 형태의 태그들이 들어간다.
° Content : 서비스에 대한 요청이나 응답이 들어간다.
일단 간단한 예제를 보면서 이해해보자..
SOAP은 XML의 형태로 Message를 교환한다,,,
▷ Example 1 ( Request Message 형태 )
POST /StockQuote HTTP/1.1
Host: www.stockquoteserver.com
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
SOAPAction: "http://example.org/2001/06/quotes"
<env:Envelope xmlns:env="http://www.w3.org/2001/06/soap-envelope" >
<env:Body>
<m:GetLastTradePrice
env:encodingStyle="http://www.w3.org/2001/06/soap-encoding"
xmlns:m="http://example.org/2001/06/quotes">
<symbol>DIS</symbol>
</m:GetLastTradePrice>
</env:Body>
</env:Envelope>
Service Provider가 가지고 있는 서비스 중에 LastTradePrice 정보를 요청하는 SOAP Message로 DIS의 값을 요구하고 있다.
▷ Example 2 (Response Message 형태 )
HTTP/1.1 200 OK
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
<env:Envelope xmlns:env="http://www.w3.org/2001/06/soap-envelope" >
<env:Body>
<m:GetLastTradePriceResponse
env:encodingStyle="http://www.w3.org/2001/06/soap-encoding"
xmlns:m="http://example.org/2001/06/quotes">
<Price>34.5</Price>
</m:GetLastTradePriceResponse>
</env:Body>
</env:Envelope>
Response Message의 경우에는 Client가 요청한 Service 이름에 Response가 붙게되며 (GetLastTradePriceResponse) Request에 대한 결과 값을 가지고 있다.
그럼 좀더 구체적으로 살펴보자,,
2-1. SOAP Envelope
SOAP Message는 필수항목인 SOAP envelope와 생략 가능한 SOAP Header 그리고 SOAP Body로 구성되어 있는 XML Document이다.
2-2. SOAP Header
SOAP는 Header라는 element를 통해 통신을 하는 쌍방 간의 어떤 제약없이 Message를 확장할 수 있는 융통성 있는 구조를 제공한다. 일반적으로 Header는 authentication이나 transaction과 같은 비교적 연관성이 없는 정보들을 구현할 수 있도록 해준다. Header element는 SOAP Envelope 바로 다음에 오는 첫 번째 Child element로서 모든 Header 다음에 오는 Child element들을 Header Entry라고 한다.
Example 3 ( SOAP Header block )
<env:Header xmlns:env="http://www.w3.org/2001/06/soap-envelope" >
<t:Transaction xmlns:t="http://example.org/2001/06/tx" env:mustUnderstand="1" >
5
</t:Transaction>
</env:Header>
2-3 SOAP Body
SOAP Body element는 필수 정보를 교환하기 위해 사용되는 간단한 메카니즘을 제공한다, 일반적으로 Body는 어떤 결과나 error를 보고하기 위해 사용된다. Body는 SOAP Envelope 바로 다음에 오는 Child element로서 만약 Header가 존재하면 Header 다음에 와야하고 Header가 정의되어있지 않으면 Envelope 바로 다음에 와야한다. Header와 마찬가지로 Body element 바로 다음에 오는 Child element들을 Body entry라고 부른다.
2-4. Fault Code
SOAP은 error를 reporting 하기 위해 Fault element를 사용한다. 이 Fault element는 다음과 같은 Child element로 구성된다.
° faultcode : Software나 Provider가 사용하는 error number로 error를 구분하기 위해 사용된다. 반드시 존재해야하는 element이다.
° faultstring : error에 대한 간단한 이유나 제목을 기술하며 반드시 존재해야하는 element이다.
° faultactor : message 경로에서 누구에 의해 야기되는 error인지에 대한 정보를 나타낸다. 반드시 존재해야하는 것은 아니다.
° detail : error에 대한 상세 정보를 기술한다. 반드시 요구되는 것은 아니고 사용자가 정의한 error tag가 올 수 있다.
Example 4 ( SOAP Fault Code )
<env:Envelope xmlns:env='http://www.w3.org/2001/06/soap-envelope'
xmlns:f='http://www.w3.org/2001/06/soap-faults' >
<env:Header>
<f:Misunderstood qname='abc:Extension1'
xmlns:abc='http://example.org/2001/06/ext' />
<f:Misunderstood qname='def:Extension2'
xmlns:def='http://example.com/stuff' />
</env:Header>
<env:Body>
<env:Fault>
<faultcode>MustUnderstand</faultcode>
<faultstring>One or more mandatory headers not understood</faultstring>
</env:Fault>
</env:Body>
[정리] 소셜 플랫폼 (0) | 2010.10.05 |
---|---|
[펌] OLAP & DataWarehouse (0) | 2008.11.26 |
[펌] 자바 웹 프로그래머의 기본 (0) | 2007.11.28 |
[펌] AOP 개념 (한빛미디어 - 김대곤) (0) | 2007.11.28 |
String myObjectInJSON = myObject.toJSONString(); |
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] } |
var url = "organizePeople.php?people=" + people.toJSONString(); xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = updatePage; xmlHttp.send(null); |
var url = "organizePeople.php?people=" + escape(people.toJSONString()); request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); |
var url = "organizePeople.php?timeStamp=" + new Date().getTime(); request.open("POST", url, true); request.onreadystatechange = updatePage; request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send(people.toJSONString()); |
// This is just a code fragment from a larger PHP server-side script require_once('JSON.php'); $json = new Services_JSON(); // accept POST data and decode it $value = $json->decode($GLOBALS['HTTP_RAW_POST_DATA']); // Now work with value as raw PHP |
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { //report an error } try { JSONObject jsonObject = new JSONObject(jb.toString()); } catch (ParseException e) { // crash and burn throw new IOException("Error parsing JSON request string"); } // Work with the data using methods like... // int someInt = jsonObject.getInt("intParamName"); // String someString = jsonObject.getString("stringParamName"); // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName"); // JSONArray arr = jsonObject.getJSONArray("arrayParamName"); // etc... } |
[Servlet] Servlet에서 request의 input stream을 이용해서 읽어들일 때 (0) | 2009.02.19 |
---|---|
[펌] Getting the Requesting URL in a Servlet (0) | 2009.02.19 |
[스터디] Ajax 마스터하기, Part 10: 데이터 전송에 JSON 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 9: Google Ajax Search API 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 8: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
{ "firstName": "Brett" } |
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" } |
{ "people": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ]} |
{ "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] } |
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] } |
people.programmers[0].lastName; |
people.authors[1].genre // Value is "fantasy" people.musicians[3].lastName // Undefined. This refers to the fourth entry, and there isn't one people.programmers.[2].firstName // Value is "Elliotte" |
people.musicians[1].lastName = "Rachmaninov"; |
String newJSONtext = people.toJSONString(); |
String myObjectInJSON = myObject.toJSONString(); |
[펌] Getting the Requesting URL in a Servlet (0) | 2009.02.19 |
---|---|
[스터디] Ajax 마스터하기, Part 11: 서버 측의 JSON (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 9: Google Ajax Search API 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 8: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 7: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
function OnLoad() { // Create the Google search control var searchControl = new GSearchControl(); ... } |
function OnLoad() { // Create the Google search control var searchControl = new GSearchControl(); // These allow you to customize what appears in the search results var localSearch = new GlocalSearch(); ... // Tell Google your location to base searches around localSearch.setCenterPoint("Dallas, TX"); ... } |
function OnLoad() { // Create the Google search control var searchControl = new GSearchControl(); // These allow you to customize what appears in the search results var localSearch = new GlocalSearch(); searchControl.addSearcher(localSearch); searchControl.addSearcher(new GwebSearch()); searchControl.addSearcher(new GvideoSearch()); searchControl.addSearcher(new GblogSearch()); // Tell Google your location to base searches around localSearch.setCenterPoint("Dallas, TX"); ... } |
function OnLoad() { // Create the Google search control var searchControl = new GSearchControl(); // These allow you to customize what appears in the search results var localSearch = new GlocalSearch(); searchControl.addSearcher(localSearch); searchControl.addSearcher(new GwebSearch()); searchControl.addSearcher(new GvideoSearch()); searchControl.addSearcher(new GblogSearch()); // Tell Google your location to base searches around localSearch.setCenterPoint("Dallas, TX"); // "Draw" the control on the HTML form searchControl.draw(document.getElementById("searchcontrol")); searchControl.execute("Christmas Eve"); } |
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=[YOUR GOOGLE KEY]" type="text/javascript"> </script> |
// Create the Google search control var searchControl = new GSearchControl(); |
<div id="searchcontrol" /> |
// "Draw" the control on the HTML form searchControl.draw(document.getElementById("searchcontrol")); |
[스터디] Ajax 마스터하기, Part 11: 서버 측의 JSON (0) | 2009.02.16 |
---|---|
[스터디] Ajax 마스터하기, Part 10: 데이터 전송에 JSON 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 8: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 7: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 6: DOM-기반 웹 애플리케이션 구현하기 (0) | 2009.02.16 |
function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var response = request.responseText; // response has the XML response from the server alert(response); } } } |
<ratings><show><title>Alias</title><rating>6.5</rating></show><show><title>Lost</title><rating>14.2</rating></show><show><title>Six Degrees</title><rating>9.1</rating></show></ratings> |
function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var xmlDoc = request.responseXML; // work with xmlDoc using the DOM } } } |
function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var xmlDoc = request.responseXML; var showElements = xmlDoc.getElementsByTagName("show"); } } } |
function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var xmlDoc = request.responseXML; var showElements = xmlDoc.getElementsByTagName("show"); for (var x=0; x<showElements.length; x++) { // We know that the first child of show is title, and the second is rating var title = showElements[x].childNodes[0].value; var rating = showElements[x].childNodes[1].value; // Now do whatever you want with the show title and ratings } } } } |
[스터디] Ajax 마스터하기, Part 10: 데이터 전송에 JSON 사용하기 (0) | 2009.02.16 |
---|---|
[스터디] Ajax 마스터하기, Part 9: Google Ajax Search API 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 7: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 6: DOM-기반 웹 애플리케이션 구현하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 5: DOM 다루기 (0) | 2009.02.16 |
<name>jennifer</name> |
firstName=Larry lastName=Gullahorn street=9018 Heatherhorn Drive city=Rowlett state=Texas zipCode=75080 |
function callServer() { // Get the city and state from the Web form var firstName = document.getElementById("firstName").value; var lastName = document.getElementById("lastName").value; var street = document.getElementById("street").value; var city = document.getElementById("city").value; var state = document.getElementById("state").value; var zipCode = document.getElementById("zipCode").value; // Build the URL to connect to var url = "/scripts/saveAddress.php?firstName=" + escape(firstName) + "&lastName=" + escape(lastName) + "&street=" + escape(street) + "&city=" + escape(city) + "&state=" + escape(state) + "&zipCode=" + escape(zipCode); // Open a connection to the server xmlHttp.open("GET", url, true); // Set up a function for the server to run when it's done xmlHttp.onreadystatechange = confirmUpdate; // Send the request xmlHttp.send(null); } |
function callServer() { // Get the city and state from the Web form var firstName = document.getElementById("firstName").value; var lastName = document.getElementById("lastName").value; var street = document.getElementById("street").value; var city = document.getElementById("city").value; var state = document.getElementById("state").value; var zipCode = document.getElementById("zipCode").value; var xmlString = "<profile>" + " <firstName>" + escape(firstName) + "</firstName>" + " <lastName>" + escape(lastName) + "</lastName>" + " <street>" + escape(street) + "</street>" + " <city>" + escape(city) + "</city>" + " <state>" + escape(state) + "</state>" + " <zip-code>" + escape(zipCode) + "</zip-code>" + "</profile>"; // Build the URL to connect to var url = "/scripts/saveAddress.php"; // Open a connection to the server xmlHttp.open("POST", url, true); // Tell the server you're sending it XML xmlHttp.setRequestHeader("Content-Type", "text/xml"); // Set up a function for the server to run when it's done xmlHttp.onreadystatechange = confirmUpdate; // Send the request xmlHttp.send(xmlString); } |
xmlHttp.setRequestHeader("Content-Type", "text/xml"); |
[스터디] Ajax 마스터하기, Part 9: Google Ajax Search API 사용하기 (0) | 2009.02.16 |
---|---|
[스터디] Ajax 마스터하기, Part 8: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 6: DOM-기반 웹 애플리케이션 구현하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 5: DOM 다루기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 4: 웹 응답에 DOM 활용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 8: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
---|---|
[스터디] Ajax 마스터하기, Part 7: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 5: DOM 다루기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 4: 웹 응답에 DOM 활용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 3: Ajax의 고급 요청 및 응답 (0) | 2009.02.13 |
// These first two lines get the DOM tree for the current Web page, // and then the <html> element for that DOM tree var myDocument = document; var htmlElement = myDocument.documentElement; // What's the name of the <html> element? "html" alert("The root element of the page is " + htmlElement.nodeName); // Look for the <head> element var headElement = htmlElement.getElementsByTagName("head")[0]; if (headElement != null) { alert("We found the head element, named " + headElement.nodeName); // Print out the title of the page var titleElement = headElement.getElementsByTagName("title")[0]; if (titleElement != null) { // The text will be the first child node of the <title> element var titleText = titleElement.firstChild; // We can get the text of the text node with nodeValue alert("The page title is '" + titleText.nodeValue + "'"); } // After <head> is <body> var bodyElement = headElement.nextSibling; while (bodyElement.nodeName.toLowerCase() != "body") { bodyElement = bodyElement.nextSibling; } // We found the <body> element... // We'll do more when we know some methods on the nodes. } |
// These first two lines get the DOM tree for the current Web page, // and then the <html> element for that DOM tree var myDocument = document; var htmlElement = myDocument.documentElement; // What's the name of the <html> element? "html" alert("The root element of the page is " + htmlElement.nodeName); // Look for the <head> element var headElement = htmlElement.getElementsByTagName("head")[0]; if (headElement != null) { alert("We found the head element, named " + headElement.nodeName); // Print out the title of the page var titleElement = headElement.getElementsByTagName("title")[0]; if (titleElement != null) { // The text will be the first child node of the <title> element var titleText = titleElement.firstChild; // We can get the text of the text node with nodeValue alert("The page title is '" + titleText.nodeValue + "'"); } // After <head> is <body> var bodyElement = headElement.nextSibling; while (bodyElement.nodeName.toLowerCase() != "body") { bodyElement = bodyElement.nextSibling; } // We found the <body> element... // Remove all the top-level <img> elements in the body if (bodyElement.hasChildNodes()) { for (i=0; i<bodyElement.childNodes.length; i++) { var currentNode = bodyElement.childNodes[i]; if (currentNode.nodeName.toLowerCase() == "img") { bodyElement.removeChild(currentNode); } } } } |
<html> <head> <title>JavaScript and the DOM</title> <script language="JavaScript"> function test() { // These first two lines get the DOM tree for the current Web page, // and then the <html> element for that DOM tree var myDocument = document; var htmlElement = myDocument.documentElement; // What's the name of the <html> element? "html" alert("The root element of the page is " + htmlElement.nodeName); // Look for the <head> element var headElement = htmlElement.getElementsByTagName("head")[0]; if (headElement != null) { alert("We found the head element, named " + headElement.nodeName); // Print out the title of the page var titleElement = headElement.getElementsByTagName("title")[0]; if (titleElement != null) { // The text will be the first child node of the <title> element var titleText = titleElement.firstChild; // We can get the text of the text node with nodeValue alert("The page title is '" + titleText.nodeValue + "'"); } // After <head> is <body> var bodyElement = headElement.nextSibling; while (bodyElement.nodeName.toLowerCase() != "body") { bodyElement = bodyElement.nextSibling; } // We found the <body> element... // Remove all the top-level <img> elements in the body if (bodyElement.hasChildNodes()) { for (i=0; i<bodyElement.childNodes.length; i++) { var currentNode = bodyElement.childNodes[i]; if (currentNode.nodeName.toLowerCase() == "img") { bodyElement.removeChild(currentNode); } } } } } </script> </head> <body> <p>JavaScript and DOM are a perfect match. You can read more in <i>Head Rush Ajax</i>.</p> <img src="http://www.headfirstlabs.com/Images/hraj_cover-150.jpg" /> <input type="button" value="Test me!" onClick="test();" /> </body> </html> |
var pElement = myDocument.createElement("p"); var text = myDocument.createTextNode("Here's some text in a p element."); pElement.appendChild(text); bodyElement.appendChild(pElement); |
var imgElement = document.createElement("img"); imgElement.setAttribute("src", "http://www.headfirstlabs.com/Images/hraj_cover-150.jpg"); imgElement.setAttribute("width", "130"); imgElement.setAttribute("height", "150"); bodyElement.appendChild(imgElement); |
// Remove all the top-level <img> elements in the body if (bodyElement.hasChildNodes()) { for (i=0; i<bodyElement.childNodes.length; i++) { var currentNode = bodyElement.childNodes[i]; if (currentNode.nodeName.toLowerCase() == "img") { bodyElement.removeChild(currentNode); } } |
// Remove all the top-level <img> elements in the body var imgElements = bodyElement.getElementsByTagName("img"); for (i=0; i<imgElements.length; i++) { var imgElement = imgElements.item[i]; bodyElement.removeChild(imgElement); } |
// Remove all the top-level <img> elements in the body var imgElements = bodyElement.getElementsByTagName("img"); for (i=0; i<imgElements.length; i++) { var imgElement = imgElements.item[i]; // Print out some information about this element var msg = "Found an img element!"; var atts = imgElement.attributes; for (j=0; j<atts.length; j++) { var att = atts.item(j); msg = msg + "\n " + att.nodeName + ": '" + att.nodeValue + "'"; } alert(msg); bodyElement.removeChild(imgElement); } |
var pElements = bodyElement.getElementsByTagName("p"); for (i=0; i<pElements.length; i++) { var pElement = pElements.item(i); var text = pElement.firstChild.nodeValue; alert(text); } |
var someNode = document.documentElement.firstChild; if (someNode.nodeType == Node.ELEMENT_NODE) { alert("We've found an element node named " + someNode.nodeName); } else if (someNode.nodeType == Node.TEXT_NODE) { alert("It's a text node; the text is " + someNode.nodeValue); } else if (someNode.nodeType == Node.ATTRIBUTE_NODE) { alert("It's an attribute named " + someNode.nodeName + " with a value of '" + someNode.nodeValue + "'"); } |
[스터디] Ajax 마스터하기, Part 7: 요청과 응답에 XML 사용하기 (0) | 2009.02.16 |
---|---|
[스터디] Ajax 마스터하기, Part 6: DOM-기반 웹 애플리케이션 구현하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 4: 웹 응답에 DOM 활용하기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 3: Ajax의 고급 요청 및 응답 (0) | 2009.02.13 |
[스터디] Java개발자를 위한 XML 4 (0) | 2009.02.12 |
<html> <head> <title>Trees, trees, everywhere</title> </head> <body> <h1>Trees, trees, everywhere</h1> <p>Welcome to a <em>really</em> boring page.</p> <div> Come again soon. <img src="come-again.gif" /> </div> </body> </html> |
someDiv.style.height = "300px"; |
var domTree = document; |
[스터디] Ajax 마스터하기, Part 6: DOM-기반 웹 애플리케이션 구현하기 (0) | 2009.02.16 |
---|---|
[스터디] Ajax 마스터하기, Part 5: DOM 다루기 (0) | 2009.02.16 |
[스터디] Ajax 마스터하기, Part 3: Ajax의 고급 요청 및 응답 (0) | 2009.02.13 |
[스터디] Java개발자를 위한 XML 4 (0) | 2009.02.12 |
[스터디] Java개발자를 위한 XML 3 (0) | 2009.02.12 |