2

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 ?

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
brot
  • 35
  • 2
  • 6

5 Answers5

7

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).

Tamas Czinege
  • 118,853
  • 40
  • 150
  • 176
  • Thanks, that was exactly what i was looking for. Also, i will try to implement the escaping in the frontend, not the db. – brot Apr 27 '09 at 11:20
4

The usual practice is the other way around. We save whatever is in the textarea, and use escapeXML attribute of a <c:out> tag when showing it. This way everything CSS, HTML tags all will be treated as simple text.

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
2

You can also use JSTL function: fn:escapeXml().

 <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
 ...   
 <input type="hidden" name="htmlCode" value="${fn:escapeXml(htmlCode)}"/>
pawelsto
  • 75
  • 5
0

You can also use JSTL core library.

c:out has escapeXml on as default.

Examples:

<c:out value="${tp.title}" />

<c:out value="${product.listPrice}" escapeXml="false" /> //if you want turn off

This approach let you do escaping in presentation layer as other people recommended.

Meow
  • 18,371
  • 52
  • 136
  • 180
0

You need to escape the HTML for security purposes, e.g. to prevent things like Cross Site Scripting attacks (XSS).

Search for Cross site scripting on Google/Stack Overflow for more details.

There will be several open source Servet Filters which will do this for you.

e.g. see here for an explanation

A_M
  • 7,693
  • 6
  • 33
  • 37
  • You mean something like this ? http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project Sounds great, and i dont loose the feature that users can use things like "" and "" – brot Apr 27 '09 at 10:52