<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js"></script>
</head>
<body onload="testJosn()">
<button onclick="testJosn()">点击这里请求</button>
<table style="width:100%" border=1>
<tr align="center">
<td>产品编号</td>
<td>产品名称</td>
<td>类别</td>
<td>价格</td>
<td>图片</td>
<td>条形码</td>
<td>二维码</td>
<td>说明</td>
<td>生产时间</td>
</tr>
<c:forEach items="${productList}" var="product">
<tr align="center">
<th scope="row">${product.id}</th>
<td>${product.productname}</td>
<td>${product.category}</td>
<td>${product.price}</td>
<td>${product.image}</td>
<td>${product.barcode}</td>
<td>${product.qrcode}</td>
<td>${product.description}</td>
<td><fmt:formatDate value="${product.protime}"
pattern="yyyy-MM-dd" /></td>
</tr>
</c:forEach>
</table>
<script type="text/javascript">
function testJosn() {
$.ajax({
url : "http://localhost:8080/zyr0609/rest/products",
type : "get",
contentType : "application/json;charset=UTF-8",
dataType : "json",
success : function(result) {
alert("返回码:" + result.id);
alert("信息:" + result.message);
alert("是否成功:" + result.success);
$.each(result.data, function(i, item) {
print("第" + (i + 1) + "条记录:" + item.productname);
});
},
error : function() {
print("请求失败");
}
});
}
</script>
</body>
</html>
package controller.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.Product;
import service.ProductService;
@Controller
public class ProductRest {
@Autowired
private ProductService productService;
@RequestMapping(value="rest/products",method=RequestMethod.GET)
@ResponseBody
public List<Product> allProduct(){
List<Product> productList =productService.allProduct();
return productList;
}
}
package controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Product;
import service.ProductService;
@Controller
public class ProductController {
@Autowired
ProductService productService;
@RequestMapping("product")
public String allProduct(Model model) {
List<Product> list = new ArrayList<Product>();
list = productService.allProduct();
model.addAttribute("productList", list);
return "AjaxProductList";
}
}