I am working on my first JSP-servlet-DB application and I have problem with special characters <>. I need to view text from db in my jsp page, but some HTML elements typed into textarea caused trouble. I don't want to forbid inserting special chars, so I just decided to escape them...like this:
String text = textFromDB.replaceAll("<", "& lt;"); //used space in & lt; otherwise it shows escaped in here:)
then use it somewhere in my jsp <%= text %>
Problem is that < is not escaped, text in my page shows & lt; still
...strangely enough escaping & with & amp; works, but not <,>
Thanks for any suggestion.
//developing in eclipse + tomcat 7
Using scriptlets is out-of-date by almost 10 years. 10 years! A whole decade! I would say that it's high time that you familiarize yourself with the JSTL and EL. The longer you wait, the harder the transition will be.
I know I am not doing it in a proper way, but I am quite new into whole servlets-jsp thing. I wanted to learn about JSTL right after finishing my current project and then rewrite it without using scriptlets (because of gaining some practice). So please if you have any idea about my question, let me know. Thanks.
There is little benefit of writing your own custom HTML/XML escape program when it is built into JSTL. JSP and JSTL are made specifically to help you over the hurtles of converting data to HTML.
Using java scriptlets within JSP is considered a bad practice. While I understand the need for practice ... why a BAD practice? When Bear recommends not to do it, he's not steering you wrong.
If you want to practice writing code, why not make your HTML escape program a helper class? Then you can write it in pure java, without having to escape the characters you're trying to escape in the HTML in JSP. (And I made that sentence purposely confusing - it's a metaphor for what you're trying to do in JSP).
In preparing for battle I have always found that plans are useless, but planning is indispensable. -- Dwight D. Eisenhower
Joined: Aug 27, 2010
The Apache Commons library has excellent escape utilities.
Thank you all for your answers, now I'll figure it out I hope.
To answer why I don't use JSTL....well I thought it would too much of theory to learn servlets, jsp and jstl at once. I wanted to start practicing at least some of those technologies. But once I'm done with my first project, I'll abandon scriptlets. I promise:-)