Search
Relevant Links
Top 10 Articles
Jetty - Java Developers's Guide To Latest Web Server Technology
Jetty, an Open source application server from Java has been the talk of the Developers community these days
Jetty - Java Developers's Guide To Latest Web Server Technology
Advantage And Disadvantages Of String Implementation In JAVA
Advantages of the String implementation in JAVA
Advantage And Disadvantages Of String Implementation In JAVA
Hibernate Vs JDBC Performance
The Hibernate advantage over JDBC
Hibernate Vs JDBC Performance
Choosing Java Vs .Net For Web Development
Choosing Java Vs .Net For Web Development
Choosing Java Vs .Net For Web Development
How To Call Java Applet Functions From Javascript
How to Call Java Applet Functions From Javascript
How To Call Java Applet Functions From Javascript
Java 2 Platform Enterprise Edition (J2EE) Three-Tier Model
Enterprise edition of J2EE is used for developing modular enterprise request.
Java 2 Platform Enterprise Edition (J2EE) Three-Tier Model
What Is Java Virtual Machine
What is java virtual machine?
What Is Java Virtual Machine
How Does Java Handle Overriding
Overriding tactics in Java is very different from C++ as methods by default in Java can be overridden unlike C++
How Does Java Handle Overriding
Java Interface Overview
Interface: Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy
Java Interface Overview
Enterprise Java Bean Application Development With A Three-Tier Architecture
Enterprise java beans is basically a server side component architecture for developing modular enterprise applications based on the java platform
Enterprise Java Bean Application Development With A Three-Tier Architecture
Use Of Hibernate With Java Persistence API
Hibernate has become immensely popular amongst the developer community as it is a free, powerful, high performance open source object
Use Of Hibernate With Java Persistence API
Java Embedded Applications
Java, or J2ME is a format for applications for mobile and PDAs. It provides software that can been added to mobile phones
Java Embedded Applications
How Does Java Handle Overriding?
Overriding tactics in Java is very different from C++ as methods by default in Java can be overridden unlike C++. In C++, the concept of overriding functions are handled by Virtual Table, VTable
How Does Java Handle Overriding?
Work With Teradata Using Java
Teradata is one of the leading vendor in data analytics and data warehousing applications and softwares.
Work With Teradata Using Java
Point To Point Video Conferencing Using Java's JMF API
When a face-to-face meeting with someone far away becomes a necessity or a compelling presentation must be given to a remote person,
Point To Point Video Conferencing Using Java's JMF API
Learning Java Programming Coding Language
There are many programming languages available and each of them is suitable for another program or application.
Learning Java Programming Coding Language
Java Hashtable
A collection allows a group of objects to be treated as a single unit.
Java Hashtable
Working With JNDI In A J2SE Application
Java Naming and Directory Interface (JNDI) allows Java objects to be published to a directory service which can be accessed by other Java applications later.
Working With JNDI In A J2SE Application
Java Games - The World Of Excitement Is Readying With Options!
Mobile phones have grown from the pedestal of a mere communication tool and with the aid of some innovative steps plus the technological up-gradation
Java Games - The World Of Excitement Is Readying With Options!
Everything You Need To Know And How To Use Java
Java is an object-oriented programming language developed by Sun Microsystems in the early 1990s
Everything You Need To Know And How To Use Java
Of CGI And Java Scripts
CGI and Java Scripts are both functional with both Netscape and Internet Explorer browsers.
Of CGI And Java Scripts
Free Java Games - Entertain Yourself In Your Leisure Time
Today, you can find cell phones having multifunctional organisational tools
Free Java Games - Entertain Yourself In Your Leisure Time
Ajax Applications Development
AJAX has not only sprouted but has got root hold in developing dynamic web applications,
Ajax Applications Development
Benefits And Pitfalls Of A Java-Based Forex Trading Platform
Many forex brokers today offer a Java-based platform to traders as opposed to the traditional software that needs to be installed on your computer.
Benefits And Pitfalls Of A Java-Based Forex Trading Platform
Point To Point Video Conferencing Using Java's JMF API
When a face-to-face meeting with someone far away becomes a necessity or a compelling presentation must be given to a remote person, video conferencing is always your best choice
Point To Point Video Conferencing Using Java's JMF API
What Is CLASSPATH
A path specifies the name and location of a file on the file system.
What Is CLASSPATH
Javascript Is Not Java
Repeat after me: JavaScript is not Java, JavaScript is not Java. . .
Javascript Is Not Java
Eclipse IDE
Eclipse is an open-source, platform-independent software framework for delivering what the project calls "rich-client applications".
Eclipse IDE
Tomcat Jsp Run Error:Unable To Find A Javac Compiler
I always get this error when I run simple jsp files in my Tomcat 5.0.19/win2000. These jsp files run on other versions of Tomcat on the same PC. Any ideas?
Tomcat Jsp Run Error:Unable To Find A Javac Compiler
Deploying Web Applications To Tomcat
In this article we are going to cover the deployment of web applications using Tomcat.
Deploying Web Applications To Tomcat
Running The Tomcat 4.0 Servlet/JSP Container
Tomcat 4.0, a server that implements the Servlet 2.3 and JSP 1.2 Specifications from Java Software. In order to install and run this container, you must do the following
Running The Tomcat 4.0 Servlet/JSP Container
SOAP Example
In the example below, a GetStockPrice request is sent to a server. The request has a StockName parameter, and a Price parameter will be returned in the response.
SOAP Example
SOAP HTTP Binding
HTTP communicates over TCP/IP. An HTTP client connects to an HTTP server using TCP. After establishing a connection, the client can send an HTTP request message to the server:
SOAP HTTP Binding
SOAP Fault Element
The optional SOAP Fault element is used to hold error and status information for a SOAP message.
SOAP Fault Element
SOAP Body Element
The mandatory SOAP Body element contains the actual SOAP message.
SOAP Body Element
Introduction To SOAP
SOAP is a simple XML based protocol to let applications exchange information over HTTP.
Introduction To SOAP
Where Did Java Come From?
In the late 1970's Bill Joy thought about doing a language that would merge the best features of MESA and C
Where Did Java Come From?
What Is Java?
Java, formerly known as oak, is an object-oriented programming language developed by Sun
What Is Java?
How Do I Format Numbers Like C's Printf()?
Java does not have any built in equivalent to C's printf/sprintf/fprintf family of functions that specify the width and precision of numbers converted into strings.
How Do I Format Numbers Like C's Printf()?
How Do I Play A Sound In An Application?
Java's audio support comes from the AppletContext class and the AudioClip interface. Since applications don't have applet contexts, they have no easy way to play audio clips
How Do I Play A Sound In An Application?
Java Interview Questions
Java Interview Questions for java programmers !
Java Interview Questions
Java Games For Your Cell Phone
Are you one of those people who get tired when standing in queue? Can't stop multitasking no matter what you do
Java Games For Your Cell Phone
Pros And Cons Of JavaScript
Javascript use is very common across the Internet; but just because it is popular, does that mean you should use it for your site
Pros And Cons Of JavaScript
Tag Libraries
JSP 1.1 introduces a method of extending JSP tags, called "tag libraries".
Tag Libraries
Beans And Form Processing
The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean.
Beans And Form Processing
JSP Sessions
If you are programming the site, it is very helpful to be able to associate some data with each visitor. For this purpose, "session"s can be used in JSP
JSP Sessions
JSP Tags
Another important syntax element of JSP are tags. JSP tags do not use <%, but just the < character. A JSP tag is somewhat like an HTML tag.
JSP Tags
JSP Directives
We have been fully qualifying the java.util.Date in the examples in the previous sections. Perhaps you wondered why we don't just import java.util.*;
JSP Directives
Mixing Scriptlets And HTML
We have already seen how to use the "out" variable to generate HTML output from within a scriptlet.
Mixing Scriptlets And HTML
JSP:Scriptlets
JSP also allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between <% and %> characters
JSP:Scriptlets
Categories
Related Links

 

Java4Programmers.com

Java4Programmers.com This is a high-level informational site for java programmers outside of Sun Microsystems. This is a categorized directory of information sources for Java, including sources, communities, tools, etc.

Tomcat

Tomcat : Deploying Web Applications To Tomcat

 

In this article we are going to cover the deployment of web applications using Tomcat. We are performing a manual deployment to fully explain the steps involved when deploying a web application.

The best way to describe the deployment process is to create a web application of our own that includes the important components found in most Java web applications; then package it for deployment. The following sections will take you through the steps involved in deploying a web application. The name of our web application will be onjava.

In this article, we

  • create the web application directory structure,
  • create a web application ServletContext,
  • add JSPs,
  • add Servlets,
  • add Tag Libraries, and
  • create and deploy a WAR file.

Creating the Web Application Directory Structure

The first thing you need to do is create the directory structure that will contain the application. We discussed this structure in Part 1, Java Web Applications, and I include the relevant details in Table 1.


Table 1. The Web Application Directory Structure

Directory

Contains

/onjava

This is the root directory of the web application. All JSP and XHTML files are stored here.

/onjava/WEB-INF

This directory contains all resources related to the application that are not in the document root of the application. This is where your web application deployment descriptor is located. Note that the WEB-INF directory is not part of the public document. No files contained in this directory can be served directly to a client.

/onjava/WEB-INF/classes

This directory is where servlet and utility classes are located.

/onjava/WEB-INF/lib

This directory contains Java Archive files that the web application depends upon. For example, this is where you would place a JAR file that contained a JDBC driver.

The name of our web application, onjava, is the root of our directory structure.

While in development I suggest creating the directory directly in the Tomcat /webapps directory. When it comes time for deployment, you can package your web application into a WAR file and go though the production deployment process.

The last step in creating the web application directory structure is adding a deployment descriptor. At this point you'll be creating a default web.xml file that contains only the DTD, describing the web.xml file, and an empty element. Listing 1 contains the source for a default web.xml file.

Listing 1 web.xml



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


Now copy this file to the TOMCAT_HOME/onjava/WEB-INF/ directory, and we'll begin adding web application components to it in the following sections.

Creating a Web Application ServletContext

After you've created the web application directory structure, you must add a new ServletContext to Tomcat. The ServletContext defines a set of methods that are used by components of a web application to communicate with the servlet container. The ServletContext acts as a container for the web application. There is only one ServletContext per web application. We will discuss the relationship between a ServletContext and its web application in much more detail in Part 4, "Web Applications and the ServletContext."

To add a new ServletContext to Tomcat you need to add the following entry to the TOMCAT_HOME/conf/server.xml file, setting the values for the path and docBase to the name of your web application. Notice again that the name we are using is onjava.

There are two things here we need to focus on. The first, path="/onjava", tells the servlet container that all requests with /onjava appended to the server's URL belong to the onjava web application. The second, docBase="onjava", tells the servlet container that the web application exists in the /onjava directory.

Adding JSPs

Now that you have created the web application directories and added ServletContext, you can add server-side Java components. The first components we are going to add are JSPs.

The first JSP will include a simple login screen. Listing 2 contains the source for the login.jsp page.

Listing 2 login.jsp



 OnJava Demo
 




 
  
   
  
  
  
  
  
   
  
 
 

   
 

 
  
   
  
 

    
     
     
      
      
     
     
      
      
     
     
      
      
     
     
    
User Name: 
Password: 
 

   


As you look at this JSP, you'll see nothing very special about it. The only thing you should pay attention to is the action of the form. It references a servlet in the package com.java named login. This servlet will retrieve the username-password parameters from the request and perform its own processing.

There isn't much to deploying a JSP. You just copy it to the public directory of your web application, which in this case is TOMCAT_HOME/webapps/onjava/. Any images that it references should be placed in an images folder that you have created in the /onjava directory.

To see this JSP in action, open the following URL in a browser:


http://localhost:8080/onjava/login.jsp

The second JSP is the target JSP referenced by the servlet defined in the following section. This JSP will retrieve the request attribute USER that was added to the request with the following servlet. It will then output the String value of the attribute. Listing 3 contains the source for the target JSP.

Listing 3 welcome.jsp



 OnJava Demo
 


 
  
   
  
  
  
  
  
  
   
  
 
 

   

   Welcome : <%= request.getAttribute("USER")
%>

  
 


As we stated earlier to deploy this JSP, you simply need to copy it to the public directory of your web application, which in this case is TOMCAT_HOME/webapps/onjava/.

Adding Servlets

The next component to add is a servlet. This servlet will be the action of login.jsp's form. It will retrieve the username and password values from HttpServletRequest, look up the associated user, and then forward the request to a target JSP. The source code for this servlet can be found in Listing 4.

For our example the value of the USER is static. Normally you would perform a real lookup of some sort, but, to keep things simple, I'm just returning String Bob.

Listing 4 com.onjava.login.java

package com.onjava;

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

public class login extends HttpServlet {

 private String target = "/welcome.jsp";

 private String getUser(String username, String password) {

// Just return a static name
  // If this was reality, we would perform a SQL lookup
  return "Bob";
 }

 public void init(ServletConfig config)
  throws ServletException {

  super.init(config);
 }

 public void doGet(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {

  // If it is a get request forward to doPost()
  doPost(request, response);
 }

 public void doPost(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {

  // Get the username from the request
  String username = request.getParameter("username");
  // Get the password from the request
  String password = request.getParameter("password");

  String user = getUser(username, password);

  // Add the fake user to the request
  request.setAttribute("USER", user);

  // Forward the request to the target named
  ServletContext context = getServletContext();

  RequestDispatcher dispatcher =
   context.getRequestDispatcher(target);
  dispatcher.forward(request, response);
 }

 public void destroy() {
 }
}

To deploy a servlet as part of a web application you first need to compile the servlet and move it into the web application's /WEB-INF/classes directory. For this example, you should compile this servlet and move it to the /onjava/WEB-INF/classes/com/onjava/ directory.

This class file is in the subdirectory com.onjava because of its package name.

The next step in deploying the login servlet is to add a servlet entry into the web application's web.xml file. An example element can be found in the following code snippet.

It isn't necessary to add all servlets to the web.xml file; it's only necessary when the servlet requires additional information, such as initialization parameters.

Example Element


  ExampleServlet
  packagename.ExampleServlet
  
   parameter
   value
  

  1

This servlet entry contains a simple servlet definition. A description of each of its parts can be found in Table 2.

Table 2. The Sub-elements of a

Sub-element

Description

The element is simply the canonical name of the deployed servlet.

The sub-element references the fully qualified class name of the servlet.

The sub-element is an optional parameter containing a name-value pair that is passed to the servlet on initialization. It contains two sub-elements, and , which contain the name and value, respectively, to be passed to the servlet.

The sub-element indicates the order in which each servlet should be loaded. Lower positive values are loaded first. If the value is negative or unspecified, then the container can load the servlet at anytime during startup.

To add our login servlet we need to make the following entry into the TOMCAT_ROOT/onjava/WEB-INF/web.xml file:


login
com.onjava.login

That's all there is to it. To see your web application in action, restart the Tomcat server and open the following URL in your browser:


http://localhost:8080/onjava/login.jsp

Adding Tag Libraries

The final component that we're adding is a tag library. This library contains a single tag, HelloTag, that replaces every occurrence of the text with the literal string "Hello". While this is a perfectly silly example of a tag library, it allows us to present a practical example of deploying a tag library. The source code for the tag handler can be found in Listing 5 and the source for the tld can be found in Listing 6.

Listing 5 HelloTag.java

package com.onjava;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;

public class HelloTag extends TagSupport
{
 public void HelloTag() {

 }

 // Method called when the closing hello tag is encountered
 public int doEndTag() throws JspException {

  try {

   // We use the pageContext to get a Writer
   // We then print the text string Hello
   pageContext.getOut().print("Hello");
  }
  catch (Exception e) {

   throw new JspTagException(e.getMessage());
  }
  // We want to return SKIP_BODY because this Tag does not support
  // a Tag Body
  return SKIP_BODY;
 }

 public void release() {

  // Call the parent's release to release any resources
  // used by the parent tag.
  // This is just good practice for when you start creating
  // hierarchies of tags.
  super.release();
 }
}

Listing 6 taglib.tld


  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">




 1.0
 1.1
 onjava
 /onjava

 
 hello
 com.onjava.HelloTag
 empty
 Just Says Hello
 

To deploy this tag library, we need to make an entry to the web.xml file. The modified web.xml file can be found in Listing 7.

Listing 7 web.xml



 '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
 'http://java.sun.com/j2ee/dtds/web-app_2_3.dtd'>



 
  login
  com.onjava.login
 


 
  /onjava
  /WEB-INF/lib/taglib.tld
 


The added entry contains two elements. The first element, , tells the container how the tag library is to be referenced. For this example we use the value /onjava, which is the way we'll reference the tag library in our JSPs.

The second element, , defines the location of the tag library's descriptor (TLD). The TLD defines the tags contained in the library and the handlers that will process the defined tags.

To complete your deployment, copy the compiled tag library and the taglib.tld into the TOMCAT_ROOT/onjava/WEB-INF/lib directory.

To test you new tag library, you need to modify the welcome.jsp page, replacing the Welcome message with a reference to the tag. You need to also add a taglib directive referencing the taglib.tld to the welcome.jsp file. The modified JSP is in Listing 7.


Listing 7 Modified welcome.jsp

<%@ taglib uri="/onjava" prefix="onjava" %>


 Onjava Demo
 


 
  
   
  
  
  
  
  
  
   
  
 
 

   

    : <%= request.getAttribute("USER") %>
  
 


Now open the login.jsp page as described previously and run through the demo again. This time instead of Welcome: Bob, you should see the message Hello: Bob.



Creating and Deploying a WAR File

When your web application is ready for deployment, you need to package it for distribution. As we discussed previously in Java Web Applications, web applications are packaged in WAR files. The steps required to "WAR-up" your /onjava web application and deploy it are as follows:

  1. Change to the root directory of your web application. In this case the root directory would be TOMCAT_HOME/webapps/onjava/.

  2. Archive the web application:

    jar cvf onjava.war .
  3. Copy the resulting WAR file, onjava.war, to the TOMCAT_HOME/webapps directory.

    If you're deploying this WAR file to the Tomcat installation that you were developing in, then you will need to back up your development directory and remove it from the TOMCAT_HOME/webapps directory.

  4. Add a new Context entry to the /TOMCAT_HOME/conf/server.xml file, referencing the onjava web application.

  5. Restart Tomcat.

That's it. Your application should now be deployed and running. If it isn't, check your entry in the TOMCAT_HOME/conf/server.xml file to ensure that you have set the appropriate values.



Other Relevant Articles from this Category:
Running The Tomcat 4.0 Servlet/JSP Container
Deploying Web Applications To Tomcat
Tomcat Jsp Run Error:Unable To Find A Javac Compiler

More Categories:
Java Script  
Download Java  
Java Game  
Java Programming  
Java Developer  
Java Certification  
Java Applet  
Java Sun Certification  
Java Tutorial  
Java Swing  
Java Runtime Environment  
Xml  
Install Java  
Java Network Programming  
Java Training  
J2ee  
Thinking In Java  
Java Application Server  
Java Programmer  
Java Design Pattern  
Tomcat  
Struts  
Jsp