Spring Boot中Section父子关联新增功能出现白标错误求排查
Spring Boot Section父子节点创建问题
我是Java Spring Boot环境的新手,正在处理依赖注入相关操作。我有一张Section表,Section可以有父节点或没有父节点,若Section是父节点则需能列出其子Section。
Service代码
@Override public SectionDTO addSectionByParent(SectionDTO sectionDTO, Long parentId) { log.warn(" Checking the theParentSectionId:={}",parentId); Section parent = sectionRepository.findById(parentId).orElseThrow(() -> new RuntimeException("SectionParent not found exception")); Section section = sectionMapper.fromSectionDTO(sectionDTO); section.setParentSection(parent); Section addSection = sectionRepository.save(section); return sectionMapper.fromSection(addSection); }
Controller代码
Get请求方法
@GetMapping("/newa/{varId}") public ModelAndView newSectionByParentId(@PathVariable Long varId){ ModelAndView mav = new ModelAndView("detail/forma"); SectionDTO sectionDTO = new SectionDTO(); SectionDTO sectionParent = sectionService.showSection(varId); mav.addObject("detail",sectionDTO); mav.addObject("pro",sectionParent); return mav; }
Post请求方法
@PostMapping("/savingx") public String savingx(@ModelAttribute("section") @Valid SectionDTO sectionDTO, BindingResult bindingResult, @RequestParam(value = "parentId", required = false) Long parentId){ SectionDTO sectionParent = sectionService.showSection(parentId); String returnValue; if (bindingResult.hasErrors()) { return "project/forma"; } System.out.println("******************* parentId : "+ parentId); if (sectionParent != null) { sectionDTO.setParentId(sectionParent.getParentId()); sectionService.addSectionByParent(sectionDTO, sectionParent.getProductId()); } returnValue = "redirect:/product/detail/by/parent/{sectionId}"; return returnValue; }
出现的错误
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.
问题分析
1. 核心逻辑错误引发异常
- Post方法
savingx中,调用sectionService.addSectionByParent时传入的第二个参数是sectionParent.getProductId(),但该方法需要的是父Section的ID,而非ProductId。这个错误会导致sectionRepository.findById(parentId)找不到对应父节点,抛出RuntimeException,由于没有配置全局异常处理器,Spring返回默认的Whitelabel错误页。 sectionDTO.setParentId(sectionParent.getParentId());逻辑错误:你需要将当前Section的父节点设为传入的parentId对应的节点,应该设置为parentId,而非父节点的父节点ID。
2. 跳转路径无效
返回的跳转路径redirect:/product/detail/by/parent/{sectionId}中的{sectionId}是占位符,Spring不会自动替换为实际创建的Section ID。需先获取创建后的节点ID再拼接路径,示例:
SectionDTO savedSection = sectionService.addSectionByParent(sectionDTO, parentId); returnValue = "redirect:/product/detail/by/parent/" + savedSection.getId();
3. 未处理的空值风险
@RequestParam(value = "parentId", required = false)允许parentId为null,但如果showSection方法内部是通过findById(parentId).orElseThrow()实现的,parentId为null时会直接抛出异常。- 当
bindingResult.hasErrors()时返回的视图是"project/forma",但Get请求返回的是"detail/forma",若project/forma视图不存在,会引发视图找不到的错误。
4. 日志排查建议
开启Spring Boot的debug日志,或在showSection等关键方法内增加日志输出,就能看到具体异常信息,而非仅显示默认错误页。
内容的提问来源于stack exchange,提问作者Sany
相关产品推荐
相关产品推荐

