2011년 12월 18일 일요일

JSON 송신 서블릿 샘플 코드

1. JSON 코드를 servlet 프로젝트에 추가해 줍니다 : http://www.json.org/java/json.zip






2. JSON 문자열 형식으로 데이타를 요청자에게 보내는 간단한 샘플 코드입니다.


public class GuServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    static {
        try {
            Class.forName("com.ibm.db2.jcc.DB2Driver");
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            doGuJSON(request, response);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            doGuJSON(request, response);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    protected void doGuJSON (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException {

        String url = "jdbc:db2://localhost:50000/META";
        String user_id="db2admin";
        String password = "rational";

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
       
        PrintWriter out = null;

        try {
            conn = DriverManager.getConnection(url,user_id,password);
            stmt  = conn.createStatement();
            rs = stmt.executeQuery("select id,name from gu");

            JSONArray listObj = new JSONArray();
            int i=0;
            while(rs.next()) {

                int id = rs.getInt(1);
                String name = rs.getString(2);

                JSONObject itemObj = new JSONObject();
                itemObj.put("name", name.trim()); //trim trailing white spaces (fixed length string)
                itemObj.put("id", id);

                listObj.put(i, itemObj);
                i++;
            }

            try {
                response.setCharacterEncoding("UTF-8");
                out = response.getWriter();
                out.println(listObj);
            } catch ( Exception e) {
                e.printStackTrace();
            } finally {
                try { if (out!=null) out.close(); } catch (Exception e) {}
            }

        } catch ( SQLException se) {
            se.printStackTrace();
        } finally {
            try { if ( rs!=null ) rs.close(); } catch ( Exception e) {}
            try { if ( stmt!=null ) stmt.close(); } catch ( Exception e) {}
            try { if ( conn!=null ) conn.close(); } catch ( Exception e) {}
        }
    }
}





3. cURL을 이용한 헤더와 바디 정보


$ curl -v localhost:8080/MetaServlet/Gu

* About to connect() to localhost port 8080 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8080 (#0)

> GET /MetaServlet/Gu HTTP/1.1
> User-Agent: curl/7.19.6 (i686-pc-cygwin) libcurl/7.19.6 OpenSSL/0.9.8n zlib/1.2.3 libidn/1.16 libssh2/1.2
> Host: localhost:8080
> Accept: */*
>

< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Transfer-Encoding: chunked
< Date: Sat, 11 Dec 2010 04:54:10 GMT
<
[{"name":"강남구","id":1},{"name":"서초구","id":2}]

* Connection #0 to host localhost left intact
* Closing connection #0

댓글 없음:

댓글 쓰기