在 Java 中用 Rhino 解析和替换 Javascript 标识符
假设我让用户使用 Javascript 编写条件,用户可以编写条件来执行测试并返回 true 或 false。例如:
INS>5 || ASTO.valueBetween(10,210)
我想查找用户编写的脚本中使用了哪些变量。我试图找到一种方法来获取 Java 中的标识符名称。 Rhino 库没有多大帮助。然而我发现通过处理异常我可以获得所有标识符。那么这个问题就解决了。
所以一切都很好,但有一个小问题。如何用数字标识符替换这些标识符?例如,INS
应为 _234
,ASTO
应为 _331
。
INS
和 ASTO
等是我数据库中的实体。我想替换它们,因为名称可能会改变。我可以使用替换来做到这一点,但这并不容易,因为:
- 它应该是可逆的。例如,
ASTO
到_234
,然后_234
再次到ASTO
。 - 将
_23
替换为MPLAH
也可能会替换_234
。这可以通过正则表达式以某种方式修复。 - 如果
_23
在评论部分怎么办?很少发生,但有可能/* _23 fdsafd ktl */
。也应该更换。 - 如果它是一个函数的名称怎么办?例如
_32() {}
。也很少见,但不应该被替换。 - 如果它包含在
""
或''
中怎么办?
我确信还有更多的案例。有什么想法吗?
Suppose I let the user to write a condition using Javascript, the user can write conditions to perform a test and return true or false. E.g.:
INS>5 || ASTO.valueBetween(10,210)
I want to find which variables are used in the script that the user wrote. I tried to find a way to get the identifier names in Java. The Rhino library didn't help a lot. However I found that via handling exceptions I could get all the identifiers. So this problem is solved.
So everything is great, but there is one little problem. How can I replace these identifiers with a numeric identifier? E.g. INS
should be _234
and ASTO
should be _331
.
INS
and ASTO
etc are entities in my database. I want to replace them, because the name may change. I could do it using a replace but this isn't easy because:
- It should be reversible. E.g.
ASTO
to_234
and_234
toASTO
again. - Replacing
_23
withMPLAH
may also replace_234
. This could be fixed with regexp somehow. - What if
_23
is in a comment section? Rare to happen, but possible/* _23 fdsafd ktl */
. It should also be replaced. - What if it is a name of a function? E.g.
_32() {}
. Also rare, but it shouldn't be replaced. - What if it is enclosed in
""
or''
?
I am sure that there are a lot more cases. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Parhs - 你真正需要的是一个 JavaScript 解析器。基本上,您将重新实现 Rhino 的各个部分,尽管从理论上讲,Rhino 可能已经有钩子来完成您需要的操作(我不熟悉它,所以不确定);或者您可以扩展 Rhino,因为它的源代码 100% 来自 Mozilla。另一个可能值得关注的方向是 Google 的 GWT。
Parhs - what you really need is a JavaScript parser. Basically, you will be re-implementing pieces of Rhino although it's theoretically possible that Rhino already has hooks to do what you need (I'm not familiar with it so not sure); or you can extend Rhino since its source is 100% avialable from Mozilla. Another possible direction to look at is Google's GWT.