How do I load an applet from a servlet or JSP? Where do I place my applet class files?

Alex Chaffee

An applet is executed on the client side (browser), not on the server side (servlet container). You need to place the applet class files in a location accessible from the browser, which means you have to treat them like normal files (like HTML or GIF files that you want the browser to load). Thus they need to go in the webapp directory tree, but not in the WEB-INF subdirectory.

It is best to think of the set of applet class files as entirely different from the set of servlet class files. They will be loaded by different Virtual Machines, and may even have different versions of classes. It is a simple matter to configure your build environment (Ant or make) to create copies of common class files in the two different classpath directories.

Since the concept of "current directory" is kind of fuzzy in the Servlet API, it is usually easiest to make a separate directory just for your applet class files, and use the optional CODEBASE parameter to the APPLET tag. Here is an architecture that works well:

Then if your servlet generates a line like:
out.println("<APPLET CODE='MyApplet.class' WIDTH=50 HEIGHT=50 CODEBASE='/applets'>">;
The browser will be able to load MyApplet.class and Util.class from your /applets web directory. It will not be able to load anything from WEB-INF/classes, since those files are accessible only by the servlet engine.

Note that loading an applet from a page generated by a servlet is much the same as loading an image. It is also easier to use a common "images" directory in that case, so that images can be loaded from any page regardless of "current" directory.

See also:

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact