I am learning JSP and Java at the moment and wrote a (very) simple guestbook to get started with JSP. But i want to ensure that noone can use CSS, so i need to strip the HTML code before saving it to my mySQL database. I already searched here and found the ‘
PreparedStatement pStmt = conn.prepareStatement('INSERT INTO test VALUES (ID, ?, ?)'); pStmt.setString(1, request.getParameter('sender')); pStmt.setString(2, request.getParameter('text')); pStmt.executeUpdate();
So what would be the proper way to do this ?
Short answer: have a look at org.apache.commons.lang.StringEscapeUtils.escapeHtml().
More detailed answer: Escaping HTML is the job of the presentation code, not the database code. What if for some reason, you want to display you data at some point in a non-web environment, such as a classic GUI? You will have to unescape the whole thing, otherwise it will display total garbage.
Just save the data as it is and make sure you escape everything you get from the user right before you display it (ok, maybe not numbers stored as numbers, but you get the idea).
If you’re using AJAX, you can take this even further and only escape your strings in JavaScript (or use innerText).