title: How to sanitize HTML code to prevent XSS attacks in Java or JSP?
body: <p>I'm writing a servlet-based application in which I need to provide a messaging system. I'm in a rush, so I choose <a href="http://ckeditor.com/" rel="noreferrer">CKEditor</a> to provide editing capabilities, and I currently insert the generated html directly in the web page displaying all messages (messages are stored in a MySQL databse, fyi). CKEditor already filters HTML based on a white list, but a user can still inject malicious code with a POST request, so this is not enough.</p>
  
  <p>A good library already exists to prevent XSS attacks by filtering HTML tags, but it's written in PHP: <a href="http://htmlpurifier.org/" rel="noreferrer">HTML Purifier</a></p>
  
  <p>So, <strong>is there a similar mature library that can be used in Java</strong> ?
  A simple string replacement based on a white list doesn't seem to be enough, since <strong>I'd like to filter malformed tags too</strong> (which could alter the design of the page on which the message is displayed).</p>
  
  <p>If there isn't, then how should I proceed? An XML parser seems overkill.</p>
  
  <p><em>Note: There are a lot of questions about this on SO, but all the answers refer to filter ALL HTML tags: I want to keep valid formatting tags.</em></p>