Saturday, April 28, 2012

Understanding the structure of web applications

Web Applications use a standard directory structure defined in the Servlet specification. When developing web applications on J2EE platform, you must follow this structure so that application can be deployed in any J2EE compliant web server.
A web application has the directory structureas shown in below figure.
J2EE Web Application Directory Structure
The root directory of the application is called the document root. Root directory is mapped to the context path. Root directory contains a directory named WEB-INF. Anything under the root directory excepting the WEB-INF directory is publically available, and can be accessed by URL from browser. WEB-INF directory is a private area of the web application, any files under WEB-INF directory cannot be accessed directly from browser by specifying the URL like http://somesite/WEB-INF/someresource.html. Web container will not serve the content of this directory. However the content of the WEB-INF directory is accessible by the classes within the application. So if there are any resources like JSPs or HTML document that you don’t wish to be accessible directly from web browser, you should place it under WEB-INF directory.

WEB-INF directory structure

WEB-INF directory contains
  • WEB-INF/web.xml deployment descriptor
  • WEB-INF/classes directory
  • WEB-INF/lib directory

/WEB-INF/web.xml

web.xml is called the web application deployment descriptor. This is a XML file that defines servlets, servlet mappings, listeners, filters, welcome files etc. Deployment descriptor is a heart of any J2EE web application, so every web application must have a web.xml deployment descriptor directly under WEB-INF folder.

/WEB-INF/classes

The classes directory is used to store compiled servlet and other classes of the application. If your classes are organized into packages, the directory structure must be reflected directly under WEB-INF/classes directory. The classes directory is automatically included in CLASSPATH.

/WEB-INF/lib

Lib directory is used to store the jar files. If application has any bundled jar files, or if application uses any third party libraries such as log4j, JDBC drivers which is packaged in jar file, than these jar files should be placed in lib directory.
All unpacked classes and resources in the /WEB-INF/classes directory, plus classes and resources in JAR files under the /WEB-INF/lib directory are included in classpath and made visible to the containing web application.
There are many changes in Servlet 3.0 Specification, web.xml file is optional, servlets, listeners and filters are no longer required to be defined in web.xml, instead they can declared using annotations. web.xml file can be devided into multiple files called webfragments. See Servlet 3.0 Tutorials for more details.

Note Directory and file names are case sensitive. 

No comments:

Post a Comment