简体   繁体   中英

Call js methods from java

I have requirement to execute javascript method (which does some reporting and dump a PDF file) from java class.

Facing issue on how to load the context path in java method and call js method directly from java.

Eg. I need the context path of js file like /webapp/js/orn/workflow/Engine.js same as we get from browser in my java class :- ocm\\src\\main\\java\\com\\interra\\orion\\util\\workflow\\ScriptEngineUtil.java

Any thoughts on how to proceed, I tried using Rhino but got struck on how to context path.

The available answers provide enough information to call javascript code using Nashorn, specially the duplicated one that suggests 31piy in the first comment.

Then I assume that your real problem is to reach the javascript file that contains your code, present in your webapp folder. I can see some possible answers to that:

Here some fellows suggest possible ways to reach the file using Spring methods: Accessing files/directories in webapp folder in Spring You should consider if there is a way available to your particular framework

However: is there a good reason for that file to be in your webapp folder? Is its logic necessary at all in the client side? Since you need the logic in the server side, I would not (even for prudence) expose it to the client of your application. If it is not necessary in the client side, don't expose it. Just keep it, let's say, in your application's src/main/resources directory (assuming you build it with maven or gradle) and access it cleanly from your classloader:

// Access the resource from the classloader
try {
    reader = new InputStreamReader(
        YourServletOrWhateverClass.class.getClassLoader().
            getResourceAsStream("your_javascript_file.js"), 
                Charset.forName("UTF-8")); 
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval(reader);            

    Invocable inv = (Invocable) engine;
    inv.invokeFunction("your_function");
}
catch(NoSuchMethodException nsme) {
    nsme.printStackTrace();
}
catch(ScriptException se) {
    se.printStackTrace();
}
finally {
    try {
        reader.close();
    }
    catch(IOException ioe) {
        ioe.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM