今天遇见一个很低级的错误,但也让人头疼一阵子,起初发现是自己代码的错,越到后面发现自己代码完全没有问题。
错误信息
//浏览器报错
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri May 12 18:23:36 CST 2023
There was an unexpected error (type=Internal Server Error, status=500).
//控制台报错
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
代码:
//Mapper
List<NewsDetail> selectLike(@Param("categoryId") Integer categoryId, @Param("title") String title);
//Mapper.xml
<select id="selectLike" resultType="com.example.provider.entity.NewsDetail">
select * from `news_detail`
<where>
<if test="categoryId != null and categoryId !='' and categoryId != 0">
categoryId = #{categoryId}
</if>
<if test="title != null and title != ''">
and title like '%${title}%'
</if>
</where>
</select>
//Service
List<NewsDetail> selectLike(int categoryId, String title);
//Impl
@Override
public List<NewsDetail> selectLike(int categoryId, String title) {
return mapper.selectLike(categoryId, title);
}
//Controller
@GetMapping("/")
public String test(@RequestParam(defaultValue = "1",value = "pageNum")Integer pageNum,
@RequestParam(required = false) Integer categoryId,
@RequestParam(required = false) String title,
Model model){
PageHelper.startPage(pageNum,2);
List<NewsDetail> list = newsDetailService.selectLike(categoryId, title);
PageInfo<NewsDetail> pageInfo = new PageInfo<>(list);
List<NewsCategory> newsCategories = newsDetailService.selectAll();
model.addAttribute("newsCategories",newsCategories);
model.addAttribute("pageInfo",pageInfo);
return "index";
}
若是你细心你也你能看出来了,这主要问题就是 Service 层的类型(int)写错了,Mapper跟Controller层用的都是 Integer,因为之前只看Mapper层,觉得Mapper层没有错误那么别的层也没有问题,所以它就给我来了一刀。
其实 因为 Integer与int 无法转换,因为 Integer 的默认值为空,也就是 null,而int的默认值就是0,所以 会因为数据类型不同而报错,即使你Mapping的文件写的没错,但一定会报错。