Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Java.JDK.5.Edition (Wrox)

.pdf
Скачиваний:
31
Добавлен:
29.02.2016
Размер:
12.07 Mб
Скачать

Chapter 14

Making your JAR file executable is extremely simple. Just follow these procedures when creating your JAR file, and you will instantly be able to make it executable:

1.Compile all of your Java source code.

2.Create a manifest file, and enter in (at a bare minimum) the Manifest-Version and Main-Class properties. The Main-Class should point to the name of the class that contains the main method in the JAR file:

Manifest-Version: 1.0

Main-Class: Test

3.Create the JAR file using the following syntax:

Jar –cmf myManifest.mf test.jar *

4.Execute the JAR using the -jar option:

java –jar test.jar

The test.jar that was created should now execute without any problem if you specified the appropriate class in the manifest file that contains the main method for the application. It is extremely useful to make JAR files self-executing when the JAR files are GUI-driven applications and not based upon initial user input that would normally be supplied to the program via its ARG list in the main method of the application.

Analyzing Applets

Java applets are one of the very elite features of the Java programming language. Applets are programs that are designed to run within Web browsers that are compatible with and support Java. Applets can be embedded directly in HTML and can be used on Web pages to process user input or display information such as the current weather forecast. Applets can also exist outside of the Web browser and can have a much more robust feature set built into them like a standalone application would. The downside of making an applet that contains the same amount of features as say a standalone Swing application is that, the larger the applet, the more time it would take to download the applet for the user to use. The reason for this is that applets are downloaded every time a user accesses the Web page containing the applet. However, this is becoming less of an issue as the caching abilities of the Java plug-in improve with each new release of Java.

Basic Anatomy of an Applet

The basic anatomy of an applet is shown in the following class. You’ll notice that there is no main method as is required by a standard Java application. Applets do not require such a method and only require you to extend the class that will be run from the Applet class. Instead of having a starting point method, applets have methods that are event-driven. There are five basic event-driven methods that are very useful when developing a basic applet: init, start, stop, destroy, and paint. These methods are demonstrated in the following code:

636

Packaging and Deploying Your Java Applications

import javax.swing.*; import java.awt.*;

public class Welcome extends JApplet {

public void init() { System.out.prinln(“Initializing Applet”); repaint();

}

public void start() { System.out.println(“Starting Applet”); repaint();

}

public void paint(Graphics g) { g.drawString(“Welcome to Java Applets!”, 100, 50);

}

public void stop() { System.out.println(“Stopping Applet”); repaint();

}

public void destroy() { System.out.println(“Destroying Applet”); repaint();

}

}

The five methods shown in the code above are described in the following table.

Method

Description

 

 

init

This method is used to initialize the applet when it is either loaded for the first time

 

or reloaded thereafter.

start

After the applet has been initialized, the start method will be called. Here, you can

 

fire off threads or begin execution of code.

stop

If the user leaves the Web page that the applet is on or exits the Web browser, this

 

method is called. This allows you a chance to clean up code such as threads or code

 

that is in the middle of being executed.

destroy

This method is your last chance to perform any final cleanup that is necessary before

 

the applet is unloaded.

paint

The paint method is called any time the GUI needs to be updated based on users’

 

interaction with the applet.

 

 

637

Chapter 14

You do not have to override all of the above events to get a basic applet to work. For example, you could just override the paint method that displays a string containing the words, “Hello World!” and the applet would function just fine. There are also many other event methods that you can override that will allow you to react to user actions. For example, if you need to capture the mouse-down event, you could do this by overriding the method mouseDown. These are standard AWT events. In more advanced applet implementations, you would most likely use Swing to build your applet.

Packaging an Applet for Execution

Applets are not executed the same way as normal Java applications. They are generally embedded in an HTML page and executed by a Java-compatible browser such as Internet Explorer. Internet Explorer uses the Java plug-in to execute applet code. For development purposes, you can also execute applets that are embedded in HTML files by using the appletviewer command. For example:

appletviewer com/wrox/Welcome.html

The example above executes the applet that is embedded in the Welcome.html file. The HTML code is shown in the following example:

<HTML>

<HEAD>

<TITLE> Welcome to Java Applet </TITLE> </HEAD>

<BODY>

<APPLET CODE=”Welcome.class” CODEBASE=”com/wrox/” WIDTH=200 HEIGHT=50> <PARAM NAME=”exampleParam” VALUE=”whatever”>

</APPLET>

</BODY>

</HTML>

The <APPLET> and </APPLET> tags designate the specific tags belonging to the applet that will be executing. The CODE attribute is used to reference the class name that contains the compiled applet class. The CODEBASE attribute is optional and specifies the base directory of where the applet’s class is stored. If you do not use this attribute, then the directory where the HTML file resides is used as the base directory.

The <PARAM>and </PARAM> tags allow you to specify specific parameters that you may want to pass to the applet when it is loaded. These tags have two attributes: a NAME and a VALUE. The VALUE can then be retrieved in code via the init method of the applet as depicted in the following example:

public void init() {

String sValue = getParameter(“exampleParam”);

if (sValue != null) {

// This will print out the value “whatever” System.out.println(sValue);

}

}

The getParameter method is used to retrieve the value of a specified parameter. In this case, you are retrieving the exampleParam value and displaying it to the user.

638

Packaging and Deploying Your Java Applications

Examining Applet Security

When creating an applet and deploying it, there are certain security restrictions that are enforced upon applets by the Java Environment. Applets usually cannot make network connections to any other machines except to that of the host they were downloaded from. Applets are generally restricted from writing or reading files from the client’s machine. Also, applets cannot start applications that reside on the client’s machine. These are not all the restrictions that are enforced on applets, but rather the most obvious. You can relax security restrictions by using SecurityObjects and Access Control Lists.

Applets cannot read or write files if they are considered untrusted. All applets that are downloaded are considered untrusted unless specified otherwise. In order to make an applet trusted, applets must be signed by an identity marked as trusted in your database of identities. Generally, your Web browser can also ask you if you trust the server that the applet is coming from. This aids in giving the applets more rights to your computer. When developing applets on your machine, they are generally trusted because they are being accessed from your local machine. So, you may not see the security restrictions that a remote user would see when downloading your applet. It is important that you understand what your applet users can and cannot do before deploying your applet. Refer to your Java documentation for more information on Applet Security specifics.

Exploring Web Applications

Web applications are applications that can be deployed on application servers as Web Archive files or, as the Java community calls them, WAR files. WAR files are the same format as JAR files, and, in fact, developers use the JAR tool to create WAR files. The difference is the directory structure and files that comprise the WAR file are different than a standard JAR. WAR files generally contain JSPs, servlets, HTML, images, audio files, XML files, and numerous other files that you may find while surfing a normal Web site.

So, static and dynamic content make up WAR files, but WAR files themselves are used for two basic reasons. One is to be front-end presentation oriented, concentrating heavily on user experience. The second is a service-oriented approach, which means that the WAR file is used to provide a service to other applications that are calling it. The most common term used for this type of Web application is Web Service.

You can have an enormous architecture that is comprised of Web Services that may use the Simple Object Access Protocol (otherwise known as SOAP) to communicate. If you add security on top of the SOAP layer, you will have a very complicated system to package and deploy because you will need to manage certificates, keystores, signed JARs, SSL, and other security-related components and protocols. Therefore, WAR files can become much more difficult to deploy in enterprise-level usages.

However, in its simplest form, WAR files are very easy to use and are a dream for packaging and compressing Web site resources that are comprised of static and dynamic data like form processing or shopping carts. The WAR file format allows the whole Web site to be portable and makes it very easy to deploy on other vendor application servers that are J2EE compliant.

639

Chapter 14

Examining the WAR Directory Structure

As stated previously, there are differences between a JAR file and a WAR file. WAR files have additional file and directory structures that are used for deploying the WAR file on to the application server of choice. Figure 14-3 is an example of a Web application that is deployed on Tomcat.

 

images

 

 

file.png

 

 

folders.png

classes

forum

 

 

 

 

Category.class

index.jsp

 

Driver.class

newcategory.jsp

WEB-INF

Post.class

newpost.jsp

 

Topic.class

newtopic.jsp

web.xml

 

post.jsp

 

web-app_2_3.dtd

libs

topic.jsp

 

 

 

 

cglib-2.0-rc2.jar

 

 

commons-collections-2.1.jar

 

 

commons-logging-1.0.3.jar

 

 

dom4j-1.4.jar

Figure 14-3

 

 

The above is the forum example Web application directory structure that was used in Chapter 6. This file is named forum.war, and, at the root level, it contains all the JSPs needed for the user interface components. The images directory simply stores images that are used by the JSPs. The WEB-INF is the important directory and is the directory that distinguishes a WAR file from a JAR file. The web.xml in the directory is a required file and is officially called the Web application deployment descriptor. The classes directory is where you would store your compiled classes that can be used by JSPs or servlets. The libs directory contains all the necessary JAR files to make your Web application work.

Understanding the WAR Deployment Descriptor

The Web application deployment descriptor is used to configure your Web application. In this example, this deployment descriptor is called web.xml. The deployment descriptor contains the following basic XML elements that are configurable and must appear in this order.

Element

Description

 

 

icon

The icon element has two child elements that represent the small icon and

 

the large icon for a GUI tool.

display-name

This element contains a short name this is intended for tools to use.

 

It doesn’t have to be unique.

description

This element is used to describe information to the parent element and is

 

used in a number of different elements.

 

 

640

 

 

Packaging and Deploying Your Java Applications

 

 

 

 

Element

Description

 

 

 

 

distributable

By having the distributable element present, you are signifying that the

 

 

Web application is programmed to be distributed in a servlet container.

 

context-param

This element is used to initialize a Web application’s servlet context.

 

filter

Filter elements are specifically used to map servlets or URL patterns for

 

 

Web applications.

 

filter-mapping

The filter-mapping element is used by the container to decide which filters

 

 

to map a request to.

 

listener

This element and its subelements are used to declare Web application lis-

 

 

tener beans. You simply specify the class that is the listener bean.

 

servlet

The servlet element and its subelements are used to designate a specific

 

 

class or JSP as a servlet and to provide specific configurations for that

 

 

servlet.

 

servlet-mapping

This element simply defines a mapping between a servlet and a specific

 

 

URL pattern.

 

session-config

This is a useful element for configuring the session information for a Web

 

 

application.

 

mime-mapping

The mime-mapping element allows you to map between a file extension

 

 

and a mime type.

 

welcome-file-list

This is the element that is used to determine the first page to be displayed

 

 

when users hit your Web application.

 

error-page

When errors occur, the mapping in this element allows you to map and

 

 

error code to an error page. Very handy.

 

taglib

You should use this element to describe the JSP tag library.

 

resource-ref

This element allows you to specify external resources to use in your Web

 

 

application.

 

security-constraint

With this element you can associate security restraints with a particular

 

 

resource.

 

login-config

This element is used to specify the authentication method to be used for

 

 

the Web application as well as any authentication constraints.

 

security-role

This element allows you to define security roles for your Web application.

 

env-entry

This element is used to specify environment entries that can be picked up

 

 

by classes, JSPs, and so forth that exist in your Web application.

 

 

 

Though the table explains the different elements and attributes used when creating a deployment descriptor, it can be confusing to try and understand how to use them. The following is a sample web.xml file for Tomcat that will hopefully shed some light on how to appropriately use some of the elements discussed in the previous table:

641

Chapter 14

<?xml version=”1.0” encoding=”ISO-8859-1”?>

<!DOCTYPE web-app

PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN” “ http://java.sun.com/dtd/web-app_2_3.dtd”>

<web-app>

Deployment descriptors are XML files; therefore, they require a standard prolog that is displayed in the previous example:

<display-name>HelloWAR</display-name> <description> HelloWAR </description>

<servlet>

<servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> <load-on-startup>1</load-on-startup>

</servlet>

The <servlet> element allows you to specify information about a servlet that exists in the Web application. In this case, I am referring to the servlet, HelloServlet. The <load-on-startup> attribute signifies that the application server should load the servlet upon startup:

<!--Creating mime type mappings --> <mime-mapping>

<extension>txt</extension> <mime-type>text/plain</mime-type>

</mime-mapping> <mime-mapping>

<extension>html</extension> <mime-type>text/html</mime-type>

</mime-mapping> <mime-mapping>

<extension>htm</extension> <mime-type>text/html</mime-type>

</mime-mapping> <mime-mapping>

<extension>gif</extension> <mime-type>image/gif</mime-type>

</mime-mapping> <mime-mapping>

<extension>jpg</extension> <mime-type>image/jpeg</mime-type>

</mime-mapping>

The <mime-mapping> element contains two attributes called <mime-type> and <extension>. These are used specifically for mapping mime types to file extensions:

<welcome-file-list> <welcome-file>index.html</welcome-file>

</welcome-file-list>

642

Packaging and Deploying Your Java Applications

One of the most common elements, <welcome-file-list>, is shown in the previous example. This element has an attribute called <welcome-file> that lets you specify the file to be loaded when a user first accesses your Web application:

<security-constraint> <web-resource-collection>

<web-resource-name>Hello View</web-resource-name> <url-pattern>/hello.jsp</url-pattern>

</web-resource-collection> <auth-constraint>

<role-name>tomcat</role-name> </auth-constraint>

</security-constraint>

<login-config> <auth-method>BASIC</auth-method> <realm-name>Hello View</realm-name>

</login-config>

<security-role> <description>

An example role defined in “conf/tomcat-users.xml” </description>

<role-name>tomcat</role-name> </security-role>

</web-app>

The <security-constraint> element contains attributes that allow you to assign roles to specific Web resources. In this example, the role of Tomcat is being assigned to hello.jsp. This means that only users with the specified role of Tomcat can view the JSP. The <security-role> element shows you how to define a role in the Web application deployment descriptor.

Packaging Enterprise Java Beans

Chapter 10 discusses the various classes that are needed to develop different types of EJBs and also has a very good loan calculator example that will help you get your feet wet with EJBs. The inherent problem with deploying EJBs is that the EJB specification isn’t specific enough about the deployment process and allows the vendors of application servers to interpret the art of deploying EJBs the way they see fit. Now, the vendors have an opportunity to interject their own proprietary deployment requirements. This makes it a painful experience if you want to move your EJBs from one vendor to another. So, the best advice is to simply read the specific documentation on the vendor of choice that you want to house your EJBs.

All is not lost though in terms of deployment standardization. There is one common file that must exist in all EJBs, and that is the ejb-jar.xml that resides in the META-INF directory of your EJBs’ JAR file. The ejb-jar.xml file is the basic EJB deployment descriptor that must be used by the EJB container to locate the necessary classes, interfaces, security restrictions, and transaction management support. The ejbjar.xml file will usually coexist with the vendor’s application server deployment descriptor. For example, if you were to use JBoss as your application server, you would have to also configure a jboss.xml file with your EJBs. Chapter 10 has a very good demonstration and explanation of what type of information is contained in the ejb-jar.xml file. It is recommended that you review the examples that are in Chapter 10 for specific information on how to deploy and package an EJB application.

643

Chapter 14

Inspecting Enterprise Archives

Once you have developed your EJBs and WARs, you should have all the components of a full application — from the business logic (and maybe database logic) to the user interface for the Web. You may have just a couple files or perhaps a large number of files. Either way, you might be looking at your application and wondering if there is a way to tidy up that directory. If you have multiple applications that use distinct EJBs and WARs, then you’re almost definitely thinking “there must be some way to easily group and distinguish these two applications.” You would be correct in thinking this, and this is where Enterprise Archives (EARs) come into the picture. Even though mistakenly called Enterprise Applications at times, this name might be more meaningful, because inside an EAR file resides all your EJBs and WARs.

An EAR file has its own descriptor file, much like EJBs and WARs. Other than that the directory structure of an EAR is arbitrary, you can develop any scheme that best suits your application. An EAR file may look like Figure 14-4. Note that there is one WAR file but multiple EJB JAR files packaged inside the EAR. This grouping is useful to make your application a single logical unit.

WAR

User Interface for the Web

EJBs packaged inside a JAR file

More EJBs packaged inside a JAR file

Figure 14-4

The EAR Descriptor File

The descriptor file is named application.xml and is located in the META-INF directory in the EAR file. The main component of this file is the module element. The following is an example of this file:

<?xml version=”1.0” encoding=”UTF-8”?>

<application xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application_1_4.xsd” version=”1.4”>

<display-name>Example EAR file</display-name> <description>Simple example</description>

644

Packaging and Deploying Your Java Applications

<module>

<ejb>ejb1.jar</ejb>

</module>

<module>

<ejb>ejb2.jar</ejb>

</module>

<module>

<web> <web-uri>mainUI.war</web-uri> <context-root>web</context-root>

</web>

</module>

</application>

Each instance of the module element specifies a particular module to load. This module can be an EJB (using the ejb element), a Web application (using the Web element), a connector (using the connector element), or a Java client module (using the Java element). The context-root element for Web applications specifies the root directory to use for the execution of the Web application.

Deployment Scenario

The previous section described a straightforward approach to packaging and using EAR files. What happens, though, if you have multiple applications that all depend upon some central component? Take a look at Figure 14-5. In this scenario, a second EAR file depends upon a component packaged in the first.

APPLICATION A

APPLICATION B

WAR

WAR

User Interface for

User Interface for

the Web

the Web

EJBs packaged

 

inside a jar

 

More EJBs

EJBs packaged

packaged inside a

inside a jar

JAR file

 

Figure 14-5

 

645

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]