Angular调用Spring Boot API获取HTML时部分属性丢失原因咨询
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.classis almost always on that list, butid,name, and customdata-*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. Customdata-*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 theXssFilterto includeid,name, and wildcard patterns fordata-*attributes.Customize or Disable Thymeleaf Sanitization
If you fully trust the source of your HTML content, you can disable Thymeleaf's sanitizer by settingspring.thymeleaf.sanitizer.enabled=falsein yourapplication.propertiesfile. 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

