Returning an array of strings from a Java servlet in jQuery

I am currently working on a web application that displays image slide shows using the Cycle plugin for jQuery. For ease of use, I make the app customizable, allowing someone to change the path for which slide images can be found for display. I found the necessary code to create all the image file names in a single String array, but I'm not quite sure how to pass the entire array back to jQuery for processing. I already use Java Servlet as a proxy for accessing some RSS feeds, so I decided to use the $ .get () method to make an HTTP request with a flagged parameter to determine which functions to perform.

In short, how can I pass a String array to an HttpServletResponse variable so that it can be accessed, like a String array in my jQuery? Here are some of the code that I use so far ... Note. I am new to Java and JavaScript, including jQuery. I know that my code is probably inaccurate and / or inefficient.

---HERE THE JAVA SERVLET---- import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.URL; import javax.servlet.http.HttpServlet; public class BBSServlet extends HttpServlet { private void getSlidesList(final HttpServletResponse response) throws ServletException, IOException { try { File slidesdir = new File(AppConfiguration.getInstance().getSlidesDir()); if(slidesdir.isDirectory()) { String slidenames[] = slidesdir.list(); // This is what I thought I could do... final PrintWriter writer = response.getWriter(); for(int i = 0; i < slidenames.length; i++) { writer.println(slidenames[i]); } // But I'm not sure if it works... } } catch(final IOException e) { e.printStackTrace(); } } public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); final URL url; if(request.getParameter("p").equals("w")) { url = new URL(AppConfiguration.getInstance().getForecastUrl()); sendXML(response, url); } else if(request.getParameter("p").equals("n")) { url = new URL(AppConfiguration.getInstance().getNewsUrl()); sendXML(response, url); } else if(request.getParameter("P").equals("f")) { getSlidesList(response); } } } ---jQuery js------------ // function called from the $(document).ready() function DisplaySlides() { $.get(baseContext + "/servlet?p=f", function(data) { // "data" is hopefully a String array? } // display my slideshow with that array } 
+4
source share
1 answer

I would suggest using JSON Parser in Java, like Jackson , to convert an array of strings to JSON. JQuery can then read this and turn it into a javascript array with jQuery.getJSON .

+1
source

All Articles