1

I know that we can call Java from JavaScript and vice-versa, but I'm wondering myself about when take that power and use it in a healthy way. I'm talking about real world applications, not "hello world".

As many developers usually I'm developing java and javascript but I not have the enough experience for know when mix those guys is a good idea.

Please if there is some developer who can share his knowlege about how has constructed real world applications using this mix would be great :).

Apologies, I failed to convey my doubt in a worthwhile way, so, Did you hear about Narshorm?, for instance you could call Javascript code from a Java Class, but I dont see a business case in which those capabilities increase the worth to my server side applications.

This is a nashorn hello world, in this application there is a Java Main which "eval" the content of a .js file calling the functions inside the .js file.

nashorn hello world app

My mainly doubt is when this power would be really useful

Gio
  • 41
  • 6
  • Querying databases is a good example. Javascript, by itself, is unable do that, so you could then call server-side Java through AJAX to do it for you and then just grab the results back and output them. – Natan Streppel Apr 28 '14 at 19:42
  • I assume you are talking about browser JavaScript and Java running on the server. You can use it the other way around too, with Java applets in the browser and Node.js as the server system... Not saying that using applets is a good idea, but still. :-) – whirlwin Apr 28 '14 at 19:58
  • Apologies, I failed to convey my doubt in a worthwhile way, so, Did you hear about [Narshorm](http://www.infoq.com/articles/nashorn)?, for instance you could call Javascript code from a Java Class, but I dont see a business case in which those capabilities increase the worth to my server side applications. – Gio Apr 28 '14 at 19:59
  • The real question is *which* "Java" (e.g. client/applet/jws, server) is being called and from *which* "JavaScript" environment (e.g. browser, embedded, node)? – user2864740 Apr 28 '14 at 20:10

3 Answers3

1

Javascript is a client-side scripting language. This is used to interact with what a user can see and do on a website (html) For instance, you can use javascript to make something happen when you click on a button, or hover over a menu item.

Java is a server-side language. This is compiled code which runs on a server and the user generally has no idea of what happens here. A good real world application of using server-side code (Java in your case) is for database queries and updates.

For example, if you have a web page that asks a user to register for an account, there might be a form with a text box for username and password. When the user clicks "register" this information is to be stored in the database.

In this, your javascript will have code that is executed when the button is pressed which captures this data. It then sends this to the server with an HTTP Post (ajax is often used to send this) The server gets this data and executes the Java code you write to insert this into the database.

A very simple website which does not need to store user data may not need any server side code at all, but in most real world scenarios, there is some server code working alongside your html and javascript

Aheinlein
  • 450
  • 2
  • 7
  • 19
  • Apologies, I failed to convey my doubt in a worthwhile way, so, Did you hear about [Narshorm](http://www.infoq.com/articles/nashorn)?, for instance you could call Javascript code from a Java Class, but I dont see a business case in which those capabilities increase the worth to my server side applications. – Gio Apr 28 '14 at 20:00
  • 2
    "Java is a server-side language" is simply incorrect, as is the assertion that a client-side language is/must be "scripted". – user2864740 Apr 28 '14 at 20:04
  • @user2864740 but Java here is server side language. That's right. – Luiggi Mendoza Apr 28 '14 at 20:05
  • 1
    @LuiggiMendoza No. Java can be *used* on a Server. It can also be used as a Client (Applets anyone?) or even on an Embedded Device. – user2864740 Apr 28 '14 at 20:05
  • @user2864740 well, it depends on the context of the question. If we're talking about web applications, Java is purely server side code, while JavaScript is client side code. – Luiggi Mendoza Apr 28 '14 at 20:06
  • @LuiggiMendoza I don't follow. Keeping in the context of web: applets on a webpage are client-side Java and Node.Js is server-size JavaScript. – user2864740 Apr 28 '14 at 20:07
  • @user2864740 applets are not web applications. An applet is a client side application that can be exposed using a HTML page, similar to a Flash application. – Luiggi Mendoza Apr 28 '14 at 20:08
  • Yes Java can be used in server side and client side I totally agree :), but my doubt is about when to call a javascript script from a Java Class is a good idea. – Gio Apr 28 '14 at 20:08
  • @LuiggiMendoza Oh, so you agree that Java is *not necessarily* a server side language? – user2864740 Apr 28 '14 at 20:08
  • @user2864740 I agree with that. I was talking about **web development** (read how OP answers, and in this context OP's right). Apart from web development, Java is executed directly in your machine through the JVM, like JavaScript is executed on your machine through an interpreter like a browser. – Luiggi Mendoza Apr 28 '14 at 20:10
1

In web application development (which is the usual scenario where Java and JavaScript interact):

there are 2 places where you can make the server and client side languages interact with each other:

  1. At rendering time, this is, when generating the HTML output to the user.

  2. At runtime, this is, when the HTML has been generated and it is at client side (e.g. browser client).

For the first case, let's say we have a Servlet that adds an attribute to the request and forward to a new (JSP) view. This is an example of the servlet:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        // Prepare messages.
        request.setAttribute("name", name);
        request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
    }
}

Then in your view (hello.jsp file inside WEB-INF folder), you have a code like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Servlet Hello World</title>
        <script>
            function changeName(var newName) {
                document.getElementById('divName').innerHtml = 'Hello ' + newName;
            }
            window.onload = function () {
                changeName('${name}');
            }
        </script>
    </head>
    <body>
        <div id="divName">
        </div>
        <form id="name" action="hello">
            Change name to: <input type="text" name="name" />
            <br />
            <input type="text" value="Change the name" />
        </form>
    </body>
</html>

By using this approach, we can communicate Java generates variables (NEVER SCRIPTLETS) directly to JavaScript when rendering the view. So we can access to Java page, request, session and context attributes only when creating the HTML that is going to the client.

Note that if you want to re-execute this Java code, you should fire a new request to the server in order to execute the Java code. This is where ajax come handy.

Ajax lets you communicate with the server side asynchronously, the server will prepare a response for your request, and then in client side you will define how to use it. For this purpose, it is better to use a common format for the communication. The most preferred format nowadays is JSON. Ajax interactions to servlet is widely covered here: How to use Servlets and Ajax? (no need to reinvent the wheel in this post).


In standalone or mobile applications:

Java will run on the client machine. Note that here Java can execute JavaScript code through a JavaScript engine like Rhino or nashorn. This is useful when you have lot of functionalities already written in javascript (like an external library) and do not want to migrate all the code to Java. You can just use ScriptEngineManager and StringEngine classes to execute the code in JavaScript in your Java application. A real-world example of using JavaScript in a Java application is Pentaho Kettle, written in Java, that allows applying transformations to your code through JavaScript scripts.

More info on Nashorn:

Community
  • 1
  • 1
Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306
  • Hi @Luiggi Mendoza thanks alot for your answer :) now I know a bit more than about this kind of tools :) – Gio Apr 28 '14 at 20:40
0

One common place for these technologies to be used together is AJAX. The server side web services might be written in Java and the client side Javascript calls web services.

It's worth pointing out that Java and Javascript are actually completely different languages. The web services could be written in any language.

Barett
  • 5,226
  • 6
  • 46
  • 53
  • I Barett apologies, I failed to convey my doubt in a worthwhile way, so, Did you hear about [Narshorm](http://www.infoq.com/articles/nashorn)?, for instance you could call Javascript code from a Java Class, but I dont see a business case in which those capabilities increase the worth to my server side applications. – Gio Apr 28 '14 at 20:02
  • I believe Narshorm was originally developed to allow implementation of a pure java web browser that could execute Javascript as appropriate. – Barett Apr 29 '14 at 22:48