踩坑小记—页面跳转失败,出现500错误页面

772 阅读1分钟

踩坑记录,愿天堂没有BUG!

错误信息:

  1. EL1007E: Property or field 'content' cannot be found on null

  2. Exception evaluating SpringEL expression: "page.content" (template: "admin/types" - line 65, col 21)

这个博客是在学习springboot时跟着网上教程做的,跟着做都出错,做个记录悼念一下自己的智商。

根据错误提示"page.content",第一反应是thymeleaf或者Controller哪里写错了。

<tr th:each="type,iterStat : ${page.content}">
    <td th:text="${iterStat.count}">1</td>
    <td th:text="${type.name}">Java学习之旅</td>
    ...
</tr>
@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @GetMapping("/types")
    public String type(@PageableDefault(size = 3,sort = {"id"},direction = Sort.Direction.DESC)
                               Pageable pageable, Model model){
        Page<Type> page=typeService.listType(pageable);
        model.addAttribute("page",page);
        return "admin/types";
    }
}

但是以上似乎都没有写错,但是有几个需要注意的细节:

  1. Controller的Pageable需要选择import org.springframework.data.domain.Pageable中的,不然会出错。
  2. TypeService记得要@Component,不放在容器内,无法被注入。
  3. model.addAttribute("page",pageable); 中的"page"不要漏掉了

解决办法:理解这段代码,这是一个遍历,既然代码都没出错,搞不好就是page他压根就没有。在Controller里输出试了一下,直接来个null,得了。。。

@Override
    public Page<Type> listType(Pageable pageable) {
        Page<Type> page=typeRepository.findAll(pageable);
        return page;
    }

这段没写。。补上,BUG消失,页面成功访问。