Usage of ScriptInjector in GWT - java

I want to use javascript library in java source code. I read sth about it and I read, that I should use ScriptInjector. This class has 2 inner classes: ScriptInjector.FromString and ScriptInjector.FromUrl. I want to load javascript library from local file, so I should use from string. How to do it?
ScriptInjector.fromString("myLibrary.js");
does not work. Where to add library?

1) fromUrl - creates script tag with specified src attribute and appends it to the page. E.g.
ScriptInjector.fromUrl("http://example.com/my-script.js").inject();
will simply produce:
<script type="text/javascript" src="http://example.com/my-script.js" />
You can host your files on the web site and inject each of them on demand
2) fromString - creates script tag with specified body of the script, so:
ScriptInjector.fromString("alert('Injected!')").inject();
will give
<script type="text/javascript">
alert('Injected!')
</script>
In this case JS code is a part of your compiled GWT code and browser doesn't require to load it with separate request. I think it is possible to include native JS file into compiled output with TextResource. So you need following:
Define resources
public interface JsResources extends ClientBundle {
final JsResources INSTANCE = GWT.create(JsResources.class);
#Source("first.js")
TextResource firstScript();
#Source("second.js")
TextResource secondScript();
}
Inject required script
ScriptInjector.fromString(JsResources.INSTANCE.firstScript().getText()).inject();

To use .fromString() you'd have to load the JS into a String and pass that.
If you need to load the script using the .fromUrl() you'll have to put it somewhere "Internet" accessible, since the inject() ends up in
private static native void nativeSetSrc(JavaScriptObject element, String url) /*-{
element.src = url;
}-*/;
(See it here)
So: Extract or otherwise expose the script to your webserver.
Cheers,

Related

How to call a javascript function with a browser in Java?

I have implemented a simple browser in java which load a html page(I wrote it), I want to call my javascript function, in my java my class!
I try the following code, but it didn't execute the script!
browser.execute("<script type='text/javascript'> "
+"loadMap("+lat+","+lng+");"
+" </script>");
Try
browser.execute("loadMap("+lat+","+lng+");");
You don't need to create a script tag to execute the script. Just execute the actual JavaScript code. Refer to this sample.

Play Framework: How do I get querystring value inside html template file

I am working on Play Framework 2.0 for Java and I have a querystring url like http://localhost:9000/project/detail?id=1, when this url hits It will call a HTML template file eg.detail.scala.html. So I want to check is there querystring exist in url in my HTML file.
ex:
#if(existsQueryString)
#showPerticularProductDetail
else
#showAllProductList
Please help me or give any suggestion for this. I dont want to pass some variable or any flag from controller to view for checking the condition. I just want to check is querystring there in url inside my HTML.
You can access the request either directly if you're in a Java project, or via an implicit parameter if you are in a Scala project.
In a Java project, you can use it directly to check the queryString :
#if(request.queryString.containsKey("myKey")){
#showPerticularProductDetail
else
#showAllProductList
If you're in a Scala project, you need to add the request as an implicit parameter of your view :
#(title: String)(implicit request: play.api.mvc.Request)
And your controller should also declare this implicit parameter :
def detail = Action { implicit request =>
...
myTemplate.render()
}

Input to JavaFX from JSP

I want to give dynamic input to Java FX application from a JSP page. I am not able to find any suitable way.
Dynamic in the sense that I want to give input to JavaFX application based on user input in a JSP page. I am embedding the same Java FX application in the same JSP page.
Any help is welcome regarding the same.
I want to give input to Java FX application when it is running through JSP page.
See the JavaFX deployment topic: Accessing a JavaFX Application from a Web Page.
The JavaScript => JavaFX interface in JavaFX is the same as that used for a traditional Java applet - it makes use of a technology known as LiveConnect. Further documentation on using LiveConnect is in the LiveConnect documentation topic: Calling from JavaScript to Java.
The JavaFX documentation provides the following sample code:
Java Code
package testapp;
public class MapApp extends Application {
public static int ZOOM_STREET = 10;
public static class City {
public City(String name) {...}
...
}
public int currentZipCode;
public void navigateTo(City location, int zoomLevel) {...}
....
}
JavaScript Code
function navigateTo(cityName) {
//Assumes that the Ant task uses "myMapApp" as id for this application
var mapApp = document.getElementById("myMapApp");
if (mapApp != null) {
//City is nested class. Therefore classname uses $ char
var city = new mapApp.Packages.testapp.MapApp$City(cityName);
mapApp.navigateTo(city, mapApp.Packages.testapp.MapApp.ZOOM_STREET);
return mapApp.currentZipCode;
}
return "unknown";
}
window.alert("Area zip: " + navigateTo("San Francisco"));
Note the important comment in the JavaScript code "Assumes that the Ant task uses "myMapApp" as id for this application". The id referred to is the placeholderid parameter of the fx:deploy task.
Now, because you are using a JSP, presumably the html page containing the application is dynamically generated by the JSP processor. So, what you may want to do is make use of the fx:template task to generate modified jsp source which invokes the dtjava deployment script to embed your target JavaFX application.
I'm not sure, but try: HostServices.getWebContext

Calling a javascript function out of java

Im trying to call a javascript function out of my Vaadin Portlet.
lets say I have an HTML file witch is located in my project ;
homepage.html
<html>
...
<script type="text/javascript">
...
function foo(String msg)
{
alert(msg);
}
...
</script>
...
</html>
the page in Embedded in my Portlet via the Vaadin Embedded Browser
how do I call the function foo(String msg) out of my java application
do i need to import/read the homepage.html file and just call it or is it something else I have to do ?
firstly you need to get the script body;
then you can user javax.script.ScriptEngineManager to solve your problem javax.script.*
pseudo code
import javax.script.*;
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("javascript");
String script = getScript(path_to_html);
engine.eval(script);
The simplest way to include an external javascript file into a Vaadin application is to override the Application#writeAjaxPageHtmlVaadinScripts method.
To call a javascript function from the Vaadin server-side code, you call Window#executeJavascript
#Override
protected void writeAjaxPageHtmlVaadinScripts(Window window,
String themeName, Application application, BufferedWriter page,
String appUrl, String themeUri, String appId,
HttpServletRequest request) throws ServletException, IOException {
page.write("<script type=\"text/javascript\">\n");
page.write("//<![CDATA[\n");
page.write("document.write(\"<script language='javascript' src='" + appUrl + "/VAADIN/scripts/example.js'><\\/script>\");\n");
page.write("//]]>\n</script>\n");
super.writeAjaxPageHtmlVaadinScripts(window, themeName, application,
page, appUrl, themeUri, appId, request);
}
NB : I have never used Vaadin as a Portlet, but a quick look suggests that this should work OK.
However, this approach is rather rudimentary, and only suitable for a quick hack/proof-of-concept: if you want to so anything more sophisticated, then developing your own Vaadin widget is correct approach. It gives you the power of GWT and JSNI, and gives you a much finer grain of control : See The Book Of Vaadin for more details.
Refer to following links, these provides API for doing what you want to do,
http://www.ibm.com/developerworks/java/library/j-5things9/index.html
http://metoojava.wordpress.com/2010/06/20/execute-javascript-from-java/

Include page javascripts conflicting with outer page javascripts

My problem is a little difficult to explain, but I will try.
I have 2 jsp pages Outer.jsp and Inner.jsp
Outer.jsp
Script: src="tabs.js"
var PageTabs = "Tab1"
#include "Inner.jsp"
Inner.jsp
Script: src="tabs.js"
var PageTabs = "Tab2~Tab3~Tab4"
Both the jsp pages use the same tabs.js to render some tab elements on the page. The "PageTabs" variable is one of the many common variables that are used by tabs.js. So what happpens is while rendering, the tabs.js takes the latest "PageTabs" variable i'e var PageTabs = "Tab2~Tab3~Tab4" even while rendeing tabs of Outer.jsp.
Note: The page variables and tabs.js are part of standard elements recieved from client. So they have to be used to give the same look and feel for application.
What I need is a way to isolate the "Inner.jsp" from accessing scripts of "Outer.jsp". This will prevent the tabs element from being confused over which variables to use.
I hope I am somewhat clear. Please let me know if I need to provide any more clarifications. Thanks.
JavaScript is interpreted top-to-bottom inside a page, so your second PageTabs value overrides the first one. One option is to use a different name for the variable (and parameterize tabs.js functions rather than rely on global vars.)
When using jsp include, one of a very useful skill is to make your .js code modular . This is also an important method to encapsulate code and avoid conflict.
tab.js:
var tabModule = (function(my){
var model;
return {
setModel: function(model){/*....*/}
//other api functions
}
})(tabModoule||{});
Outer.jsp:
tabModule.setModel({PageTabs : "Tab1"});
Innder.jsp:
tabModule.setModel({PageTabs : "Tab2~Tab3~Tab4"});

Categories