@ResponseBody注解和@RequestBody注解使用

1,@ResponseBody注解

@ResponseBody将java对象转为json格式的数据,返回页面。

一般@RestController的作用就相当于@ResponseBody+@Controller

一般使用:

@RestController
@RequestMapping("/sys/student")
public class StudentController {
}

2,@RequestBody注解

 @RequestBody使用json的格式传递数据,把json数据封装到对象中来。如果用 @RequestBody,那么就需要使用post方式提交。参数required = false:表示参数值可以空。 

一般使用:

 @ApiOperation(value = "带条件分页讲师列表")
    @PostMapping("page/{page}/{limit}")
    public String pageListCondition(
            @ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)@PathVariable Long limit,

            @RequestBody(required = false) StudentQuery studentQuery){

        Page<Student> pageParam = new Page<>(page, limit);
        QueryWrapper<Student> query=new QueryWrapper();
        //构建条件
        //多条件组合查询(即判定条件十分为空,决定是拼接条件
        Integer age = studentQuery.getAge();
        LocalDateTime createDate = studentQuery.getCreateDate();
        LocalDateTime updateDate = studentQuery.getUpdateDate();
        Integer id = studentQuery.getId();

        if(!StringUtils.isEmpty(age)){
            query.eq("age",age);
        }
        //gt,大于等于
        if(!StringUtils.isEmpty(createDate)){
            query.gt("begin",createDate);
        }
        //le,小于等于
        if(!StringUtils.isEmpty(updateDate)){
            query.le("updateDate",updateDate);
        }
        if(!StringUtils.isEmpty(id)){
            query.eq("id",id);
        }
        iStudentService.page(pageParam, query);
        List<Student> records = pageParam.getRecords();
        long total = records.size();//当前查询出多少条数据


        System.out.println(total);
        JSONObject json=new JSONObject();
        json.put("total", total);
        json.put("records", records);

        return  json.toString();
    }

在方法参数中 @RequestBody(required = false) StudentQuery studentQuery。可以在页面上把对象封装成json提交。

如:

 

对比,没有使用 @RequestBody注解时候,即 :StudentQuery studentQuery,虽然根据对象不用注解也可以获取页面传递的数据。是这样的:

 

 


版权声明:本文为qq_45315910原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。