Where is the proper place to escape quotes in Play

2019-03-31 20:05发布

问题:

I have the following flow:

  1. A user is presented with a form.
  2. He fills in the form fields, and submits to the controller, which persists this to the DB
  3. On another page, the Controller gets this record from the DB, and passes it to the view
  4. 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.