Spring Boot集成Thymeleaf处理Angular登录请求遇模板解析错误
看起来你遇到的问题是引入Thymeleaf依赖后,Spring MVC错误地将你的@RestController接口请求当成了视图渲染请求,试图去寻找名为logging的Thymeleaf模板,但实际上你期望的是返回JSON数据。下面是具体的原因分析和解决办法:
问题根源
当你在pom.xml中引入Thymeleaf依赖后,Spring Boot会自动配置Thymeleaf视图解析器。虽然你的控制器标注了@RestController(该注解包含@ResponseBody,会自动将返回对象序列化为JSON),但可能因为请求格式不匹配或者配置的小问题,导致Spring没有正确识别这是一个Rest接口请求,转而尝试渲染视图。
解决步骤
1. 确保Angular请求的Content-Type正确
你的Angular代码中使用http.post发送请求时,需要明确设置请求头的Content-Type为application/json,否则Spring无法正确解析@RequestBody中的JSON数据,可能触发视图解析逻辑。补全你的httpOptions:
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
2. 显式确认@RestController的有效性
虽然@RestController已经包含@ResponseBody,但如果遇到配置冲突,可以在你的login方法上额外添加@ResponseBody注解,强制Spring将返回的HashMap序列化为JSON:
@RestController @RequestMapping(path = "/api") public class CustomerController { @Autowired private CustomerService customerService; @RequestMapping(value = "/logging", method = RequestMethod.POST) @ResponseBody // 显式添加该注解 public HashMap login(@RequestBody Customer cus) { HashMap map = customerService.validateCustomer(cus); return map; } }
3. 检查是否存在请求映射冲突
确保没有其他@Controller类的请求映射和/api/logging重复,避免Spring路由到错误的控制器方法。
4. 验证Thymeleaf配置(可选)
如果上述方法无效,可以检查application.properties中的Thymeleaf配置,确保它不会干扰Rest接口:
# 默认配置,无需修改,确认即可 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.enabled=true
这里的配置是针对视图渲染的,你的Rest接口不应该触发这些逻辑,所以只要前面的步骤正确,这个配置不会有影响。
额外建议
可以用Postman直接测试你的/api/logging接口,发送JSON格式的请求体,确认接口本身是否正常返回JSON数据,这样可以排除Angular端的问题,聚焦到Spring Boot的配置上。
内容的提问来源于stack exchange,提问作者DESH

