Communication between JSP and Servlet?

送分小仙女□ 提交于 2019-12-31 02:18:16

问题


I have a jsp page that communicate with a servlet back end. Up until now, the way I communicate with that servlet is via .getJSON() which is a JQuery method. This work great if the data I want to send back is in the form of {key:value}. However, now I need to send a bit more data then that. The largest table in my database, contain roughly eleven attributes, and the number of row is about 20-40. It is not big, but not small to send table via JSON. I am think about XML, and I wonder if any one can shed me some light. Sample codes would be appreciated, link to tutorial, article would be awesome as well.


回答1:


Just have the data in a collection or map of fullworthy Javabeans and make use of Google Gson to convert it to JSON without any pains. JSON is more compact than XML and much easier to process in JavaScript (it's also the JavaScript Object Notation).

All you basically need to do with help of Gson is the following:

List<Data> list = dataDAO.list();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(list));

That's all. I've answered this several times before with examples: here, here, here, here and here.



来源:https://stackoverflow.com/questions/2413636/communication-between-jsp-and-servlet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!