Invoking JS code directly in Java (reprint)

Source: Internet
Author: User
Tags java se

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]
    1. Scriptenginemanager factory = new Scriptenginemanager ();
    2. Scriptenginemanager ScriptEngine = Factory.getenginebyname ("JavaScript"); or "JS"
    3. 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]
    1. Scriptenginemanager factory = new Scriptenginemanager ();
    2. Scriptenginemanager ScriptEngine = factory.getenginebyname ("Python"); or "Jython."
    3. Scriptengine.eval (code);


With Pythoninterpreter, you can invoke the Exec (String code) method:

[Java]
    1. Pythoninterpreter interpreter = new Pythoninterpreter ();
    2. Interpreter.exec (code);

Accessing the database
Using JDBC:

[Python]
  1. From Oracle.jdbc.driver import oracledriver
  2. From java.sql import DriverManager
  3. Username = ' hr '
  4. Password = ' 123456 '
  5. url = ' Jdbc:oracle:thin: @localhost: 1521:xe '
  6. Driver = Oracledriver ()
  7. Drivermanager.registerdriver (Driver)
  8. conn = drivermanager.getconnection (URL, username, password)
  9. stmt = Conn.createstatement ()
  10. sql = "Select salary from EMPLOYEES t where t.salary<2300"
  11. rs = stmt.executequery (SQL)
  12. while (Rs.next ()):
  13. Print rs.getint (' salary ')
  14. Rs.close ()
  15. Stmt.close ()


Results:
2200
2100
2200

Using ZXJDBC:

[Python]
  1. From Com.ziclix.python.sql import Zxjdbc
  2. url = ' Jdbc:oracle:thin: @localhost: 1521:xe '
  3. Username = ' hr '
  4. Password = ' 123456 '
  5. drivername = ' Oracle.jdbc.driver.OracleDriver '
  6. Mysqlconn = Zxjdbc.connect (Url,username, Password,drivername)
  7. cursor = Mysqlconn.cursor ()
  8. Cursor.execute ("select last_name from EMPLOYEES t where t.salary<2300");
  9. #print Cursor.fetchone ()
  10. List = Cursor.fetchall ()
  11. For record in list:
  12. print "name:" +record[0]
  13. #print Cursor.description[0]
  14. #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]
    1. Scriptenginemanager factory = new Scriptenginemanager ();
    2. Scriptenginemanager ScriptEngine = Factory.getenginebyname ("JRuby"); or "Ruby."
    3. Scriptengine.eval (code);

Accessing the database

Ruby Code

[Ruby]
  1. Require ' Java '
  2. Module Javalang
  3. Include_package "Java.lang"
  4. End
  5. Module Javasql
  6. Include_package ' java.sql '
  7. End
  8. Begin
  9. Username = ' hr '
  10. Password = ' 123456 '
  11. url = ' Jdbc:oracle:thin: @localhost: 1521:xe '
  12. drivername = ' Oracle.jdbc.driver.OracleDriver '
  13. Javalang::class.forname (drivername). Newinstance
  14. conn = Javasql::D rivermanager.getconnection (URL, username, password)
  15. stmt = Conn.createstatement
  16. sql = "Select last_name from EMPLOYEES t where t.salary<2300"
  17. rs = stmt.executequery (SQL)
  18. While (Rs. Next) do
  19. Puts "Name:" +rs.getstring ("last_name")
  20. End
  21. Rs.close
  22. Stmt.close
  23. Conn.close ()
  24. Rescue Javalang::classnotfoundexception
  25. Puts "ClassNotFoundException"
  26. Rescue Javasql::sqlexception
  27. Puts "SQLException"
  28. 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]
    1. Scriptenginemanager factory = new Scriptenginemanager ();
    2. Scriptenginemanager ScriptEngine = Factory.getenginebyname ("Groovy"); or "Groovy."
    3. Scriptengine.eval (code);


Using Groovyshell:

Java code

[Java]
    1. Groovyshell shell = new Groovyshell ();
    2. Script script = Shell.parse (code);
    3. Object result = Script.run ();


Accessing the database

Groovy Code

    1. Import GROOVY.SQL.SQL
    2. def username = ' HR '
    3. def password = ' 123456 '
    4. def URL = ' Jdbc:oracle:thin: @localhost: 1521:xe '
    5. def drivername = ' Oracle.jdbc.driver.OracleDriver '
    6. def sql = sql.newinstance (URL, username, password, drivername)
    7. Sql.eachrow ("Select last_name from EMPLOYEES t where t.salary<2300") {
    8. println "Name: ${it.last_name}"
    9. }

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.