How to implement a possibility for user to post some html-formatted data in a safe way?

前端 未结 2 1807
庸人自扰
庸人自扰 2020-11-27 22:14

I have a textarea and I want to support some simplest formatting for posted data (at least, whitespaces and line breaks).

How can I achieve this? If I w

2条回答
  •  北海茫月
    2020-11-27 22:20

    Use a HTML parser which supports HTML filtering against a whitelist like Jsoup. Here's an extract of relevance from its site.

    Sanitize untrusted HTML

    Problem

    You want to allow untrusted users to supply HTML for output on your website (e.g. as comment submission). You need to clean this HTML to avoid cross-site scripting (XSS) attacks.

    Solution

    Use the jsoup HTML Cleaner with a configuration specified by a Whitelist.

    String unsafe = 
          "

    Link

    "; String safe = Jsoup.clean(unsafe, Whitelist.basic()); // now:

    Link

    And then to display it with whitespace preserved, apply CSS white-space: pre-wrap; on the HTML element where you're displaying it.

    No all-in-one JSF component comes to mind.

提交回复
热议问题