Thymeleaf渲染index.html时出现SAXParseException页面无法显示
我来帮你一步步排查和解决这个问题:
1. 移除Controller中的@ResponseBody注解
你当前的Controller方法同时使用了@ResponseBody和返回ModelAndView,这是核心错误之一:
@GetMapping("/") // 必须去掉这个注解! // @ResponseBody public ModelAndView getEvaluatePage() { ModelAndView mv=new ModelAndView(); mv.setViewName("index"); return mv; }
@ResponseBody会告诉Spring把返回的ModelAndView对象直接序列化为JSON/XML返回给前端,而不是让Thymeleaf视图解析器去渲染模板页面。移除这个注解后,Spring才会正确调用Thymeleaf处理你的index.html模板。
2. 修复HTML中的标签语法错误(符合XML规范)
Thymeleaf默认使用严格的XML解析规则,所以HTML中的任何标签不闭合、嵌套错误都会触发SAXParseException。我检查到你的代码里有几处明显的标签问题:
问题1:错误的HTML命名空间
把html标签的命名空间从错误的http://www.w3.org/1999/html改为标准的XHTML命名空间,同时添加Thymeleaf的命名空间(方便后续使用Thymeleaf语法):
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
问题2:未正确闭合/嵌套的<span>标签
- file-upload-info区域:第一个
<span>没有闭合,导致标签嵌套混乱:
<!-- 原错误代码 --> <div class="col-md-12 alert alert-info" role="alert" style="display: none;" id="file-upload-info"> <span class="glyphicon glyphicon glyphicon-file" aria-hidden="true"> <span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Överlämnar valideringsdata till Watson... </span> </div> <!-- 修复后 --> <div class="col-md-12 alert alert-info" role="alert" style="display: none;" id="file-upload-info"> <span class="glyphicon glyphicon-file" aria-hidden="true"></span> <span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Överlämnar valideringsdata till Watson... </div>
- file-upload-error区域:多了一个无匹配的
</span>标签,同时建议添加alert-danger类让错误提示样式更合理:
<!-- 原错误代码 --> <div class="col-md-12 alert" role="alert" style="display: none;" id="file-upload-error"> Watson kunde inte ta emot valideringsfilen</span></div> <!-- 修复后 --> <div class="col-md-12 alert alert-danger" role="alert" style="display: none;" id="file-upload-error"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> Watson kunde inte ta emot valideringsfilen </div>
问题3:确保所有自闭合标签符合XML规范
虽然现代浏览器允许省略自闭合标签,但Thymeleaf的XML解析器要求严格,比如<input>标签要写成<input ... />,你的代码里的<input>已经是自闭合的,这部分没问题,但要保持一致。
3. 验证Thymeleaf依赖配置(确保正确引入)
确认你的pom.xml(Maven)或build.gradle(Gradle)中已经正确引入Thymeleaf依赖,以Maven为例:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
Spring Boot会自动配置Thymeleaf视图解析器,默认会从resources/templates/目录加载模板,你的index.html位置是正确的。
总结
按照以上步骤修复后,重新启动应用:
- 移除
@ResponseBody让Spring正确渲染视图 - 修复所有HTML标签的语法错误,符合XML规范
- 确认Thymeleaf依赖正确引入
这样就能解决SAXParseException异常,让页面正常渲染了。
内容的提问来源于stack exchange,提问作者Genesis

