Reputation: 4418
I have written a Servlet something like this
public class ServletUtil extends HttpServlet {
private static final long serialVersionUID = 1571172240732862415L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String acInfo = request.getQueryString();
someDao dao = new someDao();
ArrayList<String> resultAutoComplete=dao.someResults(acInfo);
out.close();
}
}
I have an auto complete Object/wizard in front end and as the user types in it is making Ajax call to back end to grab the list of results. So I have written a Servlet and I am pulling the user input and getting my results from DAO layer.
My question here is how should I send this list(resultAutoComplete) to Front end in the Servlet?
Upvotes: 0
Views: 2192
Reputation: 764
No json! instead of going through a list in javascript, return a completed <li>
lists and replace innerHTML
of <ul>
.The reason to do so is to give a better performance. Unless you want to do something more flexible, leave things to the back-end.
When do json, you gotta parse string into json object and then loop through and generate html, that's just an extra step. Keep things simple, plus, parsing string could be costly.
If you don't loop through the list and instead do out.println
the list object, you would likely see the address. also, you need to generate html, so:
StringBuilder sb = new StringBuilder();
for(String option: options){
sb.append("<li>").append(option).append("</li>");
}
out.println(sb);
Upvotes: 0
Reputation: 53496
By serializing it to a String and writing it to out
...
Seriously though, I wouldn't code at the low level Servlet spec. For this kind of return-this-pojo call I would use Spring 3's RESTful service libraries, or something similar.
Upvotes: 0
Reputation: 10241
Try this,
for (String str : resultAutoComplete)
{
out.println(str);
}
Upvotes: 0
Reputation: 272217
I'd expect you to serialise this in some fashion such that the client understands it. e.g. perhaps using JSON or similar.
I note that your response content type is text/html
. So why not simply write each element of your list to your Writer
out, separated by (say) a <li>
element (with the appropriate unordered/order list entities surrounding this)
Upvotes: 2