我在触发查询后得到了ResultSet。请让我知道如何将其转换为JSP中的JSON输出。如何将ResultSet对象转换为JSON格式输出
在第二阶段中,让我们假设我们有一个JSON输出像在此链接>http://inknpost.com/eshopping/json.jsp
上述文件是由一个$ .getJSON访问();在另一个文件中。
请让我知道如何在页面的不同行中显示“名称”和“部门”。
我在触发查询后得到了ResultSet。请让我知道如何将其转换为JSP中的JSON输出。如何将ResultSet对象转换为JSON格式输出
在第二阶段中,让我们假设我们有一个JSON输出像在此链接>http://inknpost.com/eshopping/json.jsp
上述文件是由一个$ .getJSON访问();在另一个文件中。
请让我知道如何在页面的不同行中显示“名称”和“部门”。
创建一个表示一行,一个实体的可重用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类的ResultSet
映射到一个集合这些的JavaBeans通常的JDBC方式。
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;
}
// ...
}
创建其使用JSON串行器/解串器,其能够Java Bean的arbirary收集和JSON字符串之间进行转换,例如一个Google Gson servlet类。
@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));
});
});
});
要创建您的json,您可以使用google-gson库。
然后,处理jQuery中您的JSON,这取决于你的需求,但假设你想显示在一个表中,你可以做到这一点通过以下方式:
HTML:
<table id="mytable">
<tr> <th> Name </th> <th> Department </th> </tr>
</table>
Javascript:
$.getJSON("your_url", function(categories){
for(var i=0; i<categories.length; i++){
var name = categories[i].name;
var department = categories[i].department;
$("#mytable").append('<tr><td>'+ name +'</td><td>'+department+'</td></tr>');
}
});
希望这会有所帮助。干杯
非常感谢你干净整理好的代码 – skystar7
@BalusC很棒的解决方案,如果没有你,stackoverflow将不会一样! :) –