I have a user form. If the user types in a string with '
or "
as part of it I have no problem. The form is submitted and saved correctly to the database. My problem is when I reload the page (all entries can be modified and are loaded into a list in the JSP before being displayed). On loading the page I get an error saying:
missing ) after argument list 'Caroline's message', \n
What do I need to do to escape this string for displaying it on the frontend?
Here is the code I am using on the frontend to read in the data and store it in a JavaScript object. I am not fully sure where I need to escape. The field causing the problem is c.getComName:
communications[<%=i%>][1] = new CommObject('<%=c.getComId()%>', '<%=c.getComName()%>');
UPDATED WITH HTML GENERATED:
communications[0][1] = new CommObject('101', 'Caroline's Message');
I prefer to avoid scriptlets in the middle of my page and was having to use them (increasingly often) to escape strings when used in JavaScript code. I wanted an Expression Language (EL) way of escaping the strings. I created a very small custom taglib that I use for just this purpose:
Utilities.java:
mytaglib.tld:
And, in the JSP page:
You can use the JSTL escape function
fn:escapeXml()
to get rid of anomalies caused due to single quotes(`). The following example demonstrates the difference.For example:
RESULT
Use the Apache StringEscapeUtils.escapeJavaScript function.
When you return the HTML from the CommObject class add in the \" instead of the ' and before the name (e.g. Caroline's message)
Like this: return "\"" + comName + "\"";
fn:escapeXml does not work in JavaScript. It replaces ' with #&0039; still causing an error when the JavaScript is executed.
Only escaping in the JavaScript manner is correct: \'
The the Apache StringEscapeUtils.escapeJavaScript function does this for you. Creating a taglib for it greatly simplyfies matters.
Also we have very nice solution from Spring:
So, issue from the question of this post can be resolved in this way: