Communication between JSP and servlet?

I have a jsp page that links to the back end of a servlet. So far, the way to communicate with this servlet is through .getJSON (), which is a jQuery method. This works great if the data I want to send back is in the form {key: value}. However, now I need to send a little more data. The largest table in my database contains about eleven attributes, and the number of rows is about 20-40. It is not big, but not small, to send the table via JSON. I am thinking about XML, and I am wondering if anyone can shed some light. Sample code would be appreciated, link to tutorial, article would also be awesome.

+3
source share
1 answer

Just enter the data in the collection or map of full Javabeans and use Google Gson to easily convert it to JSON. JSON is more compact than XML, and it is much easier to process it in JavaScript (this is also the designation of JavaScript objects ).

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

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

It's all. I have already answered this several times with examples: here , here , here and here .

+3
source

Source: https://habr.com/ru/post/1736228/


All Articles