자바/Web2008. 6. 26. 02:20
출처 ace7min님의 블로그 | ace7min
원문 http://blog.naver.com/ace7min/28724114

클래스이름 = function(파라미터) {

    this.id = 파라미터;

    this.name = 파라미터;

}


Member = function( id, name ) {

    this.id = id;

    this.name = name;

}


var mem = new Member( 'testId', '창마이')


클래스이름.prototype.함수이름 = function( newId, newName ) {

    this.id = newId;

    this.name = newName;

}


Member.prototype.toString = function() {

    return this.id + "[" + this.name + "]";

}


이방법 이외에 Object() 를 이용한 방법으로


var mem = new Object();

mem.id = 'testId';

mem.name = '창마이';

mem.securityNo = '7700001000000';


mem.toString = function() {

    return this.name + "[" + this.id + "]";

}

 

alert( mem.toString() );


JSON 표기법


{ 이름1: 값1, 이름2: 값2, 이름3: 값3 }


var countries = {ko: '대한민국', fr: '프랑스', uk: '영국'};

var koName = countries.ko;

var frName = countries['fr'];


배열형식


[값0, 값1, 값2, 값3]


var countryCodes = ['ko', 'fr', 'uk', 'us'];

var idx0 = countryCodes[0]; //'ko'

var idx1 = countryCodes[2]; //'uk'


배열과 응용


var member = {

    name: '창마이',

    favorateColors: ['파랑', '노랑', '빨강']

};


var message = member.name + "님이 좋아하는 색상은 " +

     member.favorateColors.length + "개이고,";

message += "그중 첫 번째 색상은 " +

     member.favorateColors[0] + "입니다.";



JSON 표기법을 사용한 클래스 정의

 

클래스이름  = function( 파라미터 ) {

    ...

}


클래스이름.prototype = {

    함수명1: function( 파라미터 ) {

        ....

    },

    함수명1: function( 파라미터 ) {

        ....

    }

}


Ex)


Member = function(name, id, securityNo) {
 this.name = name;
 this.id = id;
 this.securityNo = securityNo;
}


Member.prototype = {
 setValue: function(newName, newId, newSecurityNo) {
  this.name = newName;
  this.id = newId;
  this.securityNo = newSecurityNo;
 },
 getAge: function() {
  var birthYear = parseInt(this.securityNo.substring(0, 2));
  var code = this.securityNo.substring(6,7);
  if (code == '1' || code == '2') {
   birthYear += 1900;
  } else if (code == '3' || code == '4') {
   birthYear += 2000;
  }
  var today = new Date();
  return today.getFullYear() - birthYear;
 },
 toString: function() {
  return this.name + "[" + this.id + "]";
 }
}




자바스크립트에서 패키지 정의하기


var ajax = new Object();

ajax.Request = function() {

    ...

}


ajax.Request.prototype = {

    someFunction = function() {

        ...

    },

    ...

}


위에 정의한 클래스 사용하기


var req = new ajax.Request();

req.someFunction();


중첩해서 패키지 만들기

 

var ajax = new Object();

ajax.xhr = new Object();

ajax.xhr.Request = function() {

    ...

}


// 아래와 같이 사용

var req = new ajax.xhr.Request();


빈 클래스 만들기


var ajax = {};

ajax.xhr = {};

ajax.xhr.Request = function() {

    ...

}


JSON 표기법에 대한 정보는 http://www.json.org/ 사이트에서 참고할 수 있다.

'자바 > Web' 카테고리의 다른 글

JSON  (0) 2008.06.26
JSON vs XML  (0) 2008.06.26
XML과 JSON 사이에 변환 패턴  (0) 2008.06.26
JavaScript 객체 JSON  (0) 2008.06.26
Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기  (0) 2008.06.26
Tomcat 5.X 버전에서 한글 파라메터 쓰기  (0) 2008.06.26
Posted by 양군이당
TAG java, JSON

댓글을 달아 주세요

자바/Web2008. 6. 26. 02:19

복사 http://blog.naver.com/eclips32/30020578345

Simple Java toolkit for JSON (JSON.simple)
==========================================

http://www.JSON.org/java/json_simple.zip

1.Why the Simple Java toolkit (also named as JSON.simple) for JSON?

  When I use JSON as the data exchange format between the AJAX client and JSP
  for the first time, what worry me mostly is how to encode Java strings and
  numbers correctly in the server side so the AJAX client will receive a well
  formed JSON data. When I looked into the 'JSON in Java' directory in JSON
  website,I found that wrappers to JSONObject and JSONArray can be simpler,
  due to the simplicity of JSON itself. So I wrote the JSON.simple package.

2.Is it simple,really?

  I think so. Take an example:

  import org.json.simple.JSONObject;

  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.print(obj);

  Result:
  {"nickname":null,"num":100,"balance":1000.21,"is_vip":true,"name":"foo"}

  The JSONObject.toString() will escape controls and specials correctly.

3.How to use JSON.simple in JSP?

  Take an example in JSP:

  <%@page contentType="text/html; charset=UTF-8"%>
  <%@page import="org.json.simple.JSONObject"%>
  <%
    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);
    out.print(obj);
    out.flush();
  %>

  So the AJAX client will get the responseText.

4.Some details about JSONObject?

  JSONObject inherits java.util.HashMap,so it don't have to worry about the
  mapping things between keys and values. Feel free to use the Map methods
  like get(), put(), and remove() and others. JSONObject.toString() will
  combine key value pairs to get the JSON data string. Values will be escaped
  into JSON quote string format if it's an instance of java.lang.String. Other
  type of instance like java.lang.Number,java.lang.Boolean,null,JSONObject and
  JSONArray will NOT escape, just take their java.lang.String.valueOf() result.
  null value will be the JSON 'null' in the result.

  It's still correct if you put an instance of JSONObject or JSONArray into an
  instance of JSONObject or JSONArray. Take the example about:

  JSONObject obj2=new JSONObject();
  obj2.put("phone","123456");
  obj2.put("zip","7890");
  obj.put("contact",obj2);
  System.out.print(obj);

  Result:
  {"nickname":null,"num":100,"contact":{"phone":"123456","zip":"7890"},"balance":1000.21,"is_vip":true,"name":"foo"}

  The method JSONObject.escape() is used to escape Java string into JSON quote
  string. Controls and specials will be escaped correctly into \b,\f,\r,\n,\t,
  \",\\,\/,\uhhhh.

5.Some detail about JSONArray?

  org.json.simple.JSONArray inherits java.util.ArrayList. Feel free to use the
  List methods like get(),add(),remove(),iterator() and so on. The rules of
  JSONArray.toString() is similar to JSONObject.toString(). Here's the example:

  import org.json.simple.JSONArray;

  JSONArray array=new JSONArray();
  array.add("hello");
  array.add(new Integer(123));
  array.add(new Boolean(false));
  array.add(null);
  array.add(new Double(123.45));
  array.add(obj2);//see above
  System.out.print(array);

  Result:
  ["hello",123,false,null,123.45,{"phone":"123456","zip":"7890"}]

6.What is JSONValue for?

  org.json.simple.JSONValue is use to parse JSON data into Java Object.
  In JSON, the topmost entity is JSON value, not the JSON object. But
  it's not necessary to wrap JSON string,boolean,number and null again,
  for the Java has already had the according classes: java.lang.String,
  java.lang.Boolean,java.lang.Number and null. The mapping is:

  JSON          Java
  ------------------------------------------------
  string      <=>   java.lang.String
  number      <=>   java.lang.Number
  true|false  <=>   java.lang.Boolean
  null        <=>   null
  array       <=>   org.json.simple.JSONArray
  object      <=>       org.json.simple.JSONObject
  ------------------------------------------------

  JSONValue has only one kind of method, JSONValue.parse(), which receives
  a java.io.Reader or java.lang.String. Return type of JSONValue.parse()
  is according to the mapping above. If the input is incorrect in syntax or
  there's exceptions during the parsing, I choose to return null, ignoring
  the exception: I have no idea if it's a serious implementaion, but I think
  it's convenient to the user.

  Here's the example:

  String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
  Object obj=JSONValue.parse(s);
  JSONArray array=(JSONArray)obj;
  System.out.println(array.get(1));
  JSONObject obj2=(JSONObject)array.get(1);
  System.out.println(obj2.get("1"));

  Result:
  {"1":{"2":{"3":{"4":[5,{"6":7}]}}}}
  {"2":{"3":{"4":[5,{"6":7}]}}}

7.About the author.

  I'm a Java EE developer on Linux.
  I'm working on web systems and information retrieval systems.
  I also develop 3D games and Flash games.

  You can contact me through:
  Fang Yidong<fangyidong@yahoo.com.cn>
  Fang Yidong<fangyidng@gmail.com>

  http://www.JSON.org/java/json_simple.zip

'자바 > Web' 카테고리의 다른 글

JSON  (0) 2008.06.26
JSON vs XML  (0) 2008.06.26
XML과 JSON 사이에 변환 패턴  (0) 2008.06.26
JavaScript 객체 JSON  (0) 2008.06.26
Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기  (0) 2008.06.26
Tomcat 5.X 버전에서 한글 파라메터 쓰기  (0) 2008.06.26
Posted by 양군이당
TAG java, JSON

댓글을 달아 주세요

자바/Web2008. 6. 26. 02:18

tomcat 5.x 버전에서 웹브라우저로 부터 날라온 Get/Post 로 전달되는 한글이 ISO8859-1로 넘어오는 경우가 있어

한글이 깨지는 경우가 있습니다. 아래와 같이 Get / Post로 넘오는 한글 처리를 하시면 됩니다.


1. Get 방식으로 넘어오는 파라미터

   server.xml

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

   <Connector
               port="8080"               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               debug="0" connectionTimeout="20000"
               disableUploadTimeout="true" useBodyEncodingForURI="true" URIEncoding="KSC5601"/>


2. Post 방식으로 넘오는 파라미터


2-1. 톰캣이 설치된 디렉토리에서

<TOMCAT_HOME>/webapps/jsp-examples/WEB-INF/classes/filters/SetCharacterEncodingFilter.class 파일을 복사해서

<TOMCAT_HOME>/common/classes/filters/ 밑으로 복사함.


2-2.

 web.xml

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

 <filter>
      <filter-name>Set Character Encoding</filter-name>
      <filter-class>filters.SetCharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>euc-kr</param-value>
      </init-param>
    </filter>

    <filter-mapping>
      <filter-name>Set Character Encoding</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

'자바 > Web' 카테고리의 다른 글

JSON  (0) 2008.06.26
JSON vs XML  (0) 2008.06.26
XML과 JSON 사이에 변환 패턴  (0) 2008.06.26
JavaScript 객체 JSON  (0) 2008.06.26
Java 객체를 이용해서 JSON객체를 위한 텍스트 생성하기  (0) 2008.06.26
Tomcat 5.X 버전에서 한글 파라메터 쓰기  (0) 2008.06.26
Posted by 양군이당

댓글을 달아 주세요