The Web Application Package

So far, we've talked about servlets as distinct objects. In what we've seen, the only thing binding them together is the notion of a shared HttpSession object. As you might guess, it is desirable to package servlets (and other Web resources) into a single package. We might want to do this so that we can host multiple applications on a single WebLogic Server, update a group of resources wholesale, or easily refer to a group of multiple resources under a single name.

About Web Applications

As of the servlet specification Version 2.2, a new feature was added to J2EE: the Web Application. A Web application is a collection of servlets, HTML pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors.

By its nature, a Web application is rooted at a specific path within WebLogic Server. For example, a Web application could be located at http://www.bea.com/mywebapp. All requests that start with this prefix are handled by the Web application designated for that path. Web applications are typically bundled together to form a Web Archive (WAR) and are designated by a .war suffix in the filename.

The next section discusses how to build Web applications. It also covers the mechanics of how to package the Web archive, write the appropriate deployment descriptors, set up WebLogic Server to use a Web archive, and other topics.

Web Application Overview

A Web application can include:

  • Servlets

  • JSPs

  • Utility classes

  • Static documents (HTML, images, sounds, etc.)

  • Client-side applets, beans, and classes

  • Descriptive meta information that ties all the preceding elements together

Of these items, the last is the most important. Typically, the descriptive meta information (documents that describe other documents in the Web application) resides in XML encoded files. The XML files describe how the elements combine to make a single application.

Web Archive Organization

Web archives have a hierarchical organization. The root of the archive maps to the root of the application path, for example, http://www.bea.com/mywebapp. Other components reside in particular directories in the Web archive. To illustrate, let's say that we have the following components in our Web archive:

/index.html
/howto.jsp
/feedback.jsp
/images/banner.gif
/images/jumping.gif

Top-level files such as index.html map to http://www.bea.com/mywebapp/index.html. The image jumping.gif maps to http://www.bea.com/mywebapp/images/jumping.gif.

Servlet classes, supporting classes, and meta documents are included in the WEB-INF directory. In a typical Web application, this might look like the following:

/WEB-INF/web.xml ← The main meta document

/WEB-INF/lib/jspbean.jar ← Supporting classes for JSPs

/WEB-INF/classes/com/mycorp/servlets/MyServlet.class ← Servlet classes

/WEB-INF/classes/com/mycorp/util/MyUtils.class ← Utility classes

The components stored in the /WEB-INF directory of the archive are not directly visible to the client. They are never sent to the Web browser. Instead, they are used by the Web application either to directly service clients or as infrastructure to service clients. The web.xml deployment descriptor ties all these components together for WebLogic Server.

Building a .war File

There are four steps to build a .war file out of the items in the directory structure previously described.

Step 0: Creating a Directory Structure

Create a working directory for your Web application. This discussion uses the directory C:dev13; however, you can use whatever directory you like. Open a command shell and change to that directory. Copy the CookieServlet example code fragments from their location on the CD into your new directory. You should see something like Figure 3-18 after you have created your directory structure.

Figure 3-18. Directory Listing for Building the CookieServlet Package


Step 1: Setting Your Environment

You can use the environment scripts included with WebLogic Server as we have in the previous examples. Depending upon the location of your WebLogic Server installation, choose the setEnv.cmd script, located in the mydomain directory:

c:eawlserver6.0configmydomainsetEnv.cmd

You should see something like Figure 3-19.

Figure 3-19. Setting the Environment


Step 2: Running the Jar Utility

To run the jar utility, simply type “jar” at the command line with the options to instruct the utility to create a new file:

jar cvf cookieServlet.war *

The “c” option tells the jar utility to create a new file. The “v” option says that we would like for jar to work in a verbose mode, which means that it outputs details about everything that it does. And finally, the “f” option tells jar that we specify the files for it to use. The third and fourth entries in the command line tell jar the name of the package to create and the files to include. The asterisk (*) is a wild card that instructs jar to include all the files in this directory, and all subdirectories.

After typing the preceding into the command line, you should see something like Figure 3-20.

Figure 3-20. Creating the Archive


You now have a new war file that can be deployed in WebLogic Server. Note that if you look at the build script (build.bat) included with all the examples, these steps are automatically done for you.

You can view the contents of the war file in any compression utility that supports the Zip file format. For example, the war file can be loaded into WinZip (http://www.winzip.com). See Figure 3-21.

Figure 3-21. Looking at the .war File with the WinZip Utility


The directory called meta-inf is automatically created for you. It includes information about the package itself.

IMPORTANT

Note also that this Web archive includes both the build script and the source code in the application. In a real-world application, you probably would not want to make the source code to your application available to anyone visiting your site. For that reason, do not put it in your Web archive file unless you wish to make it available to users of your application.


web.xml

WebLogic Server needs to know information about the Web application, such as what components compose the Web application, where they are located, what type they are, and so forth. As defined by the servlet standard, this information about Web applications is included in multiple meta documents, which are also known as deployment descriptors.

In the case of WebLogic Server, there are two different deployment descriptors for Web applications. The first is a generic deployment descriptor named web.xml, which is placed in the /WEB-INF/ directory in the Web application jar file. The second is a WebLogic Server–specific deployment descriptor called weblogic.xml. This deployment descriptor is used to define external resources that are WebLogic Server–specific, such as such as DataSources, EJBs, or a Security realm.

In order to create web.xml files and to understand how they work for Web applications, it is best to learn by example. In this section, we show three examples of web.xml files, and discuss what they configure. These files are available on the CD accompanying this book.

Sample1-web.xml

This sample web.xml is very simple. It is the deployment descriptor for the first Hello World servlet.

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-
app_2_2.dtd">

<web-app>

  <context-param>
    <param-name>weblogic.jsp.compileCommand</param-name>
    <param-value>javac</param-value>
  </context-param>

  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>book.ch3.HelloServlet</servlet-class>
  </servlet>

  <welcome-file-list>
    <welcome-file>/HelloServlet</welcome-file>
  </welcome-file-list>

  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

If you are familiar with HTML, this format should look very familiar. The first entry defines the document type to be an XML document. The document type description (DTD) tells WebLogic Server what format is being used for the deployment descriptor XML. Note also that this tag includes an external URL. WebLogic Server does not use this external URL, but relies upon a local copy. This enables WebLogic Server to work with XML, even when not connected to the Internet.

The second tag, <web-app>, signifies a Web application.

The first tag inside the Web application tag specifies the Java compiler to be used in building this application. This second tag specifies an included server class. The third, <welcome-file-list>, specifies what servlet should be activated by default when someone accesses the Web application. So, if someone visits http://127.0.0.1:7001/, the Hello Servlet is activated. Note that the Web application is deployed at the URL:

http://<server name>/<Web application archive name>/

So, a Web application archive named “foo.war” is automatically deployed at:

URL: http://<server name>/foo/

The last entry specifies the URL pattern to which the Hello Servlet should map. In this case, we've specified that it should map to any URL pattern for the application. In a real-world application, you specify the full path for the servlet URL.

Sample2-web.xml

This sample web.xml includes a number of other options. Comments about each component are included.

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-
app_2_2.dtd">

<web-app>

The <display-name> tag signifies the name used when the application is displayed in something like the WebLogic Server console:

<display-name>A Simple Application</display-name>

The <context-param> tag specifies a parameter to be included in the ServletContext, which is a topic covered in the next section. In this case, the ServletContext now includes a parameter named Webmaster, with the value of the email address of the Webmaster:

<context-param>
    <param-name>Webmaster</param-name>
    <param-value>[email protected]</param-value>
</context-param>

The following specifies a servlet with the name catalog. It specifies the class to be used, com.mycorp.CatalogServlet and some initial parameters for the servlet. These are also located in the ServletContext for the servlet:

<servlet>
     <servlet-name>catalog</servlet-name>
   <servlet-class>com.mycorp.CatalogServlet</servlet-class>

   <init-param>
        <param-name>catalog</param-name>
        <param-value>Spring</param-value>
   </init-param>
</servlet>

The following maps the catalog servlet to a URL pattern. WebLogic Server receives requests for any URL beginning with catalog/.

<servlet-mapping>
     <servlet-name>catalog</servlet-name>
   <url-pattern>/catalog/*</url-pattern>
</servlet-mapping>

The following specifies the default timeout for HTTP session objects—in this case, 30 seconds:

<session-config>
     <session-timeout>30</session-timeout>
</session-config>

The following specifies a mime type extension to be used. If a file with the .pdf suffix extension is sent, WebLogic Server affixes the mime type as follows:

<mime-mapping>
     <extension>pdf</extension>
   <mime-type>application/pdf</mime-type>
</mime-mapping>

The next specifies the file to be used as a welcome file to the Web application. If someone accesses the Web application without specifying a file (such as http://www.girdley.com/myApp/), WebLogic Server attempts to display the welcome file. The files are chosen in order, with highest precedent on the file listed first:

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

The following specifies the page to be used in the event of a 404 (File Not Found) HTTP Error:

<error-page>
     <error-code>404</error-code>
     <location>/404.html</location>
</error-page>

The following concludes the definition of the Web application:

</web-app>

Note that you can set the error page for any number of http://error codes. The complete list of all possible http://error codes is in the HTTP specification, available on the Internet at ftp://ftp.isi.edu/in-notes/rfc2616.txt.

You also can map an error page to an exception type. To do this, instead of listing an error code, list the fully qualified name of your Java exception type:

<error-page>
<exception-type>
      com.learnweblogic.exceptiontype
</exception-type>
<location>/error.html</location>
</error-page>

The complete Sample2-web.xml listed here is located on the CD accompanying this book in the codech3 directory:

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

     <display-name>A Simple Application</display-name>

     <context-param>
         <param-name>Webmaster</param-name>
       <param-value>[email protected]</param-value>
     </context-param>

     <servlet>
          <servlet-name>catalog</servlet-name>
        <servlet-class>com.mycorp.CatalogServlet</servlet-class>

        <init-param>
             <param-name>catalog</param-name>
             <param-value>Spring</param-value>
        </init-param>
     </servlet>
     <servlet-mapping>
          <servlet-name>catalog</servlet-name>
        <url-pattern>/catalog/*</url-pattern>
     </servlet-mapping>

     <session-config>
          <session-timeout>30</session-timeout>
     </session-config>

     <mime-mapping>
          <extension>pdf</extension>
        <mime-type>application/pdf</mime-type>
     </mime-mapping>

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

     <error-page>
          <error-code>404</error-code>
          <location>/404.html</location>
     </error-page>

</web-app>

Other web.xml Options

Many of the other options specifically support security, EJB, or JSP. We will cover these other web.xml options in subsequent chapters.

For your reference, here are some other important options that can be included in a web.xml file, with examples of each.

Icon Element

The icon element contains a small-icon and a large-icon element, which specify the location of a small and a large image used to represent the Web application in a GUI tool. At a minimum, tools must accept GIF and JPEG format images. The small-icon element contains the location of a file containing a small (16×16 pixel) icon image. The large-icon element contains the location of a file containing a large (32×32 pixel) icon image.

<icon>
<small-icon>filename</small-icon>
<large-icon>filename</large-icon>
</icon>

Display-Name Element

The display-name element contains a short name that is intended to be displayed by GUI tools.

<display-name>name</display-name>

Description Element

The description element provides descriptive text about the parent element.

<description>name</description>

The ServletContext

A Web application needs a way to tie all its components together programmatically. For example, as part of a Web application, a servlet should be able to define elements that other servlets can use. To solve this problem, the ServletContext is available as part of the specification. It is a variable specific to a given Web application that is used to define how a given servlet looks at the rest of the Web application. ServletContext also includes information on where external resources are located in which the servlet can rely.

Some of the things that the servlet can do with the ServletContext include:

Getting the ServletContext

The process of acquiring the ServletContext is very straightforward. The following simple servlet demonstrates this:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ContextServlet extends HttpServlet {

   public void doGet(HttpServletRequest req, HttpServletResponse
res)
        throws IOException
    {

        // Locate Our Servlet Context
								ServletContext sc = getServletConfig().getServletCon-
								text();

        // Use the Context here.

    }
}

Setting and Getting Attributes

The ServletContext object offers you the ability to set and retrieve attributes. The attributes can be Java objects. After they are set in the ServletContext, attributes are then available to any other servlet that is part of the same Web application. Attributes are useful any time you want to track a resource and share it among multiple servlets.

Context attributes exist locally to the instance of WebLogic Server in which they are created. This prevents the ServletContext from being used as a distributed shared memory store. In later sections, we describe how to share data among multiple servers in the distributed computing environment that WebLogic Server provides.


The following simple servlet shows how to acquire the ServletContext object, add an attribute, retrieve an attribute, and retrieve an Enumeration of all the attributes available in the ServletContext:

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ContextServlet extends HttpServlet {

   public void doGet(HttpServletRequest req, HttpServletResponse
res)
      throws IOException
    {

      // Locate Our Servlet Context
      ServletContext sc = getServletConfig().getServletContext();

      /*
        Set an attribute named "attrib1" that contains
        a value of "my value":
      */
      sc.setAttribute("attrib1", "my value");

      /*
        Get an Enumeration of all the attributes
        currently active in our ServletContext.
      */
      Enumeration myAttributes = sc.getAttributeNames();

      /*
        Remove attribute named "attrib1".
      */
      sc.removeAttribute("attrib1");

    }
}

The above example employed a number of the methods available in ServletContext. The first declared a new attribute named "attrib1" and set its value equal to a string literal of "my value". It is notable that setAttribute() can incorporate any derivative of java.lang.Object (that is, any Java object) as an attribute. You should also note that calling setAttribute()on an attribute that already exists updates the value of that attribute.

After setting the first attribute, we call the getAttributeNames() method, which returns a java.util.Enumeration of all the names of the attributes available in the ServletContext. This is useful if you need to locate an attribute but you're unsure of its name. Finally, we call the removeAttribute() method to remove the attribute that we added.

The following summarizes the methods that are available for attributes:

  • public java.lang.Object getAttribute(String name)— Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

  • public java.util.Enumeration getAttribute Names()— Returns an enumeration containing the attribute names available within this servlet context.

  • public void removeAttribute(String name)— Removes the attribute with the given name from the servlet context.

  • public void setAttribute(String name, java.lang.Object object)— Binds an object to a given attribute name in this servlet context.

Using Web Application Resources

Web applications can also include resources that are defined and contained in its package. These resources can be virtually anything that is static content: text files, images, or other multimedia. They must also be included in the Web application package itself in order to be accessed by components of the Web application.

The ability to access resources from your servlets can be very useful. Some uses include:

  • Dynamically processing and filtering images for a given user. For example, you might want to overlay a user's name on top of a standard image, to customize it.

  • Simple queries of text resources or other data stored in the Web application. This is very helpful for rapid prototyping.

Your application locates and accesses resources using the ServletContext object. Two methods are useful to locate and access resources:

  • public java.net.URL getResource(String path)— Useful when you wish to understand the complete URL of a given Web application resource. You supply a relative path to the resource; you are returned the full URL.

  • public java.io.InputStream getResourceAs Stream(String path)—This method returns a reference to an InputStream whose source is the resource specified by path.

In both of these methods, the parameter is a relative path to the resource from the root of the Web application. To illustrate, if you have a resource contained in your Web application package in a subdirectory named /luke/images/ and the resource is named myimage.gif, the relative path would be /luke/images/myimage.gif.

The following locates the full URL for this image and makes it available as an InputStream:

    // Import classes, define servlet, etc. here.

    public void doGet(HttpServletRequest req, HttpServletResponse
res)
       throws IOException
     {

      // Locate Our Servlet Context
      ServletContext sc = getServletConfig().getServletContext();

      // Get the Full URL to Our Image:
      java.net.URL myURL = sc.getResource("/luke/images/myim-
age.gif");

      // Get Our Image As an InputStream:
      java.io.InputStream myIS =
    sc.getResourceAsStream("/luke/images/myimage.gif");
    }

Note that any resource accessed in this manner is treated as static content. As you'll see later, JSPs are stored as text files and compiled automatically. If you were to try to load a JSP using these methods for resources, you would see the text of the JSP page and not the output of the executed code. If you wish to include the output of another executable component of the Web application such as a JSP or a servlet, you should take advantage of the RequestDispatcher interface discussed in the next section.


Using the RequestDispatcher

In many cases, a Web application requires that a client be directed to another servlet. One way of doing this is to send a redirect back to the client. However, this is inefficient because it requires the client to make another HTTP request.

The solution for this problem is the servlet RequestDispatcher mechanism. This mechanism allows requests to be handled by another Web resource on the server such as a servlet, JSP, or HTML page. This is done in a way that is completely transparent to the user.

There are two ways to use the RequestDispatcher functionality: forwarding a request to other resources, or including the output of other resources in your servlet output.

Forwarding to Other Resources

Using the RequestDispatcher requires information stored in the ServletContext of the servlet. We can use the following to locate the ServletContext as mentioned in the previous section:

// Locate Our Servlet Context
ServletContext sc = getServletConfig().getServletContext();

Next, you'll need to get a handle to the resource that you'll be forwarding to:

/*
  Specify the path of the resource we want to get using
  the Servlet context from above.
  */
RequestDispatcher my RequestDispatcher = sc.getRequestDis-
patcher(String path)

You can then use the forward() method to direct the request to the object of your choice:

/*
  Call forward on this request dispatcher using the
  parameters sent to our service method.
  */
myRequestDispatcher.forward(HttpServletRequest myHttpServletRe-
quest ,
HttpServletResponse myHttpServletResponse );

The forward functionality of the RequestDispatcher may only be called if you have not sent any output to the client. If output exists that has already been placed in a response buffer that has not been committed (i.e., sent to the client), then the buffer must be cleared. If a response has already been sent to the client and the forward functionality is in use, an IllegalStateException will be thrown at runtime. In any servlet that you forward to, you should make sure to explicitly instruct the servlet container to “return” at the end of your method:

return;

This causes the servlet container to stop processing your code. This action is also helpful when you have a servlet or JSP page that you wish to have stop processing and simply return to the user the response that has been constructed so far in your servlet.

Use the forward method to redirect a user to a login page if that user's session is invalid.


Including Other Resources

It is also useful to include the output of other resources in your responses. For example, if you want to include a standard header that is generated by another servlet or a static HTML file in your servlet output, use the include functionality of the RequestDispatcher.

First, follow the process used above to locate the RequestDispatcher for the object that you want to include. Then, call the include method on that resource:

// Call Include on This Request Dispatcher Using the
// Parameters Send to Our Service Method
myRequestDispatcher.include (HttpServletRequest myHttpServletRequest ,
HttpServletResponse myHttpServletResponse );

A best practice is to use this include method for programmatic server-side includes. For example, you have a single servlet that responds with a sports score for the entire user base. You can include that servlet in multiple pages.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.189.57