简体   繁体   中英

Generate JavaScript code in a Java application

I've seen similar questions but not the same. I have a java application which sends a get and post requests. Now the issue is that the requests need to have a CSRTF TOKEN which I can't get from the ReasteastClient.getcookies method, so I've written a JavaScript code to get this token. I'm trying to generate a JavaScript code from my java application and to get the function response.

Any way to do so ?? Thank you all.

To generate JavaScript code in Java you need to follow following steps

1.create your JavaScript File and add your function which retrieves CSRTF TOKEN

By adding function :

$.get('CSRFTokenManager.do', function(data) {
   var send = XMLHttpRequest.prototype.send,
   token =data;
   document.cookie='X-CSRF-Token='+token;
   XMLHttpRequest.prototype.send = function(data) {
       this.setRequestHeader('X-CSRF-Token',token);
       //dojo.cookie("X-CSRF-Token", "");

       return send.apply(this, arguments);
   };
});

2.Save this as Jsfunctions.js and use it in your java code like below.

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// read script file
engine.eval(Files.newBufferedReader(Paths.get("C:/Scripts/Jsfunctions.js"), 
StandardCharsets.UTF_8));

Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("yourFunction", "param");

Hope this helps..!

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