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

查看:28
本文介绍了使用 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')");不返回字符串以便我可以将其输出到套接字的输出流:

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);
}

推荐答案

您可以通过将 writer 设置在 <代码>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天全站免登陆