| 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: 19216
|
|
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
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: 19216
|
|
|
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.
|
 |
 |
|
|
subject: javax.script: Save state/scope between eval()s
|
|
|