Evaluating javascript using a java code

java, javascript, web

Solution

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

Problem

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

Original source