views:

1419

answers:

4

I am of course familiar with the java.net.URLEncoder and java.net.URLDecoder classes. However, I only need HTML-style encoding. (I don't want ' ' replaced with '+', etc). I am not aware of any JDK built in class that will do just HTML encoding. Is there one? I am aware of other choices (for example, Jakarta Commons Lang StringEscapeUtils, but I don't want to add another external dependency to the project where I need this.

I'm hoping that something has been added to a recent JDK (aka 5 or 6) that will do this that I don't know about. Otherwise I have to roll my own.

A: 

No. I would recommend using the StringEscapeUtils you mentioned, or for example JTidy (http://jtidy.sourceforge.net/multiproject/jtidyservlet/apidocs/org/w3c/tidy/servlet/util/HTMLEncode.html).

simon
A: 

Please don't roll your own. Use Jakarta Commons Lang. It is tested and proven to work. Don't write code until you have to. "Not invented here" or "Not another dependency" is not a very good base for deciding what to choose / write.

bitboxer
In general, I would agree with you. But I'm adding an additional diagnostic output to something that is in production. Lawyers get involved when a new 3rd party dependency is added. It's not as trivial as you think. Otherwise I would not have asked the question!
Eddie
+3  A: 

There isn't a JDK built in class to do this, but it is part of the Jakara commons-lang library.

String escaped = StringEscapeUtils.escapeHTML(stringToEscape);

Check out the JavaDoc

Adding the dependency is usually as simple as dropping the jar somewhere, and commons-lang has so many useful utilities that it is often worthwhile having it onboard.

John Case
As I said in a comment to another answer, adding a dependency is *NOT* as simple as dropping a JAR somewhere. Lawyers need to go over the license for the 3rd party JAR, installers need to be changed, and so on. It's not always trivial.
Eddie
+1  A: 

Apparently, the answer is, "No." This was unfortunately a case where I had to do something and couldn't add a new external dependency for it -- in the short term. I agree with everyone that using Commons Lang is the best long-term solution. This is what I will go with once I can add a new library to the project.

It's a shame that something of such common use is not in the Java API.

Eddie