How can you run Javascript using Rhino for Java in a sandbox?

前端 未结 6 871
梦毁少年i
梦毁少年i 2020-12-04 08:50

Part of our java application needs to run javascript that is written by non-developers. These non-developers are using javascript for data formatting. (Simple logic and str

6条回答
  •  爱一瞬间的悲伤
    2020-12-04 09:33

    If you are looking for pure JavaScript functions only, here is a solution basing on JDK embedded Rhino library without importing any 3rd-parties libraries:

    1. Find out JavaScript script engine factory class name by ScriptEngineManager#getEngineFactories
    2. Load script engine factory class in a new class loader, in which JavaMembers or other related classes will be ignored.
    3. Call #getScriptEngine on loaded script engine factory and eval scripts on returned script engine.

    If given script contains Java script, class loader will try to load JavaMembers or other classes and trigger class not found exceptions. In this way, malicious scripts will be ignored without execution.

    Please read ConfigJSParser.java and ConfigJSClassLoader.java files for more details:

    https://github.com/webuzz/simpleconfig/tree/master/src/im/webuzz/config

提交回复
热议问题