使用java代码评估javascript [英] Evaluating javascript using a java code

查看:110
本文介绍了使用java代码评估javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能不实用,但我把它作为一项任务。
我在java中打开了一个ServerSocket。现在我想读取一个包含html和javascript的文件,并将javascript结果输出到浏览器。所以这样,我会评估服务器端的javascript。所以我想要评估
里面的内容。

This might not be practical, but I have it as a task. I have an opened ServerSocket in java. Now I want to read a file which contains html and javascript, and output the javascript result to the browser. So this way, I would be evaluating the javascript on the server side. So I want what is inside to be evaluated.

我试过这个测试,它有效,但它有一些问题,例如它打印消息到System.out中。和engine.eval(print('Welocme to java worldddd'));不会返回一个String,以便我可以将它输出到套接字的输出流:

I tried this to test, it worked but it has some issues, for example it prints the message to System.out. And engine.eval("print('Welocme to java worldddd')"); does not return a String so that I can output it to the outputstream of the socket:

import javax.script.*;
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
try {
     // evaluate JavaScript code from String
     engine.eval("print('Welocme to java worldddd')");
     //engine.eval("a");
} catch (ScriptException ex) {
     Logger.getLogger(doComms.class.getName()).log(Level.SEVERE, null, ex);
}


推荐答案

你可以得到输出脚本(在JavaScript中用 print()打印的内容)通过在 ScriptContext上设置编写器

You can get the output of the script (what is printed with print() in JavaScript) by setting the writer on the ScriptContext:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
ScriptContext context = engine.getContext();
StringWriter writer = new StringWriter();
context.setWriter(writer);

engine.eval("print('Welocme to java worldddd')");

String output = writer.toString();

System.out.println("Script output: " + output);

这篇关于使用java代码评估javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆