赞
踩
在前后端进行数据交互的时候,如果交互的数据比较多,比如说是一个集合,那么正常的就不能使用String或者其他的基本数据类型来完成交互,而是使用JSON格式,因为JSON格式对于浏览器来说更加易于解析,并且是一个主流的数据传输的格式。
JSON有两大数据类型:
@WebServlet("/buyBook/SelectBookStockViewServlet") public class SelectBookStockViewServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); String bookName = request.getParameter("bookName"); if(null == bookName) { bookName = ""; } BuyBookService service = new BuyBookServiceImp(); List<BookStockView> bookStockViews = service.selectBookStockViewByBookName(bookName); //Collection : 表示的是集合的最高父接口 //Connection : 数据库连接对象 JSONArray jsonArray = new JSONArray(); jsonArray.addAll(bookStockViews);//将集合中所有的对象放入到JSONArray中 out.print(jsonArray);//向页面响应jsonArray out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
以上就是将list集合中的数据转换为json格式输出到前端的代码
如果是单个数据,就用JsonObject对象输出。
JSON是前后端交互常用的数据格式,需要熟悉如何使用。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。