[Java]
Package jason. Rhino. study;
Import java. io. File;
Import java. io. FileReader;
Import java. io. IOException;
Import org. mozilla. js. Context;
Import org. mozilla. js. ContextAction;
Import org. mozilla. js. ContextFactory;
Import org. mozilla. js. ImporterTopLevel;
Import org. mozilla. js. Scriptable;
Public class ScriptManager {
Private Scriptable scope = null;
Private String beanName = null;
Public ScriptManager (final String beanName, final Object beanObj ){
This. beanName = beanName;
ContextFactory. getGlobal (). call (new ContextAction (){
@ Override
Public Object run (Context cx ){
Scope = new ImporterTopLevel (cx );
Scriptable wrapped = Context. toObject (beanObj, scope );
Scope. put (beanName, scope, wrapped );
Return null;
}
});
}
Public Object exec (final String script ){
ContextFactory. getGlobal (). call (new ContextAction (){
@ Override
Public Object run (Context cx ){
Return cx. evaluateString (scope, script, null, 0, null );
}
});
Return null;
}
Public void exec (File scriptFile) throws IOException {
FileReader in = new FileReader (scriptFile );
StringBuffer strBuf = new StringBuffer ("");
Char [] buf = new char [2048];
Int length =-1;
While (length = in. read (buf ))! =-1 ){
StrBuf. append (buf, 0, length );
}
String scriptStr = strBuf. toString ();
In. close ();
In = null;
StrBuf = null;
Buf = null;
Exec (scriptStr );
}
Public void destroyBean ()
{
Scope. delete (this. beanName );
}
Public static void main (String [] args) throws Exception {
CheckDataTampered check = new CheckDataTampered ();
ScriptManager js = new ScriptManager ("check", check );
File file = new File ("./src/jason/Rhino/study/test. js ");
If (file. exists ()){
Js.exe c (file );
} Else {
System. out. println ("file not found ");
}
}
}
[Java]
Package jason. Rhino. study;
Import java. util. ArrayList;
Import java. util. List;
Public class CheckDataTampered {
Private List <String> lsFields = new ArrayList <String> ();
Public void setProtectedField (String fieldName ){
LsFields. add (fieldName );
}
Public void printOut (){
For (String field: lsFields ){
System. out. println (field );
}
}
}
Test. js
[Javascript]
Check. setProtectedField ("111111111 ");
Check. setProtectedField ("222222222 ");
Check. setProtectedField ("333333333 ");
Check. setProtectedField ("444444444 ");
Check. setProtectedField ("555555555 ");
Check. setProtectedField ("666666666 ");
Check. printOut ();
Author: javalover_yao