JavaScript Escaping Form Values

2019-09-08 06:57发布

问题:

I know there are a lot of JavaScript escaping questions, but nothing seemed to fit my needs.

I have textarea elements being dynamically displayed on a JSP. In the case of invalid form submits, I need to repopulate these fields with the values the user entered. I am doing this like so (note: simplified version):

var textareaBox = document.getElementById("myTextArea");
if (textareaBox) {
    textareaBox.value = '${myForm.myValue}';
}

Everything works fine until the user enters a value in the box that contains special characters. I've tried using the escape and unescape JavaScript functions individually and combined to no avail.

Does anyone know how I can handle these special character values? Note that I obviously do not want the escaped text in the textarea as this would not look good to users.

回答1:

Use JSTL's <c:out> tag to escape it and assign it as innerHTML of the text area:

textareaBox.innerHTML = '<c:out value="${myForm.myValue}" />';

But why don't you just display it in textarea's body directly without the need for JS?

<textarea id="myTextArea"><c:out value="${myForm.myValue}" /></textarea>

The <c:out> (and its EL function counterpart fn:escapeXml()) escapes XML special characters.

See also:

  • Not able to display special characters properly in a JSP page