如何在java中调用js方法

JavaScript026

如何在java中调用js方法,第1张

js代码如下:

[javascript] view plain copy

function formula(var1,var2){

return var1+var2-factor

}

java代码如下:

[java] view plain copy

import java.io.FileNotFoundException

import java.io.FileReader

import java.util.Scanner

import javax.script.Bindings

import javax.script.Invocable

import javax.script.ScriptContext

import javax.script.ScriptEngine

import javax.script.ScriptEngineManager

import javax.script.ScriptException

public class AboutJavaScript {

public static void main(String[] args) throws Exception {

ScriptEngine engine=new ScriptEngineManager().getEngineByName("javascript")

Bindings bind = engine.createBindings()

bind.put("factor", 1)

engine.setBindings(bind, ScriptContext.ENGINE_SCOPE)

Scanner input=new Scanner(System.in)

while (input.hasNextInt()) {

int first= input.nextInt()

int sec=input.nextInt()

System.out.println("输入参数是:"+first+","+sec)

engine.eval(new FileReader("F:/model.js"))

if(engine instanceof Invocable){

Invocable in =(Invocable) engine

Double result=(Double) in.invokeFunction("formula", first,sec)

System.out.println("运行结果:"+result.intValue())

}

}

}

}

JDK1.6版添加了新的ScriptEngine类,允许用户直接执行js代码。

在Java中直接调用js代码

不能调用浏览器中定义的js函数,会抛出异常提示ReferenceError: “alert” is not defined。

package com.sinaapp.manjushri

import javax.script.ScriptEngine

import javax.script.ScriptEngineManager

import javax.script.ScriptException /** * 直接调用js代码 */

public class ScriptEngineTest {

public static void main(String[] args) {

ScriptEngineManager manager = new ScriptEngineManager()

ScriptEngine engine = manager.getEngineByName("javascript")

try{

engine.eval("var a=3var b=4print (a+b)")

// engine.eval("alert(\"js alert\")") // 不能调用浏览器中定义的js函数 // 错误,会抛出alert引用不存在的异常

}catch(ScriptException e){

e.printStackTrace()

}

}

}