File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Other JSE/JEE APIs and the fly likes javax.script: Save state/scope between eval()s Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "javax.script: Save state/scope between eval()s" Watch "javax.script: Save state/scope between eval()s" New topic
Author

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

Vidar Ramdal
Greenhorn

Joined: Aug 31, 2009
Posts: 3
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

Joined: Oct 27, 2005
Posts: 19692
    
  20

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Vidar Ramdal
Greenhorn

Joined: Aug 31, 2009
Posts: 3
Yes, the same ScriptEngine instance is reused between requests.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19692
    
  20

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

Joined: Aug 31, 2009
Posts: 3
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: javax.script: Save state/scope between eval()s