问题
I have the following flow:
- A user is presented with a form.
- He fills in the form fields, and submits to the controller, which persists this to the DB
- On another page, the Controller gets this record from the DB, and passes it to the view
- The view captures it as a javascript variable:
var foo = '${user.bar}';
Now, if the user enters this string in the form:
I have a quote - ' - very dangerous
then the quote is passed through all the way to the DB and back, and results in a corrupt javascript statement:
var foo = 'I have a quote - ' - very dangerous';
What is the best place to escape this character, and how? I don't want to do it manually for each template usage, it's tedious and error prone.
回答1:
The data is the data. If it contains a quote, it contains a quote, and it has to be stored that way in the database. You need to escape the quote when using this String a a JavaScript string literal.
You could use Apache commons-lang StringEscapeUtils.escapeECMAScript()
method to do that, or you could encode your Java objects into JSON strings, and parse the JSON string in your JavaScript code.
来源:https://stackoverflow.com/questions/10928642/where-is-the-proper-place-to-escape-quotes-in-play-framework