网页
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>欢迎使用查询系统</title>
<link rel="stylesheet" href="./layui/css/layui.css">
<script src="/layui/layui.js"></script>
<script src="/jquery/jquery-3.2.1.js"></script>
<script src="/js/excel.js"></script>
<div class=layui-field-box>
<table class="layui-table">
<colgroup>
<col width="150px">
<col width="150px">
<col width="150px">
<col width="150px">
</colgroup>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>WEIGHT</th>
<th>PRICE</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
js中动态生成数据到前台(加载时执行)
$(function(){
var tabletTbody = $(".layui-table").find('tbody');
tabletTbody.empty();
$.getJSON("/goods/showGoods",function(json){
// 下面使用each进行遍历
$.each(json, function(i, item) {
var vTr = "<tr><td>" + item.id + "</td><td>" + item.name
+ "</td><td>" + item.weight+"</td><td>" + item.price
+ "</td></tr>"
tabletTbody.append(vTr);
});
})
})
controller定义为可返回object类似@RestController
package com.yayun.controller;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yayun.service.GoodsService;
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Resource
private GoodsService goodsService;
@RequestMapping("/showGoods")
public Object toIndex(String name){
return goodsService.getGoodsByName(name);
}
}
其中在spring-mvc中需要配置自动转换,能将object成json(使用的是fastjson)
<!-- 启用默认配置 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 配置Fastjson支持 -->
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="features">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>