今天遇到了一个非常奇怪的问题,当我在使用@RequestBody 进行传参时,在service层一直获取不到对象值,后台提示错误是空指针异常,找了很久都没有发现是什么问题,结果在最后发现是注解的坑。
@GetMapping("/**/{pageNow}/{pageSize}")
public Response getAllCourseByPage(@PathVariable long pageNow,
@PathVariable long pageSize,
@RequestBody(required = false) **Query **Query) {
Page<EduCourse> **Page = new Page(pageNow, pageSize);
courseService.pageQuery(**Page, **Query);
long total = **Page.getTotal();
List<EduCourse> records = **Page.getRecords();
return Response.ok().data("total", total).data("items", records);
}
@Override
public void pageQuery(Page<EduCourse> **Page, **Query **Query) {
QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
String title = **Query.getTitle();
String status = **Query.getStatus();
if (!StringUtils.isEmpty(title)) {
queryWrapper.like("title", title);
}
if (!StringUtils.isEmpty(status)) {
queryWrapper.eq("status", status);
}
queryWrapper.orderByDesc("gmt_create");
baseMapper.selectPage(coursePage, queryWrapper);
}
java.lang.NullPointerException
at com.nanjuedu.serviceedu.service.impl.EduCourseServiceImpl.pageQuery(EduCourseServiceImpl.java:102)
at com.nanjuedu.serviceedu.service.impl.EduCourseServiceImpl$$FastClassBySpringCGLIB$$d6c817dd.invoke(<generated>)
但是经过debug之后发现我的service层中并没有获取到对象(Query),导致对象(Query)为空,当对象调用getter方法时就会爆出空指针异常的错误!找了很久都没发现哪里出错了,结果是错在了注解上!!!
springMvc的新注解:GetMapping 不支持@RequestBody ,使用PostMapping改成以下代码就可以了!
@PostMapping("/**/{pageNow}/{pageSize}")
public Response getAllCourseByPage(@PathVariable long pageNow,
@PathVariable long pageSize,
@RequestBody(required = false) **Query **Query) {
Page<EduCourse> **Page = new Page(pageNow, pageSize);
courseService.pageQuery(**Page, **Query);
long total = **Page.getTotal();
List<EduCourse> records = **Page.getRecords();
return Response.ok().data("total", total).data("items", records);
}