Excuse my lack of knowledge in many fundamental areas, but I am just learning how to create applets in java and how to allow interaction between the applet and the web page (javascript).
At the moment I have an applet with an init() and method1(). method1() just returns a string.
The applet is loaded on a web page and in javascript I literally reference the function:
<html>
<head>
<title>Testing Applet</title>
<script>
function hello() {
result = document.wplayer.method1();
alert(result);
}
</script>
</head>
<body>
<applet code = "player.Player" name = "wplayer" archive = "player.jar" width = "600" height = "400">
</applet>
<button onClick="hello();">Interact with app</button>
method1() just returns a string ("blah blah blah");
My question is, is this a safe way to do it and is it the most compatible?
Thanks!
Nick
is this a safe way to do it and is it the most compatible?
It's only as safe as the client is safe, so you should assume that the client may edit/forge/hack, etc.
If you meant safe in the other sense - not causing conflict - use an Object as your namespace in JavaScript and have everything kept within that Object. This way you are much less likely to have trouble with any conflicting variable names elsewhere on a page. You may also want to use unobtrusive JavaScript, to keep your script and HTML independent of each other.
Currently, your function hello is in the global namespace, and creates a global result, which could cause conflicts.
Assuming that the client has an up-to-date copy of Java and plugins enabled, you only really need to worry about the same compatibility issues as when writing any normal JavaScript for any browser.
Related
i am working on a legacy project where i have seen below piece of code.
I know it is a bad practice to use script inside scriptlet.
Regarding this , i have few confusion in mind.
what i believe is scriptlet is executed before page loads, so if below if condition is true then ShowBookReference() function call is a part of an Html page, but my question is when page is rendered should this function call happens or not ?
<% if (refLinkTerm != null) { %>
<script Language="javascript">
ShowBookReference('<%=sub2ndNavMenu%>', '<%=refLinkTerm%>', <%=String.valueOf(searchType)%>, <%=String.valueOf(codeType)%>)
</script>
<%}%>
How to avoid this kind of practice ?
Please share your thoughts.
Use an MVC framework such as Spring MVC. In these frameworks, you fill in a Java object (or map of objects) with the values for the page to display, and then the page just fills in placeholders with those values.
In terms of JSP, Its usual to use scriptlets to assign value to JS.
But as you've mentioned that it runs before the page load, so it's good to run the function on window.onload.
<script type="text/javascript">
window.onload = function() {
ShowBookReference('<%=sub2ndNavMenu%>', '<%=refLinkTerm%>', <%=String.valueOf(searchType)%>, <%=String.valueOf(codeType)%>)
}
</script>
In case you're referring some DOM elements inside ShowBookReference function, it may not be available so run it on page load.
Else you can use UI frameworks like JSF which provides you tags to bind java values to UI easily.
I am looking at writing a tutorial for a Java concept where it would be really nice if I could write the tutorial as a HTML-document with pretty printed Java sources.
I understand I can do this with e.g. http://code.google.com/p/google-code-prettify/ if I copy the various Java sources in my HTML document where I want them to be and put a styling class on the surrounding tag.
However, in order to ensure that the snippets are up to date I would really like to have the HTML page refer to the actual, real Java source files instead of a manually maintained copy.
To my understanding - which may be wrong - this is not supported directly by the Google Prettyprint library, but perhaps some trickery with Javascript pulling in the file and putting it in the DOM tree inside a <pre> tag could do it? I would like the HTML file to be present in the local file system, so doing server side scripting is not an option.
My question is - how can I do this?
(I intend to have the HTML file physically placed at the root of the source tree. This mean that all references from HTML to Java sources will be relative and without '..'. I do not know if that is important or not.)
There is no way to access files directly using JavaScript. JavaScript is restricted in this way for obvious security reasons.
You will need your webserver to serve the Java files. You don't need to do server side scripting but the content of your Java files has to be available at some web address. If they are you can load the content of the Java files with AJAX and inset the content into your webpage.
Using jQuery loading the text could be done as follows
$.get('java/somefile.java', function(data) {
$('#sourceCodeDestination').html(data);
// Prettyprint neeeds to run again in order to see the newly added code
prettyPrint();
}, "text");
This will load the url java/somefile.java get the content of it as plain text and insert it into the DOM element with the id sourceCodeDestination. For more information see the jQuery documentation on get() and ajax().
Here is a demo. As you can see it loads a minified version of the Prettyprint sourcecode from a CDN and pretty prints it.
if your users can accept the requirement of online access while reading your document, you could host your code somewhere like gist (https://gist.github.com/), and embed it in your html dopcument (see example by putting this into your document <script src="https://gist.github.com/sangohan/6494440.js"></script>)
Assuming prettify.js has been loaded previously you can invoke the function prettyPrint which takes arguments callback and rootNode.
<div id="foo">
<pre id="bar"></pre>
</div>
var pre = document.getElementById('bar');
pre.textContent = 'function () {\n return;\n}'; // assign code
pre.className = 'prettyprint'; // assign class
prettyPrint(null, document.getElementById('foo')); // prettify
DEMO
I have a javascript file main.js. The main.js contains something like this:
$(document).ready(function() {
Cufon.replace('#myform p.head', { fontFamily: 'HelveticaNeueLT Std Thin' });
......
});
I suppose what this does is to run this method after the whole page is loaded and apply the change to the css elements.
But what I found out is that this only works when the script is loaded before all the HTML elements, e.g.:
<body>
HTML......
<script type="text/javascript" src="js/main.js"></script>
</body>
However, if this script is put on top of all the HTML, it stops working:
<body>
<script type="text/javascript" src="js/main.js"></script>
HTML......
</body>
This happens on both static HTML and the GWT page. Because my GWT always put the generated HTML stuff at the end of all the body contents, the script is always before the HTML, hence is does not work. For example, my HTML for GWT module is like this:
<body>
<script type="text/javascript" src="js/main.js"></script>
</body>
And after compiled, the generated HTML from my UIBinding gives HTML page like:
<body>
<script type="text/javascript" src="js/main.js"></script>
Generated HTML....
</body>
My questions are:
Is there anyway in GWT where I can specify the generated HTML goes
between some statements in the tag.
Is there any other ways instead of $(document).ready I can guarantee
it is called as the last thing happened in a page load?
Many thanks
While I find it strange that the script doesn't work as intended when moved up in a static page ($(document).ready(…) is supposed to wait for the </html> to be reached –aka DOMContentLoaded– before running the function passed to it), it's not the reason it doesn't work with your GWT application (in other words, your diagnostic is wrong).
GWT's onModuleLoad also runs at DOMContentLoaded (or later, but never earlier) so you probably have a race condition between your app's onModuleLoad and jQuery's $(document).ready(…). You could try putting the <script> for your GWT app before the main.js, but because onModuleLoad might run after DOMContentLoader anyway, there's no guarantee it'll work (even less in a crossbrowser way).
I think you'd better remove the main.js or replace the $(document).ready(…) with a simple function, and call Cufon (and/or whatever else you were doing in $(document).ready(…)) from within your GWT app, at the moment appropriate for your needs (i.e. after you attached the #myform p.head element/widget to the document).
The easiest way to do that is to put the script in a JSNI method and then call that method where appropriate. Just make sure you use $wnd.Cufon instead of Cufon (and similarly for all other globals), and replace all occurrences of document with $doc and window with $wnd.
public static void cufon() /*-{
$wnd.Cufon.replace('#myform p.head', { fontFamily: 'HelveticaNeueLT Std Thin' });
}-*/;
I've got a JSP page that I want to return a fragment of HTML. The trouble is that whenever I request the JSP, something is attempting to make the HTML more valid by wrapping <html> tags around it. I don't want it to do this though as it will be used in a variety of other places.
For an example, the following JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script src="${applicationConfig.javascriptUrl}update.js" language="javascript" type="text/javascript"></script>
<p>Wibble</p>
Will result in the following HTML:
<html xmlns="http://www.w3.org/1999/xhtml"><head></head><script src="http://fisher.mycompany.com:8080/my-app/includes/js/update.js" language="javascript" type="text/javascript"></script>
<p>Wibble</p></html>
I really don't want those <html> & <head> tags there and would like to get rid of them but have no idea where this is happening to turn it off. Does anyone have any clues?
* Edit *
To give a little more information on what I am trying to achieve. This JSP will check a variety of things and form a piece of HTML. This HTML can then be included into other applications via a web service call.
Servlets can return any content type including javascript and images, not just HTML. Tomcat should not wrap jsps in extraneous tags. I put the snippet you suggested in a jsp, minus the taglib which I don't have set up, and got back exactly the HTML that I put in.
Can you tell us more about your environment? Are you using tomcat? Are you using some kind of framework?
Servlets are HTML factories. They expect to send a valid HTML page down to a browser to be rendered. You can't "get rid of it" without breaking the whole model.
Your original concept of sending a snippet that's "used in a variety of other places" is flawed. You sound like to want to set some data that might be used in other places - that's valid - but I don't see how wrapping it in markup matters.
Only the JSP should be using the marked up data. JSPs are all about display. I'd rethink what you're doing and attack how you want to share the data, not the markup.
One approach it might work,
Create HTML files as you required valid HTML,
and use servlet to returns response, servlet should read HMTL File and return
its contents as String, like XML respones from servlet
hopes thats helps
I have been looking into the GWT for a couple of days now and I have some confusion.
I come from a PHP/JSP background so when I wanted to create a website that had multiple pages I would just create a PHP page for each page and then let the user select what to view.
Now that I am looking into GWT I don't really understand how this is done?
Lets say I would like my site to have three pages (index.html, help.html, contact.html), when a GWT app is loaded the onModuleLoad() method is called. How would I then code each separate pages widgets then using only this one method?
Looking at the example GWT application that is created in Eclipse, A single HTML page is created. How would I create an application with multiple pages if there is only a single onModuleLoad() method?
GWT can be used in a Web 2.0, client-side application way as mentioned by Chris Lercher and nvcleemp or you can use it in conjunction with a more traditional page view/reload model. If you simply want to inject DHTML functionality into existing, static pages, you can look for specific element id's for injecting into or you could read a javascript embedded configuration variable when onModuleLoad() is called to determine what state/mode you are in and what type of GWT client functionality you should be running.
For example, using the different injection points:
page 1:
<html>
<head>
...
<script type="text/javascript" src="yourmodule.nocache.js"></script>
...
</head>
<body>
...
<div id="injectMode1"></div>
...
</body>
</html>
page 2:
<html>
<head>
...
<script type="text/javascript" src="yourmodule.nocache.js"></script>
...
</head>
<body>
...
<div id="injectMode2"></div>
...
</body>
</html>
Your GWT EntryPoint:
#Override
public void onModuleLoad() {
final Panel mode1 = RootPanel.get("injectionMode1");
if (mode1 != null) {
mode1.add(new ModeOneWidget());
}
final Panel mode2 = RootPanel.get("injectionMode2");
if (mode2 != null) {
mode2.add(new ModeTwoWidget());
}
}
EDIT:
Using javascript variables, on each page that you want to embed GWT functionality you can do something similar to:
page foo:
<html>
<head>
...
<script type='text/javascript'>
var appMode="mode1";
</script>
<script type="text/javascript" src="yourmodule.nocache.js"></script>
...
</head>
...
Your GWT EntryPoint:
private static final native String getAppMode()/*-{
return $wnd.appMode;
}-*/;
#Override
public void onModuleLoad() {
String appMode = getAppMode();
if(appMode != null){
if(appMode.equals(MODE1)){
...
}
...
}
}
GWT uses JavaScript to modify the page content. So you don't load a new page [*].
With GWT, you don't need the server to create dynamic HTML content anymore. It's created dynamically on the client side (using static JavaScript code). When you need to load something from the server, you just load data objects (in JSON or XML format, or using GWT-RPC). The client may then use this data to build HTML snippets (to set innerHTML) or DOM objects to modify the browser's DOM tree.
With GWT, you don't have to build these snippets manually: You can use Widgets and UiBinder (client side HTML templating, enhanced with GWT tags and dynamic parameters).
[*] There are some special cases (e.g. if you have a https login page, whereas the rest of the app might use http), where you do load a new page, but that means either that your other page doesn't use GWT at all, or that you create a separate GWT module for it. Of course you can share some of the Java classes between these modules.
GWT is used to build applications like e.g. Google Reader or Gmail: this means that there is just 'one' page. You could have a 'window' inside that page that shows the contact information and a 'window' that shows the help information. When the users clicks the corresponding link you show that 'window'