开发者

Embedding HTML within XHTML

开发者 https://www.devze.com 2023-02-16 16:31 出处:网络
I have a JSF page which is outputting XHTML (from a facelet). One of the fields h开发者_JS百科as user-generated HTML which is causing parsing errors in my web browser (Safari).

I have a JSF page which is outputting XHTML (from a facelet). One of the fields h开发者_JS百科as user-generated HTML which is causing parsing errors in my web browser (Safari).

I understand that this is because XHTML is strict and follows the rules of XML, unlike HTML. What is the best way of embedding this HTML while avoiding fatal parsing errors?

One thing I've thought of is replacing all instances of say <br> with <br />, but there's got to be a better solution than that.

Here's another example of something I need to embed:

This is my sample text.<br>The address is Wind & Fire.

Notice here that the line break tag needs to be self-enclosing, and the ampersand should probably be &aamp;


Use a HTML parser which returns well formed HTML syntax. I can recommend Jsoup for this.

Kickoff example:

String userHtml = "foo<br>bar&baz";
String wellFormedHtml = Jsoup.parse(userHtml).body().html();
System.out.println(wellFormedHtml); // foo<br />bar&amp;baz

Just apply this once when you're about to process submitted user input.

Jsoup offers more advantages as well, such a Whitelist which you can use to strip out potential malicious HTML/JS code which can open XSS attack holes.

0

精彩评论

暂无评论...
验证码 换一张
取 消