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.
My mainly doubt is when this power would be really useful
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:
At rendering time, this is, when generating the HTML output to the user.
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:
Oracle Nashorn: A Next-Generation JavaScript Engine for the JVM
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
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.
Related
I recently developed a whole system in Java that connected to a database and exports and imports the table content to an excel sheet. I used SWING for the user interface. the user will interact with it for authentication and file management.
Apparently the client changed the requirements, He wants everything from a Web Interface. My team leader advised to look through JSP.
What does JSP actually do?
Will I have to rewrite the User Interface in Web if I used JSP?
is there an more effective and efficient solution to do this job?
I would Appreciate a specific answer
I'm not sure what you mean by "specific answer", but here goes:
JSP is a kind of template language, based on Java, and a technology for dynamically generating HTML. It's a server side technology. Look here.
Yes, if you're going for a pure web/HTML solution, you'll need to completely rewrite the UI.
There are other frameworks for creating webapps, such as Vaadin or Play! Framework that may be "better" than JSP, but then there's a whole new API/framework to learn...
What does JSP actually do?
Will I have to rewrite the User Interface in Web if I used JSP?
is there an more effective and efficient solution to do this job?
and
I used SWING for the user interface.
and
exports and imports the table content to an excel sheet.
not, have to look at JavaFX 2
You will certainly need to rewrite the user interface if you convert to JSPs.
JSPs are essentially just a method for dynamically generating HTML (with the option to embed Java code to produce parts of the page).
It is still possible to run Swing applications from a web browser: you might want to take a look at Java Web Start. This will save you from having to do a complete rewrite.
1.) JSP is pretty much like PHP. It is server side scripting. When ever a browser request for a page (JSP page), server (mostly Tomcat or any application server which you deploy your JSP project) will generate HTML content using the JSP code. Mainly JSP consist of part HTML, JavaScipt (if you want dynamic stuff), and Java.
2.) As far as I know if you are aked to do it in JSP then you need to o all the client side work again in JSP. There you will be generating HTML UIs using Java codes. But you can use all the back end codes you used.
You may can use SWING in a Applet.
I'm trying to create an excel file and save to local file system using java applet. After sign the application, i can successfully create the file by directly invoking the applet. However, when i try to call the method from javascript, it failed without any error message. I'm wondering if there is any policy control to prevent java method to be called from javascript?
<html>
<script language="JavaScript">
function createExcel()
{
document.excel.createExcel();
document.excel.setMessage("hello world from js");
}
</script>
<body>
<input type="button" value="Generate Excel" onclick="createExcel()" />
<applet id='applet' name='excel' archive='Office.jar,poi-3.7-20101029.jar' code='com.broadridge.Office.class' width='100' height='100'></applet>
</body>
</html>
Methods in a trusted applet that are invoked using JavaScript need to be wrapped in a PrivilegedAction and called using one of the AccessController.doPrivileged(..) variants.
Sandboxed file-system access
Plug-In 2 JREs (Oracle's 1.6.0_10+ JRE for example) offer sandboxed access to the local file-system using the JNLP API file services (specifically the FileSaveService). See the file service demo. for an example.
Applet element
An applet called by JS should declare that it is scriptable in the HTML. As for getting that 'HTML', the best way to write it is using Oracle's deployJava.js. It will not only write the applet element the best way that is currently known for each browser, but does JRE presence (is Java installed?) and minimum version (is the JRE the minimum version needed to run this applet?) checking.
There may be several issues here.
1) You have to use the JavaScript deployment method for the applet (see link).
2) If the method you try to invoke is not in the applet-child itself, you first have to get an instance of the class in question and then invoke it's method, e.g. (for Calculator class):
var calculator = mathApplet.getCalculator();
calculator.setNums(numA, numB);
Moor info
I've been tasked with building a new Javascript file browser but unfortunately I have to use Prototype and can't use Jquery (at least not at the moment) due to some issues that may arise from conflicts (they have said they plan to resolve this but for the moment it looks like I may have to go with prototype). I've been searching on google for plugins that I can use for Prototype / Scriptaculous but they seem few and far between and all the ones I have found are geared towards use with PHP. I figure I may be able to rewrite the PHP end to Java / JSP as our application is built with Java. I just figured I would post here to see if anyone can recommend a good plugin for this that could easily be made to integrate with Java. Thanks
EDIT: This is what I mean:
http://abeautifulsite.net/blog/2008/03/jquery-file-tree/ (this is in Jquery) so I need something like this for Prototype
This is for browsing the file system of the server, not the client, so there would be a server-side page / controller that returns an HTML list, of sorts, of the files / folders and then the JavaScript manipulates this as needed to collapse / expand. There are a bunch of these written in Jquery but unfortunately I can't seem to find one written with Prototype
As pointed out by Diodeus, and as demonstrated by your own example, and as probably used by most file browser plugins available it works on HTML being rendered and returned by the server. All the javascript needs to do is insert the returned HTML, Prototype has a function which does most of that for you, Ajax.Updater. You could write your own very quickly.
function expandCollapseFolder(event, folder) {
var list = folder.down('ul');
if (list) list.toggle();
else new Ajax.Updater(folder, 'URL-OF-SERVER-PAGE',
{
parameters: { path: folder.readAttribute('data-path') },
insertion: 'bottom'
});
}
Event.on('ID-OF-FILE-BROWSER', 'click', 'li.folder', expandCollapseFolder);
The above is not tested code, it is meant to show how little is needed in total. The hard work is done by the server, it needs to scan and return folder contents with the appropriate file icons and URLs.
<ul>
<li class="folder" data-path="/folder">
<img src="folder-icon.png" />This is a folder
</li>
<li>
<a href="URL-OF-FILE" target="_blank">
<img src="file-icon.png" />This is a file
</a>
</li>
</ul>
I've been searching on google for plugins that I can use for Prototype
/ Scriptaculous but they seem few and far between and all the ones I
have found are geared towards use with PHP.
Based on your question I'm not sure exactly what you need to accomplish.
Prototype & Scriptaculous are add-on libraries for JavaScript, just as jQuery is. They have absolutely nothing to do with PHP, Java or any other server-side language because they are part of the client side: JavaScript.
If you're making one to browse files on the server, you're simply sending a HTML representations of the file listing to the browser. You would use Prototype to manipulate this HTML.
There are no Javascript-based client-side file browsers, regardless of whether you're using jQuery or Prototype because JavaScript cannot see the local filesystem on the client machine. This was deliberately designed this for security reasons.
I wanted to know how to scrape web pages that use AJAX to fetch content on the web page being rendered. Typically a HTTP GET for such pages will just fetch the HTML page with the JavaScript code embedded in it. But I want to know if it is possible to programmatically (preferably Java) query for such pages and simulate a web browser kind of a request so that I get the HTML content resulting after the AJAX calls.
In The Productive Programmer author Neal Ford suggests that the functional testing tool Selenium can be used for non-testing tasks. Your task of inspecting HTML after client side DOM manipulation has taken place falls into this category. Selenium even allows you to automate interactions with the browser so if you need some buttons clicked to fire some AJAX events, you can script it. Selenium works by using a browser plugin and a java based server. Selenium test code (or non-test code in your case) can be written in a variety of languages including java, C# and other .Net languages, php, perl, python and ruby.
You may want to look at htmlunit
Why choose when you can have both? TestPlan supports both Selenium and HTMLUnit as a backend. Plus it has a really simple language for doing the most common tasks (extensions can be written in Java if need be -- which is rare actually).
I would like to open a webpage and run a javascript code from within a java app.
For example I would like to open the page www.mytestpage.com and run the following javascript code:
document.getElementById("txtEmail").value="test#hotmail.com";
submit();
void(0);
This works in a browser...how can I do it programatically within a java app?
Thanks!
You can use Rhino to execute JavaScript but you won't have a DOM available - i.e. document.getElementById() would work.
You can use HTML Unit (headless) or WebDriver/Selenium (Driving a browser) to execute JavaScript in an environment that has a DOM available.
I'm not sure what you are looking for but I assume that you want to write automated POST request. This can be done in with Http Client library. Only you have to set appropriate request (POST or GET) parameters.
Look at examples - with this library you can do basic authentication or post files too.
Your question is a bit ambiguous, as we don't know the position of the Java program.
If that's a Java applet inside your page, you should look at Java<->JavaScript interaction, it works well.
If you need a separate Java program to control a browser, like sending a bookmarklet in the address bar (as one of your tags suggests), it is a bit harder (depends on target browser), perhaps look at the Robot class.
There's Rhino JS engine written in Java that you can run on app server such as Tomcat and feed JS to, however - it's not clear what are you trying to do with this?
There's also Envjs simulated browser environment which is based on Rhino but complete enough to run jQuery and/or Prototype
DWR (and other frameworks) now support "reverse ajax." The general idea is that you use one of three methods to communicate back to the client:
Comet (long-lived https session)
Polling
opportunistic / piggy-back (i.e. next time a request comes from the client, append your js call)
Regardless of method (which is typically a configuration-time decision and not a coding issue), you will have full access to any/all js calls you want to make.
Check out the reference page from DWR to get a pretty good explanation.