1

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.

1

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 %>;

Comments

0

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'...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.