Ajax JSON for Java Web


Inti dari article ini adalah menggunakan JSON untuk mempermudah implementasi AJAX pada Java.

Seandainya kita membuat sebuah sistem pencharian buku. Seperti biasa kita terlebih dahulu mengimplemenasikan model, controller, dan view.

Model yang akan diimplementasikan: Book, BookAddress.


Model Book

 co.id.hanoman.ajaxjson;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import java.util.ArrayList;
import java.util.List;

public class Book {

    private int bookId;
    private String title;
    private String isbn;
    private String author;
    private List<BookAddress> bookAddress;

    public Book(int bookId, String title, String isbn, String author) {
        this.bookId = bookId;
        this.title = title;
        this.isbn = isbn;
        this.author = author;
        bookAddress = new ArrayList<BookAddress>();
        bookAddress.add(new BookAddress(bookId + " - address1" + title, bookId + " - address1"));
        bookAddress.add(new BookAddress(bookId + " - address2" + title, bookId + " - address2"));
        bookAddress.add(new BookAddress(bookId + " - address3" + title, bookId + " - address3"));
        bookAddress.add(new BookAddress(bookId + " - address4" + title, bookId + " - address4"));
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public int getBookId() {
        return this.bookId;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return this.title;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getIsbn() {
        return this.isbn;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getAuthor() {
        return this.author;
    }

    public List<BookAddress> getBookAddress() {
        return bookAddress;
    }

    public void setBookAddress(List<BookAddress> bookAddress) {
        this.bookAddress = bookAddress;
    }

    public String toJSONString() {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias(Book.class.getSimpleName(), Book.class);
        xstream.alias(BookAddress.class.getSimpleName(), BookAddress.class);
        return xstream.toXML(this);
    }
}

Model BookAddress

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package co.id.hanoman.ajaxjson;

/**
 *
 * @author Administrator
 */
public class BookAddress {
    private String address1;
    private String address2;

    public BookAddress() {
    }

    public BookAddress(String address1, String address2) {
        this.address1 = address1;
        this.address2 = address2;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

}

Di view kita memasukkan id untuk mendapatkan informasi buku tersebut. lalu data dikirimkan ke controller menggunakan xmlhttprequest. nah .., apa yang terjadi ? saat controler mendapatkan informasi buku, sudah pasti informasi buku tersebut tersimpan pada object Book. Untuk mengembalikan xmlhttpresponse, object book tersebut harus terlebih dahulu kita parsing menjadi xml data.

contohnya:

<Book>
  <bookId>1</bookId>
  <title>Crime a&amp;nd &apos;Punishment</title>
  <isbn>&amp;&apos;&lt;0679734503</isbn>
  <author>Fyodor Dostoevsky</author>
  <bookAddress>
    <BookAddress>
      <address1>1 - address1</address1>
      <address2>1 - address1</address2>
    </BookAddress>
    <BookAddress>
      <address1>1 - address2</address1>
      <address2>1 - address2</address2>
    </BookAddress>
    <BookAddress>
      <address1>1 - address3</address1>
      <address2>1 - address3</address2>
    </BookAddress>
    <BookAddress>
      <address1>1 - address4</address1>
      <address2>1 - address4</address2>
    </BookAddress>
  </bookAddress>
</Book>

Untuk mempopulate data xmlhattp response ini developer harus memparsing satu-persatu xml response tersebut menggunakan DOM. Menggunakan

getElementByID
getElementByTagName

Ribet sekali bukan ????

Bagaimana jika menggunakan object biasa ?

book.title
book.author

bakalan lebih sederhana dan mudah. Untuk mengimplementasikan hal seperti itu kita terlebih dahulu mengubah POJO menjadi JSON.

Apa itu JSON ???? mari kita kupas secara seksama dalam tempo sesingkat singkatnya.

What is JSON?

JSON (or JavaScript Object Notation) is a highly portable data interchange format. While its structure is recognized natively by Javascript (as it is Javascript), its formatting conventions are easily recognized by other C-like languages. JSON.org has an excellent description:

JSON is built on two structures:

  1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangable with programming languages also be based on these structures.

In JSON, they take on these forms:

  1. An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
  2. An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
  3. A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
  4. A string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string.

JSON Examples

XML

<quotes>
<quote>"50 degrees all week today." - Ironmule</quote>
<quote>"He wasn't naked...he had sneakers on." -Jon Emmons</quote>
</quotes>

JSON

{quotes:[
"\"50 degrees all week today.\" - Ironmule",
"\"He wasn't naked...he had sneakers on.\" -Jon Emmons"
]
}

XML

<widget>
<debug>on</debug>
<window title="Sample Konfabulator Widget">
<name>main_window</name>
<width>500</width>
<height>500</height>
</window>
<image src="Images/Sun.png" name="sun1">
<hoffset>250</hoffset>
<voffset>250</voffset>
<alignment>center</alignment>
</image>
<text data="Click Here" size="36" style="bold">
<name>text1</name>
<hoffset>250</hoffset>
<voffset>100</voffset>
<alignment>center</alignment>
<onmouseup>
sun1.opacity = (sun1.opacity / 100) * 90;
</onmouseup>
</text>
</widget>

JSON

{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}

Contoh Aplikasi

Untuk mengkonversi POJO ke JSON kita membutuhkan package tambahan:

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

tambahkan method toJSONString pada POJO

 public String toJSONString() {
        XStream xstream = new XStream(new JettisonMappedXmlDriver()); // JSON Converter
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias(Book.class.getSimpleName(), Book.class); //set package alias to class name
        xstream.alias(BookAddress.class.getSimpleName(), BookAddress.class);
        return xstream.toXML(this);
    }

Full Code

index.jsp

 <!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>

        <script type="text/javascript" charset="utf-8">
            $(function(){
                $("select#ctrlBookName").change(function(){
                    $.getJSON("ServletTester",{id: $(this).val(), textInfo: $('#textInfo').val() , ajax: 'true'}, function(response){
                        var options = '';
                        for (var i = 0; i < response.length; i++) {
                            var bookAddresses = response[i].Book.bookAddress[0].BookAddress;
                            for (var idx = 0; idx < bookAddresses.length; idx++) {
                                options += '<option value="' + bookAddresses[idx].address1 + '">' + bookAddresses[idx].address1 + '</option>';
                            }
                        }
                        $("select#ctrlBookAddress").html(options);
                    })
                })

                $("input#ctrlText").change(function(){
                    $.getJSON("ServletTester",{id: $(this).val(), textInfo: $('#textInfo').val() , ajax: 'true'}, function(response){
                        var options = '';
                        for (var i = 0; i < response.length; i++) {
                            var bookAddresses = response[i].Book.bookAddress[0].BookAddress;
                            for (var idx = 0; idx < bookAddresses.length; idx++) {
                                options += '<option value="' + bookAddresses[idx].address1 + '">' + bookAddresses[idx].address1 + '</option>';
                            }
                        }
                        $("select#ctrlBookAddress").html(options);
                    })
                })
            })
        </script>
    </head>
    <body>
        <h1>Book Selection</h1>
        Book ID
        <select name="id" id="ctrlBookName">
            <option>a</option>
            <option>b</option>
            <option>c</option>
        </select>
        Book Address
        <select name="bookAddress" id="ctrlBookAddress">
            <option>pilih salah satu</option>
        </select>
        <input type="text" name="a" id="ctrlText" />
        Text Info<input type="text" name="textInfo" id="textInfo" />
    </body>
</html>

ServletTester.java


package co.id.hanoman.tester;

import co.id.hanoman.ajaxjson.Book;
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;

/**
 *
 * @author Administrator
 */
public class ServletTester extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if (request.getParameter("id") != null) {
                Book book = null;
                if ("a".equals(request.getParameter("id"))) {
                    book = new Book(1, "param 11" + request.getParameter("textInfo"), "param 12", "param 13");
                } else if ("b".equals(request.getParameter("id"))) {
                    book = new Book(2, "param 21" + request.getParameter("textInfo"), "param 22", "param 23");
                } else if ("c".equals(request.getParameter("id"))) {
                    book = new Book(3, "param 31" + request.getParameter("textInfo"), "param 32", "param 33");
                }
                System.out.println(book.toJSONString());
                out.println("[" + book.toJSONString() + "]");
            }
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

— Thats All Folks

XStream xstream = new XStream(new JettisonMappedXmlDriver

28 thoughts on “Ajax JSON for Java Web

  1. Angga Lingga December 8, 2009 / 10:58 am

    Ngeri kali kw ces ???
    Makin kw gilakkan dunia pertiwi ini kulihat …

  2. adisembiring December 9, 2009 / 2:02 am

    Cuma muka mu aja pun yang kulihat di blog aku ini. hahahahah

    Cara diatas cara yang ribet, sekarang banyak UI Ajax For Java, Seperti RichFaces, Ifaces.

    Di kantor kelen pake apa untuk mengimplementasikan ajax ?

  3. swastylumbantobing December 10, 2009 / 6:31 am

    Ternyata dah dikau aplikasikan Adi..😀
    File JSONnya blum ribet2 kali ya di..
    Belum lagi kalau satu file JSON merefer ke file JASON yang laen…

    Tapi lumayan juga make JSON daripda make Database..
    Gak ribet, gak lambat.

    Tapi kalau mau update data, susah. mesti update file JSON nyah..
    udah ntuh mesti refresh lagi halamannya…
    Loja deh..😀

  4. Angga Lingga December 10, 2009 / 6:33 am

    @Swasty
    Ngeri kali kw ces …
    Main belakang kw ama si Adi kan ???

  5. swastylumbantobing December 10, 2009 / 2:02 pm

    @Angga
    Haha,, baru tau kau ces…
    Jgn kasitau sapa2 yah ces,, ecek2nya bisik2 kita yang cerita ini..😀

  6. adisembiring December 11, 2009 / 5:56 am

    weitzzzzzz, udah muncul master JSON + extJS😀

    JSON Sample yang aku kasi itu hanya sebagai conton penjelasan tentang JSON. Coba lihat Class Book dan BookAddress, Book memiliki Book address.

    Basically, Kami menggunakan JSON bukan untuk database, tapi untuk pengolahan ajax response yang merupakan return backend dan di oleh di frontend program.
    kalo xml itu susah di oleh, ribet kali kurasa.

    Sebenarnya si angga udah master JSON sejak mereka KP. cuma diam2 aja dia, ngga mau dia share ilmunya ama kita2. hahahaha

  7. Angga Lingga December 11, 2009 / 6:22 am

    @Adi
    Sejak kapan awak ngenal namanya JSON ini …
    Barulah dari kw ini …
    Makanya aku mau berguru ama kw …

    Apalagi si Swasty ini …
    Master JSON + extJS

  8. swastylumbantobing December 11, 2009 / 8:38 am

    @Adi
    Ouw,,,
    Udah masterlah kau yah adi… Kau gilakkan JAVA itu khan..😛

    btw, tunggu dulu. Apa contoh fungsi ajax yang kau pake? dan untuk apa?
    Bukannya ribet juga kalau mengolah file JSON??? Sama2 ngolah filenya.. Trus apalah untungnya? Karena selama ini aku make JSON cuma utk ngambbil data yang static.. n bakalan jarang di ubah sama user selain ngubah langsung file JSON nya.
    Misalnya: Menu-menu item di website, menu-menu hierarchi yang beranak cucu.
    Pokoknya data-data yang terstruktur.

    Trus kau JSON yang kau pake ntuh lebih detailnya gimana Di??

    @Angga
    Iya angga.. jgn sok2 bodo kau disitu..
    Kmren udah sampe dipanggil sama direktur SUN Microsoft ktnya kau buat kerja di kantornya..😀

  9. swastylumbantobing December 11, 2009 / 8:40 am

    Btw, namabahi Adi lafet…
    Minta dibilang kau yang Master…
    Master JSON & JSP..😉

  10. Angga Lingga December 11, 2009 / 9:21 am

    @Swasty
    Kerja apa ???
    Jadi OB ???

    Hahaha …

  11. swastylumbantobing December 11, 2009 / 9:25 am

    @Angga
    tukang kusut..😀

  12. adisembiring December 11, 2009 / 9:29 am

    gini wes …, sepertinya kau masih terkena sugesti kalo JSON itu hanya digunakan sebagai data storage. tapi sebenarnya bukan, JSON itu digunakan untuk merepresentasikan data, sama lah guna nya dengan xml. hanya format mereka saja yang beda

    basically, kalo kw pernah make implementasikan ajax tanpa framework. pasti return value dari server ajax itu adalah xml.

    nah kalo mau mengolah data xml di javascript kan susah, biasanya aku pake DOM.

    harus ambil list buku dari response
    var books = reponse.getElementByTagname(books);

    var book = books[0];
    alert(book.getElementByTagname(“title”));

    //kalo mau rubah data
    book.getElementByTagname(“title”).value = “new moon”;

    nah kalo seandainya return ajax itu JSON kan jadi gampang.
    var books = response.books
    var book = books[0]

    alert(book.title);
    book.title = “new moon”;

    kan lebih sederhana😀

    intinya JSON itu memepermudah pengolahan data dibandingkan xml

    • Angga Lingga December 11, 2009 / 9:39 am

      Memang sama ces …
      Dan bahkan kalo membaca data yang terdapat dalam JSOn ini lebih mudah …
      Dia semacam Array dalam Array kan ces ???

      CMII

      Aku kalo make JSON lebih sering kaya gini

      {
      “username”: “angga”,
      “details”: [
      {
      “queue”: “34”,
      “name”: “beomeetest1”,
      “items”: [
      {
      “sender”: “angga”,
      “message”: “Welcome to Test Chat Center!You are handled by Angga Lingga now…”
      },]
      },
      {
      “queue”: “38”,
      “name”: “angga_lin”,
      “items”: [
      {
      “sender”: “angga”,
      “message”: “Welcome to Test Chat Center!You are handled by Angga Lingga now…”
      },
      {
      “sender”: “angga”,
      “message”: “Welcome to Test Chat Center!You are handled by Angga Lingga now…”
      },
      {
      “sender”: “angga_lin”,
      “message”: “halo”
      },]
      },]
      }

      Tapi karena JSON ini merupakan JavaScript
      Apakah semuanya bisa baca JSON ???

  13. adisembiring December 11, 2009 / 9:31 am

    @angga
    katanya kw pernah pake REST ??? pura2 tidak tw kw y

    @wes cintaku …😀
    Ngga semaster kau aku ces , hahahaha😛

    • Angga Lingga December 11, 2009 / 9:40 am

      Hahaha ngejek kali kw bah ces …
      Lappetlah kw

  14. swastylumbantobing December 11, 2009 / 9:41 am

    wakaka.. gak ada aku di sugestiin orang..

    Kalau JSON buat representasiin data Emang Betol..!!!
    Emang jadi mudah liatnya.. Terstruktur dia…

    Blum pernah aku say make AJAX tanpa Framework, makanya agak bingung..
    Selama ini make AJAX bawaan framework…

    Dan aku baru tau kalu file JSON bisa langsung diubah nilainya kyak kau bilang tadi:
    book.title = “new moon”;
    itu emang langsung di edit di file JSONnya yah????
    Kmren aku make file JSON utk php gak dapet fungsi yg githu,,,
    terpaksa aku harus tulis ulang file JSONnya n refresh lagi websitenyah…
    CMIIW

    • Angga Lingga December 11, 2009 / 9:46 am

      Serius bisa ubah file JSONnya ???

  15. adisembiring December 11, 2009 / 9:50 am

    @angga
    hahah .., udah keluar masternya si angga.

    ada perlu diluruskan paradigma mu tentang JSON. JSON itu bukan java script, kepanjanganya adalah Java Script Object Notation. Artinya Object yang bernotasikan JavaScript.

    Hampir sama ini dengan XML.

    Jadi JSON itu bisa dibaca di banyak bahasa pemrogramman. Pake Java, PHP. dll. tentunya harus ada JSON APINya.

    @Wes
    Nampak kali kw udah expert di extJS. samp2 lupa kw ajax conventional. hahaha😛

    • Angga Lingga December 11, 2009 / 9:55 am

      Ces …
      JavaScript … bukan Java Script jadi salah persepsi nanti …

      Tapi bacanya kebanyakan orang bacanya kok pake JavaScript ya ???

      Apa pula itu ces AJAX Conventional

      @Swasty
      Ngeri kali kw ces !!!

      • ganda January 12, 2010 / 11:10 am

        kau yang master ga, sampai bedanya pun kau ingat. aku sendiri lupa. :p

      • Angga Lingga January 12, 2010 / 11:17 am

        @Ganda
        Ah kw ngejek aja kerjaanmu bang bah …
        Hehehe …

      • ganda January 13, 2010 / 6:06 am

        @angga : gak ngejek, memang kenyataannya kau master.🙂

  16. swastylumbantobing December 11, 2009 / 10:04 am

    @Angga
    Hahaha… kenapa ces.. Minta dibilang kau.
    Aku juga bingung ini ces, kmren aku mau ngedit nilai di file JSON ribet x… klu bisanya kyak yg dibilang si Adi,khan mantap…

    @Adi
    Hahah,, Memang gak pernah aku make ajax kek githu.. Apa lagi itu namanya?? Ajax Conventional??????? Baru ini kudengar,,, wakakaka…
    Udah terbiasa hidup sm bawaan framework..😀

    Jadi gmnanya di?? Klu di PHP kira2 boleh editnya kyak yg kau buat itu tadi???

  17. adisembiring December 11, 2009 / 10:05 am

    karena sering nulis pake JavaScript di coding

    AJAX Conventional / Jadul / tanpa framework seperti yang dipake guru besarku itu lo. extJS.

    Kelen pake framework ajax apa disana ?

    • Angga Lingga December 11, 2009 / 10:07 am

      Ohhhh …
      Pure AJAX yang hanya langsung retrieve nilai dari output halaman itu ya ???

      Make jQuery … yang biasa itu …

  18. Rikky Hermanto Hasibuan December 15, 2009 / 6:10 am

    Seep…. ini juga bisa di pake buat nge-leech… It makes your system could do doGet() and doPost() without knowing by server… :pengalaman-mode-on:
    😛

  19. Rikky Hermanto Hasibuan December 15, 2009 / 6:11 am

    Seep….. ini juga bisa di pake buat nge-leech… It makes your system could do doGet() and doPost() without knowing by server… :pengalaman-mode-on:
    😛

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s