Piscean
Piscean

Reputation: 3079

How can we tell jQuery to access a Java arraylist in JavaServlets?

I am using Java servlets and JSP in my web application. My question is that how can i tell jQuery to access a java arraylist. For example i want to show a list of books in my page and i am getting list of those books using java servlet. Now i want to tell jQuery that if a specific button is clicked then show these books in that page. How can i do that? Or is there any other way to do that? Thanks in advance.

Upvotes: 1

Views: 4961

Answers (3)

pcjuzer
pcjuzer

Reputation: 2824

Here is an Ajax solution: In the servlet side, you have to write a logic in doGet or doPost method, which returns the contents of the list in XML, JSON or HTML. In client-side you have to write a logic which interprets and displays this data. In case of HTML, you just have to put the content into a DIV. In case of JSON or XML, you have to use further JQuery components (plugins) for example jqGrid. A simple example on client side for the HTML-based solution:

$.get('getlist', function(data) {
  $('#Listdiv').html(data);
});

Listdiv is the id of a DIV where the list will be displayed. getlist is the URI which your servlet will respond for.

Generating HTML content into String and write it into the HttpServletOutputStream isn't an issue:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String result = null;
          //TODO generate HTML  into 'result' here
    Writer out = new OutputStreamWriter(resp.getOutputStream(), "utf-8");
    resp.setContentType("text/html");
    out.write(result);
    out.close();
}

If you don't want to create a separated servlet, you can also use HTML content generated by JSP. In this case, you can put the JSP uri into the Ajax call: $.get('getlist.jsp'...)

Upvotes: 0

Sandeep Pathak
Sandeep Pathak

Reputation: 10747

You should use Json Library in order to serialize your ArrayList to JSON:

     String json = (new JSONArray(yourList)).toString();

And use this on mouseclick in jquery like :-

     var list= <%= json %>;

Upvotes: 0

Manish
Manish

Reputation: 3968

jQuery is a client side framework, it can not access the arraylist. Servlets/JSP are server side. When jQuery sees the page, its just plain html. What you can do is, convert your arraylist to JSON, and then output the json string in your JSP. jQuery can use the json string to display data on page.

You can have a look at http://code.google.com/p/google-gson/, which is one of the best Java-JSON library available.

Upvotes: 2

Related Questions