触发查询后我有一个ResultSet.请告诉我如何将其转换为JSP中的
JSON输出.
在第二阶段,我们假设我们有一个JSON输出,就像在这个链接> http://inknpost.com/eshopping/json.jsp
解决方法
创建一个可重用的Javabean类,它表示一行,一个实体.
public class Category { private Long id; private String name; private String department; // Add/generate getters/setters/c'tors/equals/hashcode and other boilerplate. }
创建一个可重用的DAO类,它以通常的JDBC方式将ResultSet映射到这些Javabeans的集合.
public class CategoryDAO { private static final String sql_LIST = "SELECT id,name,department FROM category"; // ... public List<Category> list() throws sqlException { List<Category> categories = new ArrayList<Category>(); try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement(sql_LIST); ResultSet resultSet = statement.executeQuery(); ) { while (resultSet.next()) { Category category = new Category(); category.setId(resultSet.getLong("id")); category.setName(resultSet.getString("name")); category.setDepartment(resultSet.getString("department")); categories.add(category); } } return categories; } // ... }
创建一个servlet类,它使用JSON序列化器/反序列化器,它能够在Javabeans的arbirary集合和JSON字符串之间进行转换,例如Google Gson.
@WebServlet("/categories.json") public class CategoriesJsonServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { try { List<Category> categories = categoryDAO.list(); String categoriesJson = new Gson().toJson(categories); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(categoriesJson); } catch (sqlException e) { throw new ServletException("DB error",e); } } }
通过http:// localhost:8080 / contextname / categories.json调用它.不,没有涉及JSP.您不应该将JSP用于HTML以外的输出格式.
最后,在jQuery中,只需访问它通常的$.getJSON()方式.
$('#somebutton').click(function() { $.getJSON('categories.json',function(categoriesJson) { var $table = $('<table>').appendTo($('#somediv')); $.each(categoriesJson,function(index,category) { $('<tr>').appendTo($table) .append($('<td>').text(category.id)) .append($('<td>').text(category.name)) .append($('<td>').text(category.department)); }); }); });