comi single blog(欢迎访问我的个人博客,现开放注册)
responseBody介绍:@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用;
在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。例如,异步获取 json 数据,加上 @Responsebody 注解后,就会直接返回 json 数据。
requestBody介绍:@requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象
添加依赖
<!--json jar包-->
<dependency>
<groupId>top.jfunc.common</groupId>
<artifactId>converter</artifactId>
<version>1.8.0</version>
</dependency>
修改springmvc.xml的annotation 标签数据,改为如下格式
@RequestMapping(value = "/getAllUsers", produces = "text/html;charset=utf-8")
@ResponseBody
public String getAllUsers() {
List<User> users = service.getAllUsers();
return "{ \"code\":200,\"message\":\"成功\",\"data\":" + JSONObject.toJSONString(users) + ",\"count\" : \"10\"}";
}
前端layui页面设置response
<script>
layui.use('table', function () {
var table = layui.table;
table.render({
elem: '#test'
, url: 'http://localhost:8080/ssmWork_war_exploded/getAllUsers'
, cellMinWidth: 80
, response: {
statusName: 'code',
statusCode: 200,
msgName: 'msg',
countName: 'count',
dataName: 'data'
}
, cols: [[
{field: 'id', width: 80, title: 'ID', sort: true}
, {field: 'name', width: 80, title: '用户名'}
, {field: 'sexual', width: 80, title: '性别'}
, {field: 'password', width: 300, title: '密码'}
, {field: 'integral', width: 80, title: '积分', sort: true}
, {field: 'total', width: 120, title: '文章总数', sort: true}
, {field: 'signature', title: '签名', width: '30%', minWidth: 100}
]]
});
});
</script>
渲染结果
分页实现
dao
// bean对象自动解析,单独的参数需要使用param1,param2,同样也可以使用注解标识
@Select("select * from users limit #{param1},#{param2}")
public List<User> PaginationUser(Integer start, Integer num);
service
public List<User> PaginationUser(Integer start,Integer num);
serviceImpl
@Override
public List<User> PaginationUser(Integer start, Integer num) {
return dao.PaginationUser(start, num);
}
controller
@RequestMapping(value = "/PaginationUser", produces = "text/html;charset=utf-8")
@ResponseBody
public String PaginationUser(@RequestParam(name = "page") Integer page) {
int start = 1; // 默认第一条数据为1
int num = 5; //规定返回数据量
List<User> users;
if (page == 1) {
users = service.PaginationUser(0, num); //数据库从0开始
} else {
users = service.PaginationUser((page * num) - 1, num);
}
int count = service.countAll();
// 数据封装
if (users.size() != 0) {
return "{ \"code\":200,\"message\":\"成功\",\"data\":" + JSONObject.toJSONString(users) + ",\"count\" : " +
(count % 5 == 0 ? count / 5 : (int) (count / 5) + 1)
+ "}";
//计算页数
} else {
return "{ \"code\":100,\"message\":\"失败\",\"data\": [],\"count\" : 0}";
}
}
最终效果(注意观察页数也返回的数据)
页面不存在