【发布时间】:2015-03-18 18:38:54
【问题描述】:
我正在使用 struts 2、mysql、jquery、jsp、bootstrap、gson 和 tomcat 开发在线购物应用程序。
我有一个名为 Product 的 Java 实体,控制器操作返回产品的 json 数组和通过 ajax 调用该操作并向用户显示所有产品的 jsp 页面。
我不明白的是如何显示这样的json数组。
我搜索了JQuery Datatables plugin,因为它建议过滤和分页,但我不知道它应该如何配置,因为我不想按产品字段对信息进行分组,而是按每个产品实体进行分组,例如下图:
如果有更好的插件或其他解决方案请推荐,但请注意,在未来的开发中我想添加Product的图像。
Product实体:
public class Product{
private long id;
private String name;
private double price;
private long storeId;
//getters and setters
}
和动作控制器类ViewAllProducts:
public class ViewAllProducts extends ActionSupport {
@Override
public String execute() throws Exception {
LOG.trace("Start execute");
Collection<Product> products = productDAO.findAll();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(products,
new TypeToken<Collection<Product>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(jsonArray);
LOG.trace("Finished execute");
return null;
}
}
这是我在 jsp 页面中的代码,我在其中执行 Ajax 调用以执行此操作:
<%@ include file="/WEB-INF/jspf/directive/page.jspf"%>
<%@ include file="/WEB-INF/jspf/directive/taglib.jspf"%>
<html>
<%@ include file="/WEB-INF/jspf/head.jspf"%>
<body>
<%@ include file="/WEB-INF/jspf/menu.jspf"%>
<div class="container" style="width: 40%">
<div id="results"></div>
</div>
<script type="text/javascript">
$.ajax({
type : 'GET',
dataType : 'json',
url : 'product/upload_products',
success : function(products) {
$.each(products, function(index, product) {
$('#results').append(?????);
});
}
},
})
</script>
</body>
</html>
Json 数组输出示例:
[{"name":"Amet Ultricies Incorporated","price":679.71,"storeId":1,"id":1},
{"name":"Ut Nisi A PC","price":1133.43,"storeId":1,"id":2},
{"name":"Ligula Limited","price":156.66,"storeId":1,"id":100}]
【问题讨论】:
-
不要使用数据表。 Datatables 非常适合实际表,但不适用于通用列表。而是使用模板引擎。我喜欢dust templates,其他人更喜欢小胡子或车把。有几种可供选择。这是interesting article on how LinkedIn chose the templating engine for their platform。
-
@gilly3 感谢您提供的链接,我会看的。但正如我现在用谷歌搜索的那样,对我来说最好的解决方案是使用
dust.js,如果是这样,你能解释一下吗?
标签: java jquery json twitter-bootstrap datatables