Play Framework中适合的地方放弃报价? [英] Where is the proper place to escape quotes in Play Framework?
问题描述
我有以下流程:
- 向用户显示一个表单。
- 他填写表单域,并提交给控制器,将其持续到DB
- 在另一个页面上,Controller从DB获取此记录,并将其传递给视图
- 该视图将其捕获为JavaScript变量:
var foo ='$ {user.bar}';
- 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
然后报价一路传递到DB并返回,并导致一个损坏的 javascript语句:
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.
推荐答案
数据是数据。如果它包含一个报价,它包含一个报价,它必须以这种方式存储在数据库中。当使用这个String一个JavaScript字符串文字时,你需要转义引号。
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.
您可以使用Apache commons-lang StringEscapeUtils.escapeECMAScript()
方法来执行此操作,也可以对Java对象转换成JSON字符串,并解析JavaScript代码中的JSON字符串。
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.
这篇关于Play Framework中适合的地方放弃报价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!