Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

javax.script: Save state/scope between eval()s

 
Vidar Ramdal
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing a web console app which runs JavaScript on the server. The web console allows the user to input a line of JavaScript, and have it evaluated by the server side script engine.

The server side code looks like this:

This works, but I'm unable to persist variables between eval() calls.
When the user assigns a javascript variable in one line, the variable is not available on next eval().

Example:
User posts var laks = "mat";
Then laks.length;

I would like this to return 3, but I'm getting ReferenceError: "laks" is not defined. It seems the "laks" variable is not around the second time eval() is called.
Makes sense, in a way, but how can I accomplish what I want?
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you using the same ScriptEngine instance for all method calls? You should use the same one, and put it in the Session, to ensure there is one for each user.
Output:
null
3
 
Vidar Ramdal
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the same ScriptEngine instance is reused between requests.
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then it should reuse that engine, and its state. As you can see from the code I've edited it evaluates laks.length just fine in the second call to eval.
 
Vidar Ramdal
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Then it should reuse that engine, and its state. As you can see from the code I've edited it evaluates laks.length just fine in the second call to eval.


You're right, when I run your code as a testcase (through JUnit), it works as expected. The engine implementation returned by manager.getEngineByName("js") is a com.sun.script.javascript.RhinoScriptEngine.

However, I get a different implementation of the ScriptEngine in my web server environment. Looks like that implementation doesn't keep variables. Have to look into that, I guess.

Thanks for the help, it's good to know I wasn't too far off.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic