Web technologies -- Laboratory 10 -- 2009-2010 -- info.uvt.ro
There are cases when it is better to offer window-based application to end-users rather than web-based ones. Applications which cannot be rendered as web-based are good examples.
The simplest way to achieve this is to publish your application on a website either as an applet or as a Java Web Start application.
Java Applets
[edit]Applets allow users to run Java applications embedded inside their browsers.
There are several steps required in order to offer a fully functional applet to users:
- code the applet
- embed the applet in the HTML code
Coding the Applet
[edit]Applets are nothing else than Java classes which extend the Applet (AWT) or JApplet (SWING) base class:
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class HelloWorld extends JApplet {
// Called when this applet is loaded into the browser.
public void init() {
// Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel lbl = new JLabel("Hello World");
add(lbl);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
The Applet and JApplet classes provide a simple framework for working with applets. This framwork includes the following methods:
- init - used for initialising the Applet. Works as a constructor
- start - used when some after-init operations are required
- stop - used together with start. It suspends the applet's execution when the user is not using it
- destroy - additional garbage collector. Most applets do not need it as most of the work is done in the stop method
Embedding the Applet inside HTML code
[edit]Embedding an applet inside a HTML page is straightforward. Users need only use the <applet> tag in order to offer this feature:
<html>
<head>
<title>Java Example</title>
</head>
<body>
<h1>Simple Applet example</h1>
<applet code="HelloWorld.class" width="200" height="100">
</applet>
</body>
</html>
Some of the most used attributes for the <applet> tag are:
- code - the Java class of the applet
- codebase - the path to the applet. Can be omitted if the applet is in the same folder as the HTML page
- name - the name of the Applet. Can be used for inter-applet communication
- height - the height of the applet in pixels
- width - the width of the applet in pixels
- etc.
Applets can be customized by specifying parameters through the <param> tag. For instance one can specify the image an applet could use, its font and color, etc:
[...]
<applet code="ShowImage.class" width="200" height="100">
<param name="image" value="nice-image.jpg"/>
</applet>
[...]
Links:
Java Web Start
[edit]Java Web Start (or better known as javaws) allows user to start Java applications directly from the Internet by using a browser as an intermediary. A specific requirement is for applications to be signed by trusted authorities.
NOTE: Contrary to applets, javaws eliminates some of the security restrictions on the former and allows applications perform operations such as file manipulation.
In order to deploy a javaws application you need to do the following (for Linux users, altough for Windows the steps are similar):
- create a jar archive using either ant or jar as tools. Be sure to place all your files (java classes, images, text files, etc.) inside it. Also be sure to maintain the relative file paths used in the application for accessing them. Be sure you give proper access rights to any file (image or text placed in the jar) your application will use (chmod +r).
- sign the jar using a digital certificate. In order to do this you must first generate one by using the keytool command followed by the jarsigner command. Don't forget to remember the password that you have provided as it will be necessary later. Also store in a safe place your certificate file. The following code fragment exemplifies how these commands can be used (from a shell window):
keytool -genkey -keystore yourKeyStore -alias yourAlias
jarsigner -keystore yourKeyStore -storepass yoursecret yourJarFile.jar yourAlias
You can create the jar from the command line by running:
jar cvf yourJarFile.jar yourJavaClass.class
NOTE: The keytool and the jarsigner are found inside the JRE folder.
- create a JNLP (Java Network Launching Protocol) file. It specifies how to launch Java Web Start applications and consists of a set of rules defining how exactly to implement the launching mechanism. The following code fragment shows an example for jnlp file called example.jnlp handling a jar named example.jar:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Use ip address or domain name and not localhost or 127.0.0.1 in the codebase as you will have problems when trying to access it from another machine-->
<jnlp spec="1.0+" codebase="http://YOUR_ADDRESS" href="YOUR_JNLP.jnlp">
<information>
<title>Example v1.0</title>
<vendor>Your Name Here</vendor>
<homepage href="http://www.your.domain.here/" />
<description>Simple example of a JavaWS application</description>
</information>
<offline-allowed/>
<security>
<!--<j2ee-application-client-permissions/>-->
<!-- In this case simply allow all. Should be changed however depending on application -->
<all-permissions/>
</security>
<resources>
<!-- The name of your jar -->
<jar href="YOUR_JAR_FILE.jar"/>
<!-- The JRE version to use -->
<j2se href="http://java.sun.com/products/autodl/j2se" onclick="javascript:mytracker(this.href);" version="1.5+"/>
</resources>
<!-- Specify the main class -->
<application-desc main-class="YOUR_MAIN_CLASS"/>
</jnlp>
NOTE: we can notice that the JOGL jars are grabbed at runtime from the site. In this way we need not bother moving them also to the web server
- Move your jar, jnlp and other dependent jars to the web server. In our case we will use an Apache Tomcat Server but any other server can be used. The files need to be moved to the $CATALINA_HOME/webapps/yourApp/ directory so that both the jar and the jnlp file should be located on the same level. For any additional libraries create a lib/ directory and place them inside. In our example we could move the example.jar and example.jnlp to $CATALINA_HOME/webapps/example-jnlp/
- Restart the web server and enter the following URL in your favourite browser: http://ipaddress:8080/yourApp/yourJNLPfile.jnlp. If everything goes fine you should see your application running. As an alternative you could use the command: javaws http://localhost:8080/yourApp/yourJNLPfile.jnlp from command line. In our example we simply need to call http://192.168.1.64:8080/example-jnlp/example.jnlp.
NOTE: You do not need to restart your web server each time you modify the jar.
IMPORTANT: When reading files be sure to use an InputStreamReader as follows, or the application will not work:
import java.net.URL;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
[...]
URL location = Thread.currentThread().getContextClassLoader().getResource(filename);
InputStreamReader isr = new InputStreamReader(location.openStream());
LineNumberReader input = new LineNumberReader(isr);
[...]
IMPORTANT the same applies for binary files such as images:
import java.io.BufferedReader;
import javax.imageio.ImageIO;
[...]
BufferedImage img = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream(filepath));
[...]
or:
import java.net.URL;
import java.awt.Image;
public MyClass {
[...]
URL location = MyClass.class.getClassLoader().getResource(filepath);
Image img = Toolkit.getDefaultToolkit().getImage(location);
[...]
}
NOTE: The filepath variable must point to a path relative to the package folders. For example given the following jar structure:
- file.jar
- mypackage
- *.class
- META-INF
- certificate files
- images
- *.jpg
- mypackage
the filepath variable is "images/*.jpg".
Links:
Exercises
[edit]- Create simple webpage which offers the following:
- a menu page for accessing three predefined applets. The applets can be found at http://www.echoecho.com/freeapplets.htm page.
- a page which allows users to run a Java Application using javaws. The application should display a single image. (See http://stackoverflow.com/questions/299495/java-swing-how-to-add-an-image-to-a-jpanel for details on how to display an image using SWING)
NOTE The website should be HTML 4.01 strict valid