java程序中运行js脚本

我怎样把我在java程序中得到的一组参数(例如一个数组)作为参数传递到一个javascript的脚本程序中去?


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

   

public class ExecJs {

 

    /**

     * 记录日志类

     */

    private Logger log = Logger.getLogger(ExecJs.class);

 

    /**

     * 后置处理,执行js脚本

     * @param js

     * @throws Exception

     */

    public void execJs(String js, Map<String,Object> map) throws Exception {

        if (log.isDebugEnabled()) {

            log.debug("execJs js : " + js);

            Iterator<Entry<String, Object>> it = map.entrySet().iterator();

            while (it.hasNext()) {

                Entry<String, Object> entry = (Entry<String, Object>) it.next();

                log.info("EXECJS MAP : " + entry.getKey() + "---" + entry.getValue());

            }// end while

        }// end if

        if ("".equals(js) || js == null) {

            log.info("EXECJS ERROR : JAVASCRIPT CONTENT IS NULL");

        } else if(map == null || map.size()<=0){

            log.info("EXECJS ERROR : MAP CONTENT IS NULL");

        } else {

            // 获取脚本引擎

            ScriptEngineManager mgr = new ScriptEngineManager();

            ScriptEngine engine = mgr.getEngineByName("javascript");

            // 绑定数据

            ScriptContext newContext = new SimpleScriptContext();

            Bindings bind = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

            bind.putAll(map);

            try {

                engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);

                engine.eval(js);

            } catch (Exception e) {

                log.info("EXECJS EXCEPTION : EXECUTE JAVASCRIPT EXCEPTION", e);

                throw (e);

            }// end try

        }// end if

    }

}

   

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-10-29
使用xml或者json传递追问

并不太知道这个==,能麻烦详细说说吗

追答

你上网查一查jackson或者fastjson的资料看看吧,这个一会儿也说不清楚,网上找点完整的教程看看效果要好一些。

第2个回答  2015-10-29
JSON比较简单。
相似回答