http://blog.csdn.net/xzyxuanyuan/article/details/8062887
The JDK1.6 version adds a new ScriptEngine class that allows the user to execute the JS code directly.
Invoking the JS code directly in Java
You cannot invoke the JS function defined in the browser and throw an exception prompt referenceerror: "Alert" is not defined.
|
Package Com.sinaapp.manjushri; Import Javax.script.ScriptEngine; Import Javax.script.ScriptEngineManager; Import javax.script.ScriptException; /** * Directly call JS code */ public class Scriptenginetest { public static void Main (string[] args) { Scriptenginemanager manager = new Scriptenginemanager (); ScriptEngine engine = Manager.getenginebyname ("javascript"); try{ engine.eval ("var a=3; var b=4;print (a+b); "); Engine.eval ("alert (\" JS alert\ ");"); Cannot invoke the JS function//Error defined in the browser, will throw the alert reference to an exception that does not exist }catch (scriptexception e) {e.printstacktrace ();}} } |
Output results: 7
Binding JS Variables in Java
When Engine.get (key) is called, NULL is returned if key is not defined
|
package Com.sinaapp.manjushri; Import javax.script.Bindings; Import Javax.script.ScriptContext; Import Javax.script.ScriptEngine; Import Javax.script.ScriptEngineManager; Import javax.script.ScriptException; public class ScriptEngineTest2 {public static void main (string[] args) {Scriptenginemanager manager = new SCRI Ptenginemanager (); ScriptEngine engine = Manager.getenginebyname ("javascript"); Engine.put ("A", 4); Engine.put ("B", 3); Bindings Bindings = engine.getbindings (Scriptcontext.engine_scope); try {///can only be double, using float and integer throws an exception Double result = (double) engine.eval ("A+b"); SYSTEM.OUT.PRINTLN ("result =" + result); Engine.eval ("C=a+b"); Double c = (double) engine.get ("C"); System.out.println ("c =" + C); } catch (Scriptexception e) {e.printstacktrace (); } } } |
Output:
result = 7.0
c = 7.0
Call the function in the JS file in Java, pass in the call parameter, and get the return value
The merge function in the JS file adds two parameters, a, B, and returns C.
|
Expression.js function merge (A, b) { c = A * b; return C; } |
Read the JS file in Java code, and parameter two parameters, then go back to return the value.
|
Package Com.sinaapp.manjushri; Import Java.io.FileReader; Import javax.script.Invocable; Import Javax.script.ScriptEngine; Import Javax.script.ScriptEngineManager; /** * Java calls and executes JS file, passes parameters, and activity return value * * @author Manjushri */Public class Scriptenginetest { public static void Main (string[] args) throws Exception { Scriptenginemanager manager = new Scriptenginemanager (); ScriptEngine engine = Manager.getenginebyname ("javascript"); String jsfilename = "Expression.js"; Read JS file filereader reader = new FileReader (jsfilename); Executes the specified script engine.eval (reader); if (engine instanceof invocable) { invocable invoke = (invocable) engine; Call the merge method and pass in two parameters //c = Merge (2, 3); Double c = (double) invoke.invokefunction ("merge", 2, 3); System.out.println ("c =" + C); } Reader.close (); }} |
Output Result:
c = 5.0
Java Invoke scripting language Note (Jython,jruby,groovy)
There are two ways
1.java SE 6 implements the JSR 223 specification
Java code:
[Java]
- Scriptenginemanager factory = new Scriptenginemanager ();
- Scriptenginemanager ScriptEngine = Factory.getenginebyname ("JavaScript"); or "JS"
- Scriptengine.eval (code); //execute a script, code is JS
Very handy for invoking scripts
2. You can use the scripting language itself to provide a means of integration with Java
Jython Integration
Using jsr223:
Prerequisites for downloading Jython's package, implemented jsr223
(Recommended to download on the official website, in the installation directory there are jython.jar,http://repo2.maven.org/maven2/org/python/jython/2.5.0/here, but there is no jsr223 in this package, See if there is no org.python.jsr223 in the package)
[Java]
- Scriptenginemanager factory = new Scriptenginemanager ();
- Scriptenginemanager ScriptEngine = factory.getenginebyname ("Python"); or "Jython."
- Scriptengine.eval (code);
With Pythoninterpreter, you can invoke the Exec (String code) method:
[Java]
- Pythoninterpreter interpreter = new Pythoninterpreter ();
- Interpreter.exec (code);
Accessing the database
Using JDBC:
[Python]
- From Oracle.jdbc.driver import oracledriver
- From java.sql import DriverManager
- Username = ' hr '
- Password = ' 123456 '
- url = ' Jdbc:oracle:thin: @localhost: 1521:xe '
- Driver = Oracledriver ()
- Drivermanager.registerdriver (Driver)
- conn = drivermanager.getconnection (URL, username, password)
- stmt = Conn.createstatement ()
- sql = "Select salary from EMPLOYEES t where t.salary<2300"
- rs = stmt.executequery (SQL)
- while (Rs.next ()):
- Print rs.getint (' salary ')
- Rs.close ()
- Stmt.close ()
Results:
2200
2100
2200
Using ZXJDBC:
[Python]
- From Com.ziclix.python.sql import Zxjdbc
- url = ' Jdbc:oracle:thin: @localhost: 1521:xe '
- Username = ' hr '
- Password = ' 123456 '
- drivername = ' Oracle.jdbc.driver.OracleDriver '
- Mysqlconn = Zxjdbc.connect (Url,username, Password,drivername)
- cursor = Mysqlconn.cursor ()
- Cursor.execute ("select last_name from EMPLOYEES t where t.salary<2300");
- #print Cursor.fetchone ()
- List = Cursor.fetchall ()
- For record in list:
- print "name:" +record[0]
- #print Cursor.description[0]
- #print Cursor.description[1]
Results:
Name: Mike
Name:olson
Name:philtanker
The Chinese content detected from the database is normal.
But in the code inside the Chinese all is garbled or throws the exception, unresolved.
Integration with JRuby
Using the Jsr223:java code
[Java]
- Scriptenginemanager factory = new Scriptenginemanager ();
- Scriptenginemanager ScriptEngine = Factory.getenginebyname ("JRuby"); or "Ruby."
- Scriptengine.eval (code);
Accessing the database
Ruby Code
[Ruby]
- Require ' Java '
- Module Javalang
- Include_package "Java.lang"
- End
- Module Javasql
- Include_package ' java.sql '
- End
- Begin
- Username = ' hr '
- Password = ' 123456 '
- url = ' Jdbc:oracle:thin: @localhost: 1521:xe '
- drivername = ' Oracle.jdbc.driver.OracleDriver '
- Javalang::class.forname (drivername). Newinstance
- conn = Javasql::D rivermanager.getconnection (URL, username, password)
- stmt = Conn.createstatement
- sql = "Select last_name from EMPLOYEES t where t.salary<2300"
- rs = stmt.executequery (SQL)
- While (Rs. Next) do
- Puts "Name:" +rs.getstring ("last_name")
- End
- Rs.close
- Stmt.close
- Conn.close ()
- Rescue Javalang::classnotfoundexception
- Puts "ClassNotFoundException"
- Rescue Javasql::sqlexception
- Puts "SQLException"
- End
Results:
Name: Ying ﹀ toilets
Name: Olson
Name: Philtanker
The Chinese content detected from the database is garbled.
And in the code inside the Chinese normal.
Integration with Groovy
Using jsr223:
Java code
[Java]
- Scriptenginemanager factory = new Scriptenginemanager ();
- Scriptenginemanager ScriptEngine = Factory.getenginebyname ("Groovy"); or "Groovy."
- Scriptengine.eval (code);
Using Groovyshell:
Java code
[Java]
- Groovyshell shell = new Groovyshell ();
- Script script = Shell.parse (code);
- Object result = Script.run ();
Accessing the database
Groovy Code
- Import GROOVY.SQL.SQL
- def username = ' HR '
- def password = ' 123456 '
- def URL = ' Jdbc:oracle:thin: @localhost: 1521:xe '
- def drivername = ' Oracle.jdbc.driver.OracleDriver '
- def sql = sql.newinstance (URL, username, password, drivername)
- Sql.eachrow ("Select last_name from EMPLOYEES t where t.salary<2300") {
- println "Name: ${it.last_name}"
- }
Results:
Name: Mike
Name: Olson
Name: Philtanker
An exception was encountered during the use of groovy
Exception in thread "main" Java.lang.VerifyError: (Class:groovy/runtime/metaclass/java/util/arraylistmetaclass, Method:super$2$invokemethod Signature: (Ljava/lang/class; Ljava/lang/object; ljava/lang/string; [Ljava/lang/object; ZZ) Ljava/lang/object;) Illegal use of nonvirtual function call
It took a long time to resolve this exception.
Because Json-lib-2.1.jar exists in the original project (possibly named Json-lib-2.1-jdk15.jar), this package is used to process json, conflicts with groovy1.7.5, and is updated to Json-lib-2.3.jar
(There are some groovy runtime-processed content in Json-lib)
Invoking JS code directly in Java (reprint)