Spring Boot Thymeleaf Ajax 调用

皮特

我尝试从 Ajax 请求调用 Spring Boot 控制器:

 $('#female').click(function(){
   $('#analysisTable').DataTable( {
     "ajax": '/analyse/female'
   });
 });

这背后的想法是将列表加载到 js 数据表中。控制器看起来像:

@GetMapping("/analyse/female")
public List<GenderAnalysis> analysisByFemale(final Model model) {
    final List<GenderAnalysis> result = analyseDao.getAnalysisByGender(AnalyseDAO.Gender.Female);
    return result;
}

控制器工作正常。但是我收到 Thymeleaf 模板错误。每个响应都将通过 ThymeleafLayoutInterceptor 处理并将“正常”(不是 ajax)请求加载到模板中。

错误如下:

org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/analyse/female.html]")

我知道没有female.html 资源,我什至不会有。只需将原始列表提供给 ajax 调用。

即使使用模板,我也不知道如何使用 Spring Boot+Thymeleaf+Ajax。这可能是拦截器的处理问题吗?我能做什么?有人能帮忙吗?

银河战士

如果您想返回 JSON 而不是 Thymeleaf 模板,您应该:

1) 将控制器声明为 a@RestController而不仅仅是 a @Controller这将影响控制器类上的所有@GetMapping,@PostMapping@RequestMapping注释。

或者

2)声明方法作为@ResponseBody@GetMapping

@GetMapping("/analyse/female")
@ResponseBody
public List<GenderAnalysis> analysisByFemale() {
    return analyseDao.getAnalysisByGender(AnalyseDAO.Gender.Female);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章