You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用Spring Boot API获取HTML时部分属性丢失原因咨询

Why Your Angular 4/5 App Loses HTML Attributes When Fetching from Spring Boot APIs

Hey there, let's break down exactly why your Angular app is losing attributes like id, name, and data-* (while keeping class) when pulling HTML from your Spring Boot backend:

Common Causes

  • Spring Boot's Default HTML Sanitization
    Spring Boot (especially when paired with Spring Security or Thymeleaf) comes with built-in sanitization to guard against XSS attacks. By default, this sanitizer uses a whitelist of "safe" HTML attributes. class is almost always on that list, but id, name, and custom data-* attributes might get excluded unless explicitly allowed. This sanitizer automatically strips any attributes it doesn't recognize as safe before sending the HTML response.

  • Spring Security's XSS Protection Rules
    If you have Spring Security enabled, its XSS filter might be enforcing strict content rules. The default setup often errs on the side of caution, filtering out attributes that could be misused for scripting attacks. Custom data-* attributes, in particular, might be flagged as untrusted if not added to the filter's allowed attributes list.

  • Thymeleaf Template Engine Behavior
    If you're using Thymeleaf to render HTML responses, its default mode might be cleaning up your markup. Thymeleaf uses a parser that can strip attributes it deems non-standard or unsafe, especially in strict HTML5 mode. Even if you're returning static HTML files, if they're processed through Thymeleaf's pipeline, this sanitization can kick in.

Quick Fixes to Try

  • Adjust Spring Security's Sanitizer Whitelist
    If Spring Security is the culprit, modify your security configuration to add the missing attributes to the allowed list. For example, you can customize the XssFilter to include id, name, and wildcard patterns for data-* attributes.

  • Customize or Disable Thymeleaf Sanitization
    If you fully trust the source of your HTML content, you can disable Thymeleaf's sanitizer by setting spring.thymeleaf.sanitizer.enabled=false in your application.properties file. For a safer approach, create a custom sanitizer bean that explicitly allows your required attributes.

  • Return Raw HTML Directly
    Instead of using a template engine, have your Spring Boot controller return the HTML as a raw string with @ResponseBody. This skips any automatic sanitization that might happen during template processing.

内容的提问来源于stack exchange,提问作者user2340939

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:15:28