반응형


今回は昨年末(2011/12/20)にリリースされたjqGrid4.3.1の新機能を実際に使ってみましょう。
#というのも、実際使おうとしたらVersion.4台でサンプルプログラム載せている
 ところがほとんどなかったので私にとっての備忘録です。
 今回は最終成果物(DLすればすぐ動かせるもの)もこのページに掲載します。

今回試すのは以下の機能です。

  • 行/列のセルマー(ColSpanとかRowSpanとかいうアレ)
  • スクロール時のセル固定(Excelで見かけるアレ)

ん〜、にしてもどんどんExcelと同じようなことができるようになってきてますね。
便利になるのはいいとしても、パフォーマンス大丈夫なのかな?
大量データを描画する際に間違いなくパフォーマンス問題を起こしそうな。。。

まぁ、今回はそこには触れずに上記新機能を実装します。

完成イメージ

今回は先に結論と成果物を共有しちゃいます。
jgGrid_sample.zip 直
これをDLしてsample.htmlを開くと、こんな画面が開けます。

スクロールすると、こんな感じにセル固定もします。

ちなみに、これら、デモサイトの作りと異なる作りをしています。
つまり、、、デモサイトの情報はこれから紹介する問題に対応していないんです!!!
古い!!!
早期改修を期待します。

内容解説

Group Header

まずはセルマージのアレを実現します。
これはjQueryメソッド内で以下を呼んであげれば実現完了です。

$("#sample1").jqGrid('setGroupHeaders', {
	useColSpanStyle: true,
	groupHeaders:[
		{startColumnName: 'age', numberOfColumns: 3, titleText: '<em>Details</em>'},
		{startColumnName: 'note1', numberOfColumns: 3, titleText: '<em>Notes</em>'}
	]
});

「useColSpanStyle: true」という指定で縦セル結合の設定。
groupHeadersで横セルのマージを行っています。
なんと簡単なことか!

Frozen Cols

次にセル固定についてです。jqGrid4.3.0から、何と1つの設定とメソッド呼び出しで
機能として実現されます。
#まずはデモサイト通りの実装です。
colModelの設定で以下を設定します。

frozen:true
/** 例:{name:'name',index:'name',width:150,align:'center',classes:'name_class',frozen:true}, */

次に、jQueryの最後で以下のメソッドを呼び出します。

$("#sample1").jqGrid('setFrozenColumns');
/** #sample1はサンプルのテーブルID */

これだけで実装完了です。これも簡単!

ハマりどころ

[Frozen Cols]そもそもテーブル操作しないとセル固定が中途半端に実現される

上記のとおりjQuery内で最後にメソッド呼び出しをすると、、、こうなります。
Windows 7 64-bit環境)

忌々しき事態です、まったく使い物になりません。

ちなみにテーブル操作を行って一度でもテーブルをリフレッシュさせると問題は起こりません。。。

色々調べましたが、全く同じ症状の人がいましたね。掲示板にて外人さんが質問しています。
英語のフォーラムなのであまり読んでませんが要約するとこんな感じでしょうか。

ユーザ
そのままsetFrozenColumnsメソッド使ってもうまく固定されないから
リロードする仕組み入れてるんだけど、リロードってパフォーマンス落ちるよね?
何とかならないの?
製作者
こっちじゃ確認できないよ、環境悪いんでない?

・・・(こんなやり取りを何度か繰り返す。)

製作者
確かに問題がありそうだね、こちらでも確認したよ。
ユーザ
現状はこうやって解消してますわぁ。

gridComplete: function() {
mygrid.jqGrid('setFrozenColumns');
}

なるほど、colModelの属性としてgridCompleteに設定するのね。
これならgrid完成後にセル固定処理が走るから問題なさそうですね。
これで一つ解決

[Frozen Cols]セル固定状態のフィルタリングで処理がストップする

上記gridCompleteに記述することにすると、次にこの問題にあたります。
セル固定やマージは一度だけ行えばいいのに、gridComplete内に記述すると、
フィルタなどの再描画の際にもさらにマージしようとするから生じるのかな?

いずれにしても、処理がストップしてフィルタリングができません。
一応現在は下記のようにして回避しています。

var isLoaded = false;

・・・

gridComplete: function(){
  if (!isLoaded == true){
    $("#sample1").jqGrid('setGroupHeaders', {
      useColSpanStyle: true,
      groupHeaders:[
        {startColumnName: 'age', numberOfColumns: 3, titleText: '<em>Details</em>'},
        {startColumnName: 'note1', numberOfColumns: 3, titleText: '<em>Notes</em>'}
      ]
    });
    $("#sample1").jqGrid('setFrozenColumns');
    isLoaded = true;
  }
},

一度でもセルマージなどの読み込みを行ったら、その後は行わない、という実装です。
一応今のところこれで問題が発生しなくなっています。
(他の機能との連携を全て試しているわけではないのでどうなるかわかりませんが。。。)

いずれにしても、本体の改修でこの辺の問題がFixされることを期待しています。
jqGridは最近とても短い期間でBugFix版を出しているので、
(4.3.0から4.3.1へのUpdateも10日足らず)すぐに修正されることを願っています。

では、今回はこの辺で。


Posted by 1010
반응형
http://stackoverflow.com/q/12606945/315935
jqgridDnD.html
Posted by 1010
02.Oracle/DataBase2014. 4. 11. 16:40
반응형

I am connecting from Oracle to MS SQL Server through an ODBC connection using Oracle SQL Developer. (How)

I want to query the schema of the MS SQL database using the data dictionary mapping of the Oracle Database Gateway for ODBC.

This works well:

select * from all_tables@katimssql;

But this doesn't:

create table alltables_mssql as 
select * from all_tables@katimssql;

Output:

Error report:
SQL Error: ORA-00604: error occurred at recursive SQL level 1
ORA-02047: cannot join the distributed transaction in progress
ORA-06512: at "SYS.HS$_DDTF_SQLTABLES", line 58
ORA-06512: at line 1

Does anyone know the solution of this?
Thanks in advance,
Kati


 

Details:

Oracle Database 11g Express Edition Release 11.2.0.2.0
Microsoft SQL Server 2008 (SP2) - 10.0.4000.0 (X64)
ODBC Driver: SQL Server Native Client 11.0 (32 bit)

initkatimssql.ora:

HS_FDS_CONNECT_INFO=katimssql
HS_FDS_TRACE_LEVEL = ON
HS_TRANSACTION_MODEL = READ_ONLY_AUTOCOMMIT

I tried these, none of them worked, the error message is the same.

HS_FDS_TRACE_LEVEL = off
HS_TRANSACTION_MODEL = SINGLE_SITE
HS_TRANSACTION_MODEL = READ_ONLY_AUTOCOMMIT
HS_TRANSACTION_MODEL = READ_ONLY
Posted by 1010
02.Oracle/DataBase2014. 4. 11. 16:32
반응형

ora-02047: cannot join the distributed transaction in progress
Cause: Either a transaction is in progress against a remote database that does not fully support two phase commit, and an update is attempted on another database, or updates are pending and and an attempt is made to update a different database that does not fully support two phase commit.
Action: complete the current transaction and then resubmit the update request

출처 : http://dpldpl.tistory.com/7

ORA-02047 동작중의 분산 트랜잭션(transaction)는 결합할 수 없습니다.

 

원인은 이기종 데이터베이스 시스템 간의 인터페이스 작업 시(ex. oracle to mssql)

데이터 처리를 함에 있어서(ex. Insert, Update, Delete)

커밋을 하지 않았기 때문에 발생하는 오류이다.

 

단일 시스템에서는 커밋을 하지 않아도 무방하지만

이기종 시스템간의 데이터 처리시에는 DML 구문뒤에 꼭 커밋을 해주어야 한다.

 

by. 덕평물류 전산정보팀(DPL Dream Partner in Logitics)

Posted by 1010
98..Etc2014. 4. 7. 13:43
반응형

http://update.zeroturnaround.com/update-site-archive/

Posted by 1010
00.scala2014. 4. 2. 00:58
반응형

http://www.scala-lang.org/api/current/#package

http://www.slideshare.net/choijeongyeol/scala-for-play

scala cheatsheets

http://docs.scala-lang.org/cheatsheets/


스칼라를 배울 수 있는 사이트

스칼라 서적(영문)

  • Programming in Scala : 마틴 오더스키가 참여한 스칼라 서적. 강추!!, Scala 2.8 기준.
  • Programming Scala : 오렐리에서 나옴. 읽어본 사람 없어서 내용은 잘 모름.
  • Programming Scala : Pragmatic에서 나온 스칼라 서적. 읽어볼만은 하지만 빠진 내용이 많아서 많이 추천하지는 않음.
  • Scala in Depth : 매닝에서 나온 서적. 읽어본 사람이 없어서 내용은 잘 모름.

그외 참고 자료

발표자료

슬라이드


Posted by 1010
98..Etc2014. 4. 2. 00:35
반응형

http://hanho9.cafe24.com 나오는 2번에 스크립트 경로를 아래에 스크립트에 적용후 


javascript:(function(e){e.setAttribute("src","http://debug-software.intel.com/target/target-script-min.js#anonymous");document.getElementsByTagName("head")[0].appendChild(e);})(document.createElement("script"));void(0);


실제 디버깅할 곳에 삽입

------------------------------------------



http://debug-software.intel.com/

http://debug.phonegap.com/



Tutorial-UsingDebugMobi.pdf




 

 

 

 

 

 

 

 

 

 

 

 

Intel® HTML5 Development Environment 

Tutorial – Using App Debugger 

v1.05 : 03.06.2013 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

Legal Information 

INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, 

EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS 

GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR 

SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR 

IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR 

WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR 

INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. 

A "Mission Critical Application" is any application in which failure of the Intel Product could result, 

directly or indirectly, in personal injury or death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS 

FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS 

SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES 

OF EACH, HARMLESS AGAINST ALL CLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE 

ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, 

PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, 

WHETHER OR NOT INTEL OR ITS SUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR 

WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS. 

Intel may make changes to specifications and product descriptions at any time, without notice. 

Designers must not rely on the absence or characteristics of any features or instructions marked 

"reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility 

whatsoever for conflicts or incompatibilities arising from future changes to them. The information here 

is subject to change without notice. Do not finalize a design with this information. 

The products described in this document may contain design defects or errors known as errata which 

may cause the product to deviate from published specifications. Current characterized errata are 

available on request. Contact your local Intel sales office or your distributor to obtain the latest 

specifications and before placing your product order. Copies of documents which have an order number 

and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-

4725, or go to: http://www.intel.com/design/literature.htm 

Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries. 

*Other names and brands may be claimed as the property of others. 

Microsoft, Windows, and the Windows logo are trademarks, or registered trademarks of Microsoft 

Corporation in the United States and/or other countries. 

Copyright © 2013, Intel Corporation. All rights reserved. Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

1.0 Purpose 

The purpose of this documentation is to demonstrate how to use the App Debugger tool to remotely 

debug HTML5 code over the Internet. The App Debugger tool is based on an open source tool called 

“Web Inspector Remote”* (WEINRE) that provides remote Web debugging for mobile devices. 

However, App Debugger is a configuration-free hosted version of that software that anyone can use for 

free across the Internet. 

2.0 How to Use App Debugger 

To use the App Debugger tool, browse to http://debug-software.intel.com in your Google* Chrome web 

browser. 

 

A unique identifier is generated automatically for you. If you were returning to App Debugger after 

debugging previously, you might instead enter your current unique ID. 

Once you have determined the unique id that will be used for the current debugging session, make sure 

that your HTML5 project has the listed script included in it. It could go anywhere, but for consistency it 

is typically placed just after the closing body tag in your HTML document. 

 

<html><body></body> 

<script src="http://debug.html5m.com/target/target-script-min.js#ac4928aa-418b-d4c8-

5839-1a6b278c0146"></script></html> 

 

 

Next, click the link to start App Debugger on your Chrome* browser. That will bring up a remote page 

that looks something like this: Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

 

There are no targets yet. Once the JavaScript* library is loaded into an HTML5 page, that page will show 

up as one of the available targets in just a few seconds. 

 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

Once the target has fetched the WEINRE JavaScript from the server, executed it, and made a good 

contact back to the App Debugger server, the Target will turn green. 

 

If you have several Targets, select the one you want to view. You should then be able to use Chrome’s 

debugging tools similar to how one would use those tools to debug local JavaScript. Switch to the 

Console view within Chrome to see the console.log messages coming from the remote JavaScript. 

 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

3.0 Finding Bugs 

The App Debugger tool can help you to find bugs in your remote JavaScript/HTML code in several ways. 

3.1 Capture console.log calls 

Any JavaScript messages logged to the console using console.log will make their way to the App 

Debugger console window. That can save you the heartache of having to write messages to the screen 

as a debug log or putting up a load of annoying alert boxes. In the example below, the HTML5 program 

running on the right is transmitting its console.log calls to the App Debugger window on the left. 

 

 

3.2 Adjust CSS on the Fly 

The App Debugger window also gives you the ability to change CSS elements and immediately see the 

results on the client side. In the example below, the CSS for the title page is adjusted and the result 

plays out immediately on the client window to the right. Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

 

3.3 Adjust JavaScript on the fly 

The App Debugger window gives you the ability to write JavaScript and have it executed immediately on 

the client side. In the example below, the canvas tag which includes the kung-fu fighter is set to be 

transparent, making him appear ghostly in the right window. 

 Tutorial – Using App Debugger v1.05 : 03.06.2013 

 

 

3.4 Inspect HTML 

The App Debugger tool allows you to inspect HTML elements. Highlighting the HTML code in the App 

Debugger window will highlight the element on the client side. In the example below, the HTML 

element for the title is selected for inspection which highlights it in the right-hand execution window. 

 

4.0 More Information 

For more information, check out a quick demonstration video here: 

http://youtu.be/k0t2oZKpmA8 

The App Debugger service is also available as a Chrome extension here: 

http://tinyurl.com/debugmobi-chrome 

For a more detailed explanation of how WEINRE works link here: 

http://muellerware.org/papers/weinre/manual.html 

 

 

Posted by 1010
98..Etc2014. 4. 1. 18:20
반응형

Weinre(와이너 or 와이너리)란?

  server는 java기반의 http서버 (jetty)

  client는  webkit계열의 브라우저 (일반적으로 서버와 같은 pc에서 실행)

  target은 webkit계열의 브라우저 (일반적으로 태블릿, 폰의 브라우저)

  위와같이 구성된 디버깅 라이브러리이고 태블릿과같이 javascript디버깅을 할수없는 기기에서 

  target(태블릿) => server(pc)로 http통신을 하여 client(pc의 브라우저)로 원격 디버깅을 할 수 있습니다.

  참고로 2.0버전부터는 Weinre의 서버가 node.js로 변경 되었습니다만

  여기에서는 java기반 서버의 마지막 버전인 1.6.1로 설명 하겠습니다.


라이센스 : apache license 2.0


사이트

  공식 : http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

  1.6.1다운로드 : http://people.apache.org/~pmuellr/weinre/builds/1.x/1.6.1/weinre-jar-1.6.1.zip


1. weinre.jar파일 실행해서 서버시작 하기

01./* 옵션 */
02.-help (or -? or -h) => 도움말
03.-httpPort [포트번호] => 포트번호 (default 8080)
04.-boundHost [hostname | ip address | -all-] => 서버 ip주소 또는 호스트이름
05.-verbose [true false] => 자세한 내용 출력 (default false)
06.-readTimeout [seconds] => weinre서버가 log내용을 읽어들이는 시간 (default 5초)
07. 
08./* 실행 */
09.java -jar weinre.jar --httpPort 포트번호 --boundHost IP주소 --verbose true



2. weinre client 띄우기

http://weinre서버주소:포트번호/client


3. 개발한 html페이지에 weinre script 삽입후 리로드

1.<script type="text/javascript" src="http://서버주소:포트번호/target/target-script-min.js"></script>


4. weinre client에서 target이 접속되었는지 확인



5. 위와같이 접속이 확인되었으면 디버깅이 가능한 상태입니다.

4번 그림에서의 화면은 webkit의 디버깅창이 아닌 webkit의 디버깅창을 

따라서 비슷하게 만든 weinre의 화면입니다.


출처 : http://kdarkdev.tistory.com/248

Posted by 1010
반응형

JSONP

From Wikipedia, the free encyclopedia

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of thesame-origin policy.

Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results. The JSONP parameters passed as arguments to a script are defined by the server.

Reason for JSONP[edit]

Under the same-origin policy (SOP)JavaScript code loaded from one domain is not allowed to fetch data from another domain. However, this restriction does not apply to the <script> tag, which can specify a URL of JavaScript code to load from a remote server in a src attribute. This was used to work around the SOP limitations by pointing the src to aweb service returning dynamically generated JavaScript code (JSONP), instead of JSON data. Because the code is loaded by the <script> tag, it can be normally executed and return the desired data block, thus bypassing SOP.

Execution of raw JavaScript from a third party raised security concerns and creates a possible vulnerability.[1] Cross-origin resource sharing (CORS) is a more recent method of getting data from a server in a different domain, which addresses some of those criticisms. All modern browsers now support CORS making it a viable cross-browser alternative.

How it works[edit]

To see how this technique works, first consider a URL request that returns JSON data. A JavaScript program might request this URL via XMLHttpRequest, for example. Suppose the user ID of Foo is 1234. A browser requesting the URLhttp://server2.example.com/Users/1234, passing the ID of 1234, would receive something like:

{
    "Name": "Foo",
    "Id": 1234,
    "Rank": 7
}

This JSON data could be dynamically generated, according to the query parameters passed in the URL.

Here, an HTML <script> element specifies for its src attribute a URL that returns JSON:

<script type="application/javascript"
        src="http://server2.example.com/Users/1234">
</script>

The browser will, in order, download the script file, evaluate its contents, interpret the raw JSON data as a block, and throw a syntax error. Even if the data were interpreted as a JavaScript object literal, it could not be accessed by JavaScript running in the browser, since without a variable assignment object literals are inaccessible.

In the JSONP usage pattern, the URL request pointed to by the <script>'s src attribute returns JSON data, with a function call wrapped around it. In this way, a function that's already defined in the JavaScript environment can manipulate the JSON data. A JSONP payload might look like this:

functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});

The function call is the "P" of JSONP—the "padding" around the pure JSON, or according to some[2] the "prefix". By convention, the browser provides the name of the callback function as a named query parameter value, typically using the name jsonp or callback as the named query parameter field name, in its request to the server, e.g.,

<script type="application/javascript"
        src="http://server2.example.com/Users/1234?jsonp=parseResponse">
</script>

In this example, the received payload would be:

parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});

Padding[edit]

While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser, it may also be a variable assignment, an if statement, or any other JavaScript statement. The response to a JSONP request is not JSON and is not parsed as JSON; the returned payload can be any arbitrary JavaScript expression, and it does not need to include any JSON at all. But conventionally, it is a JavaScript fragment that invokes a function call on some JSON-formatted data.

Said differently, the typical use of JSONP provides cross-domain access to an existing JSON API, by wrapping a JSON payload in a function call.

Script element injection[edit]

JSONP makes sense only when used with a script element. For each new JSONP request, the browser must add a new <script> element, or reuse an existing one. The former option—adding a new script element—is done via dynamic DOM manipulation, and is known as script element injection. The <script> element is injected into the HTML DOM, with the URL of the desired JSONP endpoint set as the "src" attribute. This dynamic script element injection is usually done by a JavaScript helper library. jQuery and other frameworks have JSONP helper functions; there are also standalone options.[3][4][5]

The dynamically injected script element for a JSONP call looks like this:

<script type="application/javascript"
        src="http://server2.example.com/Users/1234?jsonp=parseResponse">
</script>

After the element is injected, the browser evaluates the element, and performs an HTTP GET on the src URL, retrieving the content. Then the browser evaluates the return payload as JavaScript. This is typically a function invocation.

In that way, the use of JSONP can be said to allow browser pages to work around the same-origin policy via script element injection.

The script runs within the scope of the including page and, as such, is still subject to cross-domain restrictions relative to the including page's domain. This means that one cannot, for example, load a library hosted on another site via JSONP and then make XMLHttpRequest requests to that site (unless CORS is supported) although one could use such a library to make XMLHttpRequests to one's own site.

Cross-domain requests using a proxy server[edit]

The JavaScript same-origin policy normally prevents browsers from sending AJAX requests to a different domain and receiving a response (newer browsers that support CORS can relax this constraint). A cooperating proxy server, however, does not have such restrictions and can relay a browser request to a server in a separate domain, store the result, and then return that JSON payload when the browser makes a second request. The server would be instructed within the first request to store the output (POST returning JSON payload) temporarily into a local store (for example memcached or within a session variable), and a second request from the browser then would fetch the cached response to the initial query.[6] The xd_arbiter.php used by Facebook's JS SDK is a popular example of this cooperating server technique.[7]

Security concerns[edit]

Including script tags from remote servers allows the remote servers to inject any content into a website. If the remote servers have vulnerabilities that allow JavaScript injection, the page served from the original server is exposed to an increased risk. If an attacker can inject any JavaScript into the original web page, then that code can retrieve additional JavaScript from any domain. The Content Security Policy HTTP Header lets web sites tell web browsers which domains scripts should be included from.

An effort is underway to define a safer strict subset definition for JSON-P[8] that browsers would be able to enforce on script requests with a specific MIME type such as "application/json-p". If the response didn't parse as strict JSON-P, the browser could throw an error or just ignore the entire response. For the moment however the correct MIME type is "application/javascript" for JSONP.[9]

Cross-site request forgery[edit]

Native deployments of JSONP are subject to cross-site request forgery (CSRF or XSRF) attacks.[10] Because the HTML<script> tag does not respect the same-origin policy in web browser implementations, a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page, possibly divulging passwords or other sensitive data if the user is currently logged into the other site.

This is problematic only if the JSON-encoded data contains sensitive information which should not be disclosed to a third party, and the server depends on the browser's same-origin policy to block the delivery of the data in the case of an improper request. There is no problem if the server determines the propriety of the request itself, only putting the data on the wire if the request is proper. Cookies are not by themselves adequate for determining if a request was authorized. Exclusive use of cookies is subject to cross-site request forgery.

History[edit]

In July 2005 George Jempty suggested an optional variable assignment be prepended to JSON.[11][12] The original proposal for JSONP, where the padding is a callback function, appears to have been made by Bob Ippolito in December 2005[13] and is now used by many Web 2.0 applications such as Dojo ToolkitGoogle Web Toolkit and Web services.

An unnamed process equivalent to JSONP has been used by PostX envelopes (now owned by Cisco Systems and deployed on Cisco's Email Security Appliance and Cisco Registered Envelope Service (CRES)) since May 2002.

See also[edit]

References[edit]

External links[edit]


Posted by 1010
05.JSP2014. 4. 1. 16:53
반응형
출처 : http://warmz.tistory.com/739

Ajax 로 다른 도메인에 있는 url 을 호출해 데이터나 HTML을 가져오는건 보안상 안된다고 한다. 되면 참 좋을텐데;;


뭐 아무튼 이걸 해결하기 위한 방법으로 JSONP 라는 형식으로 호출하던가 아니면 Proxy Servlet 을 하나 맹글어 그 서블릿을 거쳐 HttpClient 로 가져오는 방법, 훌래쉬를 이용하는 방법이 있다고 한다.!

그중에서 이번엔 JSONP 형식으로 호출하는 방법을 연구해 보겠다.

JSONP 형식이란 뭐 별건 아닌것 같고 기존에 서버에서 리턴해 주던 

{"key1" : "value1",  "key2" : "value2"} 요런 json 문자열을 

callback({"key1" : "value1",  "key2" : "value2"}); 요런식으로 임의의 함수를 호출해 주는 형식의 문자열로 리턴해 주는것을 말하는것 같다.

즉, jsonp 로 ajax 호출을 하기 위해선 아무 url 이나 안되고  callback({"key1" : "value1",  "key2" : "value2"});  요런식으로 함수안에 json 문자열이 들어간 형식으로 서버에서 리턴을 해줘야 가능하다.

각설하고 jQuery를 활용해 맹글어 보자.



jQuery에서 jsonp 호출하는 방법#1
1
2
3
    //d.key;
});

jQuery에서 jsonp 호출하는 방법#2
1
2
3
4
5
6
7
8
$.ajax({
    dataType : "jsonp",
    jsonp : "callback",
    success : function(d){
        // d.key;
    }
});

방법#1 이나 방법#2는 작동하는게 동일하다. 취향에 맞게 쓰임새에 맞게 쓰면된다. 개인적으로 방법#2 를 여러가지 원하는 ajax 호출 옵션을 줄수 있어서 더 좋아한다.

살짝 설명해 보면 방법#2 에서 쓴 ajax 옵션중 jsonp는 데이터를 넘겨줄 서버에서 받는 callback 함수명 파라메터이다. 서버에 따라 원하는 callback 함수명을 적어줘야 한다. 방법#1을 보면 대충 이해할 수 있다.

jsonp 옵션에다 적어준 함수명은 ajax 호출 url 뒤에다 방법#1에서 처럼 파라메터 형식으로 자동 추가된다.



전체소스코드 client.html
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
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Jsonp test with jquery</title>
     
    <script type="text/javascript" src="/resource/js/jquery-1.6.2.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#testBtn").click(function(){
                $.getJSON("http://127.0.0.1:8080/server/data.jsp?callback=?", function(d){
                    $.each(d, function(k, v){
                        $("#getjson").append("<div>" + k + " : " + v + "</div>");
                    });
                    $("#getjson").show();
                });
                             
                $.ajax({
                    url : "http://127.0.0.1:8080/server/data.jsp",
                    dataType : "jsonp",
                    jsonp : "callback",
                    success : function(d){
                        $.each(d, function(k, v){
                            $("#ajax").append("<div>" + k + " : " + v + "</div>");
                        });
                        $("#ajax").show();
                    }
                });
            });
        });
    </script>
     
    <style>
        div{margin-bottom:10px;padding:2px;}
        #getjson{border:1px solid red;display:none;}
        #ajax{border:1px solid blue;display:none;}
    </style>
</head>
 
<body>
    <button id="testBtn">테스트!</button>
    <div id="getjson"></div>
    <div id="ajax"></div>
</body>
</html>



다음으로 간단한 테스트를 위해 초간단 심플 데이터 제공용 jsp 파일을 하나 맹글어 보자. JSON 변환용 라이브러리로 Jackson JSON Processor를 사용했다.
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
<%@ page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
 
<%@ page import="java.io.StringWriter"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
 
<%@ page import="org.codehaus.jackson.map.ObjectMapper"%>
 
<%
    Map<String, String> dummyData = new HashMap<String, String>();
    dummyData.put("value1", "값1");
    dummyData.put("value2", "값2");
    dummyData.put("value3", "값3");
    dummyData.put("value4", "값4");
     
    StringWriter sw = new StringWriter();
     
    // Jackson JSON Mapper 를 사용해서 Map 을 JSON 문자열로 변환
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, dummyData);
     
    request.setAttribute("sw", sw);
%>
 
<%-- ajax 에서 넘겨준 callback 함수 파라메터 가져오기 --%>
${param.callback}(${sw});
ajax로 호출한 url 경로에 맞게금 /server/data.jsp 로 저장하고 http://localhost:8080/client.html 로 접속해보자. 왜냐하면 localhost 랑 127.0.0.1 은 도메인이 다르니깐.  

음 잘 작동된다~~ 초간단 심플 예제이기 때문에 간단하게 JSP로 구현했는데 다음번에 쫌더 실제적으로 프로젝트에 써먹을수 있도록 Spring으로 예제를 하나 맹글어 봐야긋다~

[샘플소스]CrossDomain1.war


Posted by 1010