Thursday, September 9, 2010

The Deployment Descriptor (web.xml)

The web.xml file provides configuration and deployment information for the web components that comprise a web application. Examples of web components are servlet parameters, servlet and JavaServer Pages (JSP) definitions, and Uniform Resource Locators (URL) mappings. The Java Servlet specification defines the web.xml deployment descriptor file in terms of an XML schema document. 

Listing 1 contains the source for a default web.xml file.


Listing 1 web.xml


<?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/j2ee/dtds/web-app_2_3.dtd">

<web-app>
</web-app>

You may also see versions of the deployment descriptor that uses what is called a schema which is functionally equivalent. The start of a deployment descriptor that uses a schema will look as follows

<?xml version="1.0" encoding="UTF-7"?>
<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmnls:xsi="http://www.w3.org/2001/XML-Schema -instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
               http://java.sun.com/xml/ns/javae/web-app_3_0.xsd">
</web-app>



The web-app element is the root of the deployment descriptor for a web application. Note that the sub elements of this element can be in arbitrary order

web.xml Deployment Descriptor Elements

The following sections describe the deployment descriptor elements defined in the web.xml file under the root element <web-app>:

  • context-param         
                The optional context-param element contains the declaration of a web application's servlet context initialization parameters.

  • servlet
       The servlet element contains the declarative data of a servlet. The servlet tag has two mandatory sub tags, <servlet-name> and <servlet-class>. The servlet-class tag is the fully qualified name of the class that is to be executed and the servlet-name tag is an alias for use elsewhere within the deployment descriptor. 

    <servlet>
        <servlet-name>
HelloWorldServlet</servlet-name>
        <servlet-class>com.servlet.HelloWorld</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

The load-on-startup tag of the servlet indicates that the servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. 
  • If the value is a negative integer, or the  element is not present, the container is free to load the servlet whenever it  chooses.
  • If the value is a positive integer or 0, the container must load and  initialize the servlet as the application is deployed.   

The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value. 

The servlet element may also have the following optional sub-elements display-name,description,init-param, run-as, security-role-ref

  • servlet-mapping
      The servlet-mapping element defines a mapping between a servlet and a URL pattern. Without a servlet-mapping a servlet cannot be retrieved by a visiting browser. The following example shows a servlet mapped to a url pattern.

    <servlet-mapping>
        <servlet-name>HelloWorldServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

servlet-name tag contains the name of the servlet to which you are mapping a URL pattern. This name corresponds to the name you assigned a servlet in a <servlet> declaration tag.

url-pattern describes a pattern used to resolve URLs. The portion of the URL after the http://host:port + WebAppName is compared to the <url-pattern>. If the patterns match, the servlet mapped in this element will be called.

Given this mapping the servlet contained within the Java file at com.servlet.HelloWorld will be executed when a browser requests http://localhost/hello. The url-pattern tag can include wildcards and it is possible to have multiple mappings to a single servlet.

The url-mapping value must begin with a forward slash unless it is an extension mapping. By extension mapping I mean where a wildcard is used, e.g. to map the URL pattern *.exam to a servlet you could include the value
<url-pattern>*.exam</url-pattern>. 

But apart from that, mappings begin with a forward slash.

  • welcome-file-list
       The optional welcome-file-list element contains an ordered list of welcome-file elements. The welcome-file tag can be used to mark a servlet or a JSP file as the default first page that is returned when a visitor accesses a URL if they don't specify an explicit file. This is typically used on the home page of a web site where you see the trailing slash of the URL but you don't see the name of the file that is actually returned.

    <welcome-file-list>
        <welcome-file>welcomeservlet</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
The idea of allowing multiple welcome files might seem odd at first, after all, only one file can be returned if there is no explicit file name given. The idea of allowing multiple files is that you might have a directory structure that contains files you want to use as the default welcome file. A welcome-file value cannot start or end with a slash, and they will be picked in the order they appear in the deployment descriptor. Thus given a deployment descriptor with the following tags.
     <welcome-file-list>
  <welcome-file> index.jsp </welcome-file>  
        <welcome-file> welcome.jsp </welcome-file>
     </welcome-file-list>

The index.jsp file will be returned from a request to www.mydomain.com/. If no index.jsp file exists then welcome.jsp will be returned if it exists.

  • error-page
      The optional error-page element specifies a mapping between an error code or exception type to the path of a resource in the Web application. When an error occurs—while server is responding to an HTTP request, or as a result of a Java exception— server returns an HTML page that displays either the HTTP error code or a page containing the Java error message. You can define your own HTML page to be displayed in place of these default error pages or in response to a Java exception.

 Thus the following tags would re-direct all SQL exception errors to the /errorpage.jsp page.
    <error-page>
       <exception-type> java.sql.SQLException </exception-type>
       <location> /errorpage.jsp </location>
    </error-page> 

The following tags would re-direct all HTTP 404 errors to the /errorpage.jsp page
   <error-page>
      <error-code>404</error-code>
      <location>/errorpage.jsp</location>
   </error-page>
Note that it is possible to define a specific error page for an individual JSP page using the errorPage attribute as follows.
    <%@ page errorPage="MyErrorPage.jsp" %>
The page that this attribute points to must have the isErrorPage=true attribute set as follows.
   <%@ page isErrorPage="true" %>
  • init-param
This is an element within the servlet. The optional init-param element contains a name/value pair as an initialization attribute of the servlet. Use a separate set of init-param tags for each attribute.

The init-param tag allows initialisation parameters to be passed to a servlet via the deployment descriptor. This allows configuration without having to recompile code. 

An example of how you might use the init-param tag is to inform a servlet of the JDBC driver, and username and password to access a database.The following extract from a deployment descriptor shows how the init-param called backupfrequency could be used to inform a servlet of the interval between backups. 
    <servlet>
        <servlet-name>backupservlet</servlet-name>
        <servlet-class>com.servlet.BackupServlet</servlet-class>
        <init-param> 
            <description>Frequency of backup in hours</description>
            <param-name>backupfrequency</param-name>
            <param-value>24</param-value>
        </init-param>
    </servlet> 
The servlet can retrieve the value of the init-param through code similar to the following.
    ServletConfig config = getServletConfig();
   backupfrequency = config.getInitParameter("backupfrequency");
 

Wednesday, September 8, 2010

Structure of a Java EE Web Module

In the Java EE platform, web components provide the dynamic extension capabilities for a web server. Web components can be Java servlets, web pages implemented with JavaServer Faces technology, web service endpoints, or JSP pages. Web components are supported by the services of a runtime platform called a web container. A web container provides such services as request dispatching, security, concurrency, and life-cycle management. A web container also gives web components access to such APIs as naming, transactions, and email.

Web components and static web content files, such as images, are called web resources. A web module is the smallest deployable and usable unit of web resources.


The J2EE standard prescribes a directory structure for web applications that controls both where files should reside and what visibility they will have from the perspective of the visiting web browser. The top-level directory of a web module is the document root of the application. The document root is where XHTML pages, client-side classes and archives, and static web resources, such as images, are stored.

The document root contains a sub directory named WEB-INF. The WEB-INF directory is mandatory in a web application. Although WEB-INF is directly under the document root, it should be considered to be out of the accessible path and is invisible to a visiting web browser. It can contain the following files and directories:
  • classes: A directory that contains server-side classes: servlets, enterprise bean class files, utility classes, and JavaBeans components
  • tags: A directory that contains tag files, which are implementations of tag libraries
  • lib: A directory that contains JAR files that contain enterprise beans, and JAR archives of libraries called by server-side classes
  • Deployment descriptors, such as web.xml (the web application deployment descriptor) and ejb-jar.xml (an EJB deployment descriptor)
  • The META-INF, this directory is only relevant for use within a war file, where it is mandatory and performs a role very similar to the WEB-INF directory of a non jarred web application. If you create a META-INF directory within your application root the contents will not be directly visible from a visiting web browser. However because the META-INF directory only has relevance for war files it should not be present in a production (non war) environment and it is common practice to only create it for the purpose of generating the directory structure for a war file

A web module needs a web.xml file if it uses JavaServer Faces technology, if it must specify certain kinds of security information, or if you want to override information specified by web component annotations.

You can also create application-specific subdirectories (that is, package directories) in either the document root or the WEB-INF/classes/ directory.

A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a Web Archive (WAR) file. Because the contents and use of WAR files differ from those of JAR files,WAR file names use a .war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet specification.


Web Application Types

A web application is a dynamic extension of a web or application server. Web applications are of the following types:
  • Presentation-oriented: A presentation-oriented web application generates interactive web pages containing various types of markup language (HTML, XHTML, XML, and so on) and dynamic content in response to requests.
  • Service-oriented: A service-oriented web application implements the endpoint of a web service. Presentation-oriented applications are often clients of service-oriented web applications.

Web Application Life Cycle

The process for creating, deploying, and executing a web application can be summarized as follows:

1. Develop the web component code.
2. Develop the web application deployment descriptor, if necessary.
3. Compile the web application components and helper classes referenced by the components.
4. Optionally, package the application into a deployable unit.
5. Deploy the application into a web container.
6. Access a URL that references the web application.

Structure of a Java EE Application

 
A Java EE module consists of one or more Java EE components for the same container type and, optionally, one component deployment descriptor of that type. 

Java EE modules are of the following types:
  • EJB modules, which contain class files for enterprise beans and an EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension.
  • Web modules, which contain servlet class files, web files, supporting class files, GIF and HTML files, and a web application deployment descriptor. Web modules are packaged as JAR files with a .war (web archive) extension.
  • Application client modules, which contain class files and an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension. 
  • Resource adapter modules, which contain all Java interfaces, classes, native libraries, and other documentation, along with the resource adapter deployment descriptor. Together, these implement the Connector architecture for a particular EIS. Resource adapter modules are packaged as JAR files with an .rar (resource adapter archive) extension.

An Enterprise Archive (EAR) file contains Java EE modules and, optionally, deployment descriptors. 

Deployment Descriptor

A deployment descriptor, an XML document with an .xml extension, describes the deployment settings of an application, a module, or a component. Because deployment descriptor information is declarative, it can be changed without the need to modify the source code. 


At runtime, the Java EE server reads the deployment descriptor and acts upon the application, module, or component accordingly, i.e. with specific container options, security settings and describes specific configuration requirements.
In Java EE, there are two types of deployment descriptor: 
  •  Java EE deployment descriptors, and 
  •  Runtime deployment descriptors 

 A Java EE deployment descriptor is defined by a Java EE specification and can be used to configure deployment settings on any Java EE compliant implementation. For example, the web.xml file is a standard Java EE deployment descriptor, specified in the java servlet specification. 

A runtime deployment descriptor is defined by the vendor of each container implementation.It is used to configure Java EE implementation-specific parameters. For example, the GlassFish Server runtime deployment descriptor contains such information as the context root of a web application, as well as GlassFish Server implementation-specific parameters, such as caching directives. The GlassFish Server runtime deployment descriptors are named sun-moduleType.xml and are located in the same META-INF directory as the Java EE deployment descriptor. 

Tuesday, September 7, 2010

Introduction to Java EE 6

The aim of Java EE platform is to provide developer with a powerful set of APIs while shortening development time, reducing application complexity and improving application performance.

New technologies, including the following are available in Java EE 6:
  • Java API for RESTful Web Services (JAX-RS)
  • Managed Beans
  • Contexts andDependency Injection for the Java EE Platform (JSR 299), informally known as CDI
  • Dependency Injection for Java (JSR 330)
  • Bean Validation (JSR 303)
  • Java Authentication Service Provider Interface for Containers (JASPIC)

Also there are new features added Enterprise JavaBeans (EJB) components, servlets and Java Server Faces components.


Java EE Application Model

The Java EE application model defines an architecture for implementing services as multitier applications.This model partitions the work needed to implement a multitier service into the following parts:
  • The business and presentation logic to be implemented by the developer
  • The standard system services provided by the Java EE platform

The developer can rely on the platform to provide solutions for the hard systems-level problems of developing a multitier service.

Java EE multitiered applications are generally considered to be three-tiered applications because they are distributed over three locations: client machines, the Java EE server machine, and the database or legacy machines at the back end.
  • Client-tier components run on the client machine.
  • Web-tier components run on the Java EE server.
  • Business-tier components run on the Java EE server.
  • Enterprise information system (EIS)-tier software runs on the EIS server.

Java EE Components

Java EE applications are made up of components. 

A Java EE Component is a self contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components.

The Java EE specification defines the following Java EE components.
  • Application/web clients and applets are components that run on the client.
  • Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components are web components that run on the server.
  • Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server.

Component based architecture makes Java EE applications easy to write because business logic is organized into reusable components.


Java EE Container

Containers are the interface between a component and the low-level platform-specific functionality that supports the component.

Before it can be executed, a web, enterprise bean, or application client component must be assembled into a Java EE module and deployed into its container.

The assembly process involves specifying container settings for each component in the Java EE application and for the Java EE application itself. Container settings customize the underlying support provided by the Java EE server, including such services as security, transaction management, JavaNaming and Directory Interface (JNDI) API lookups, and remote connectivity.

The container also manages nonconfigurable services, such as enterprise bean and servlet life cycles, database connection resource pooling, data persistence, and access to the Java EE platform APIs


Container Types

The deployment process installs Java EE application components in the Java EE containers.
  • Java EE server: The runtime portion of a Java EE product. A Java EE server provides EJB and web containers.
  • Enterprise JavaBeans (EJB) container:Manages the execution of enterprise beans for Java EE applications. Enterprise beans and their container run on the Java EE server.
  • Web container:Manages the execution of web pages, servlets, and some EJB components for Java EE applications. Web components and their container run on the Java EE server.
  • Application client container:Manages the execution of application client components. Application clients and their container run on the client.
  • Applet container:Manages the execution of applets. Consists of a web browser and Java Plug-in running on the client together.

    Hello


    While I was on a learning curve trying to learn and keep up with the various technologies and frameworks related to Java, I needed to scan and read different articles and tutorials to fulfill my curiosity and then another scores of pages when I had some bug/error in my application.

    This blog is for someone like me who wants to learn and wants a good source. I am no master of any of the technology, but i wish this helps in your journey.