It is an open-source project that supports calling a script in a Java application and directly accessing Java objects and methods.
For details, see blog http://www.cnblogs.com/archie2010/archive/2011/07/12/2104403.html.
BSF script manager registers a bean and executes a script using the Script Engine (bsfengine) to obtain bean content.
It can also modify the content of the bean and, if necessary, persist the modified bean.
Code:
Bean user. Java
public class User implements Serializable {
private int id;
private String uname;
private String address;
//---------------
Test class bsftestchnagebean. Java
/**
* Js scripts change bean content
* @ Author Archie
*
*/
Public class bsftestchnagebean {
Public static void main (string [] ARGs ){
// Script script (JavaScript)
String script =
"Function dealbean () {STR = BSF. lookupbean ('U'); map = BSF. lookupbean ('map'); map. put ('amount', 'amount field of the form! '); Str. uname = 'Modified name ';}";
Try {
Bsfmanager = new bsfmanager ();
// BSF Script Engine
Bsfengine = bsfmanager. loadscriptingengine ("JavaScript ");
/**
* Bean
*/
User u = new user ();
U. setid (1 );
U. setuname ("Archie ");
U. setaddress ("shangehai ");
Bsfengine. eval ("JavaScript", 0, 0, script );
Hashmap <string, Object> map = new hashmap <string, Object> ();
// Bsfmanager registers Bean
Bsfmanager. registerbean ("u", U );
Bsfmanager. registerbean ("map", MAP );
// Execute the script by the script engine (comment this line, then the bean will not be processed by BSF)
Object result = bsfengine. eval ("JavaScript", 0, 0, "dealbean ();");
System. Out. println (Map. Get ("amount "));
System. Out. println ("name after Bean change:" + U. getuname ());
} Catch (bsfexception e ){
E. printstacktrace ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}
Running result:
Name after Bean change: name after modification
Amount field of the form!
The content of the map and user objects has been changed.
You can also directly call the method for long-running bean registration.
For example:
public static boolean executeSQL(String sql) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBManager.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.execute();
} catch (SQLException e) {
Log.error(e.getMessage());
return false;
} finally {
DBManager.close(pstmt, conn);
}
return true;
}
You can execute SQL directly in the script.