Tuesday 25 August 2015

Java 8 - Nashorn

One of the new features in Java8 is Nashorn (JSR 292)
It is basically the introduction of an engine to execute javascript in the server side over the JVM.

Over the last years there have been many solutions to execute javascript in the server side. Originally Javascript was used exclusively in the client, but with the emergence of new technologies (some as successful and trendy as node.js) javascript executed in the server is a real option.

My first question when I read about the idea of develop javascript in the server was ... why? what could be the advantage of using javascript in the server side?
If you have been working in web application probably the idea is in your mind...validation. Making validation simple and simplify code could be one of the advantages of this approach. Take into account that one of the principles of a secure development is to validate the data in both client and server.
Another advantage could be the idea of a unique programming language, not splitting anymore in front end/ server side expertise. The third advantage I could think is in re-usability of code routines.

Ok,...and how does it works? Let's see

Calling Javascript function from Java

In this example we will use a javaScript function that validates email format

Now using the js function from java:

We can use javascript in java using these three basic steps:
  • Defining ScriptEngine (see argument "nashorn")
  • Reference our javascript file using eval method.
  • Using invokeFunction or invokeMethod methods from Invocable class to call our javascript.

No comments:

Post a Comment