Where is the proper place to escape quotes in Play Framework?

余生颓废 提交于 2020-01-01 07:02:33

问题


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.



来源:https://stackoverflow.com/questions/10928642/where-is-the-proper-place-to-escape-quotes-in-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!