Welcome!

Eclipse Authors: Pat Romanski, Elizabeth White, Liz McMillan, David H Deans, JP Morgenthal

Related Topics: Eclipse, Java IoT, Open Source Cloud

Eclipse: Article

How to Bring Eclipse 3.1, J2SE 5.0, and Tomcat 5.0 Together

How to create a Web project that has Java classes located in different packages and how we use ANT

As one can see from the code, the servlet first tries to create an Http session by calling request.getSession(true), which means that a new session will be created if one doesn't exist already, then we'll get the "sessiontest.counter" attribute from the session, which will be assigned 0 if it's null, increment it, and set it back to the session. The session will be invalidated (all attributes removed from it) when counter goes above five. We'll get an HTTP request header called "Cookie" and a reference to the HTTP response writer and pass them to the SampleProgram class (see Listing 8) that will perform the logic described below.

Creating a Test Class and JUnit Test Case
For our servlet to work, we'll create one more supporting class SampleProgram with a main method that can test all these supporting classes and will be eventually called by the servlet too.

As you can see, the program in Listing 8 uses all our classes. It can also be tested from the command line (without having to deploy a servlet in Tomcat) by creating a JUnit test case.

To create a JUnit test case in Eclipse, right-click on the class SampleProgram and select the menus New, Other, Junit, and Junit Test Case. It'll add the junit.jar to the classpath, if needed, and a window pops up asking how we want to create our test case.

Select setUp() and tearDown() methods to set up the test environment and tear it down when finished. Also select create main method and allow Swing UI so we can run our test visually. On the next screen select methods to test: main and testClasses.

Once finished, a SampleProgramTest class is generated and we can test it by selecting Run As - JUnit test from the context menu. JUnit will test to see if any exceptions occur and display them as errors. It will also display failures if any of our assertion tests fail. Below is the source code of our sample JUnit test (see Listing 9).

In both test methods, we've added method calls with arguments to make sure there are no exceptions. We also do an assertion that will definitely fail to demonstrate the JUnit failure detection capability:

junit.framework.ComparisonFailure: expected:<1> but was:<2>
at junit.framework.Assert.assertEquals(Assert.java:81)
at junit.framework.Assert.assertEquals(Assert.java:87)

Coding Web.xml Deployment Descriptor
Web applications require a Web.xml deployment descriptor (see Listing 10), which should be put under the WEB-INF directory.

In our deployment descriptor, we've included our SampleServlet and the index.html as a welcome page.

Deploying Servlet Using ANT
Eclipse 3.1 comes with built-in ANT support so you can execute XML-based scripts to deploy your application in a specific application server. In our case, we're deploying under Tomcat 5.0 server, which also has built-in support for Ant for the following tasks:

  • Deploying WAR files
  • Reloading WAR files
  • Undeploying WAR files
It makes deploying, redeploying, or undeploying an application easier. With Eclipse support for Ant, it's easy to create build an XML file with Ant tasks in it using Ant executor.

To take advantage of this support, we have to add Eclipse to the external catalina-ant.jar (which is located under the $TOMCAT\server\lib directory and contains support for Tomcat Ant tasks) to the runtime class-path before running Ant tasks. Select the menus Run, External Tools, and External Tools and double-click on the Ant-build.

Running Ant tasks is simple in Eclipse. Just right-click on your build file (you have to create a build.xml file containing your Ant tasks as in Listing 11) and select Run As - Ant Build, then select tasks to create-a war file, and deploy the application.

As you can see from Listing 11, there are four major tasks in the build:

  • Creating the WAR file
  • Deploying the WAR file to Tomcat
  • Reloading the application
  • Undeploying the WAR file from Tomcat
The file also contains variables used by these tasks. The notable ones are:
  • "build" - where to build a WAR file
  • "path" - the context root of the Web application, in this case "myapp"
  • "url" - the url of the Tomcat administrative application (which comes with Tomcat and provides an inter-face for deploying/undeploying applications)
  • username - the user name for the Tomcat admin application (in our case it's "admin")
  • password - the password for the Tomcat admin application (in our case it's "admin")
The file also contains various "taskdef" entries that point to the Java classes inside catalina-ant.jar that define the execution of the particular tasks.

Using the Eclipse interface (right-click on build.xml file and select Run As - Ant Build...), these tasks can be executed one at a time or all together. Note that "Deploying the WAR file to the Tomcat" task is dependent on "Creating WAR file" task, so execute the "create-war" task first, then "deploy" task.

It's time for us to start the Tomcat server and deploy our application. In Windows, simply go to Control Panel - Services and start the Apache Tomcat service. In Unix, you can execute the $TOMCAT\bin\startup.sh script.

Once it's deployed (the ANT deployment task has been completed), just point your browser at http://localhost:8080/myapp/SampleServlet/ and you should see the output as in Figure 1.

Conclusion
In this article, I've shown you some of the new J2SE 5.0 elements and covered the creation of a Web application using simple tools available in Eclipse 3.1 and Tomcat 5.0, such as Java wizards, JUnit, and Ant. There are more advanced tools that can streamline and automate this development. One such extension to Eclipse is called Web Tools Project WTP (www.eclipse.org/Webtools), which I'll cover in a future article.

More Stories By Boris Minkin

Boris Minkin is a Senior Technical Architect of a major financial corporation. He has more than 15 years of experience working in various areas of information technology and financial services. Boris is currently pursuing his Masters degree at Stevens Institute of Technology, New Jersey. His professional interests are in the Internet technology, service-oriented architecture, enterprise application architecture, multi-platform distributed applications, and relational database design. You can contact Boris at [email protected]

Comments (13) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
sumeet jaju 07/28/06 07:40:26 AM EDT

Thanks for you

SYS-CON Belgium News Desk 01/07/06 02:16:35 PM EST

We'll build a servlet that will demo some new Java 5.0 features and do some basic tasks like creating a session to track user visits to multiple Web pages. This code can easily be extended to store a user ID in the session that will travel with her as the site is navigated. The value of the visit counter is stored in the session so multiple visits to the page will be counted (this includes the page refreshes after pressing the browser's 'Reload' button). If the counter goes over five, the counter gets cleared.

SYS-CON Australia News Desk 01/06/06 12:59:13 PM EST

We'll build a servlet that will demo some new Java 5.0 features and do some basic tasks like creating a session to track user visits to multiple Web pages. This code can easily be extended to store a user ID in the session that will travel with her as the site is navigated. The value of the visit counter is stored in the session so multiple visits to the page will be counted (this includes the page refreshes after pressing the browser's 'Reload' button). If the counter goes over five, the counter gets cleared.

Lester D'Souza 01/06/06 12:24:47 PM EST

A great article. I had to struggle to get it working due to some errors and typos. I wish I could upload my entire Eclipse project as part of the feedback. The nice thing about this set up was that I could modify my Servlet, then using the create-war, undeploy and deploy my changes on the tomcat server with the click of a button. Tomcat would detect my changes, and when I refreshed the browser, I could see my changes. This is an ideal setup for any web based development. Also I would like to mention that this is my first experience with Eclipse, Tomcat and Ant. I would like to rewrite this article and leave out the J2SE 5.0 stuff, since it does not fit in very well. Also I was able to use Junit to test the code.

Eclipse News Desk 01/05/06 08:31:49 PM EST

We'll build a servlet that will demo some new Java 5.0 features and do some basic tasks like creating a session to track user visits to multiple Web pages. This code can easily be extended to store a user ID in the session that will travel with her as the site is navigated. The value of the visit counter is stored in the session so multiple visits to the page will be counted (this includes the page refreshes after pressing the browser's 'Reload' button). If the counter goes over five, the counter gets cleared.

SYS-CON Australia News Desk 01/05/06 07:38:14 PM EST

We'll build a servlet that will demo some new Java 5.0 features and do some basic tasks like creating a session to track user visits to multiple Web pages. This code can easily be extended to store a user ID in the session that will travel with her as the site is navigated. The value of the visit counter is stored in the session so multiple visits to the page will be counted (this includes the page refreshes after pressing the browser's 'Reload' button). If the counter goes over five, the counter gets cleared.

Carrie Latimer 01/05/06 07:01:44 PM EST

I ran into the same issues Eric ran into. Help please. Thank you and take care.

Carrie Latimer 01/05/06 07:01:34 PM EST

I ran into the same issues Eric ran into. Help please. Thank you and take care.

Eric Bresie 11/16/05 09:02:26 AM EST

I was reading your article about Eclipse and Tomcat and was trying to follow on and ran into a snag or two.

One problem that I did find was that the SampleProgram has a class name in the file of TestProgram.

The other problem, and I'm not sure if this may not be an Eclipse project setup issue, environment issues, or something else, but when I try to compile the SampleProgram and reference the ForLoop's convertToString, it indicates that it cannot be resolved. I believe I have the classes included into the project correctly, so I am still a little confused.

Since this is my first encounter with Java 5's new features such as the new forloops, I am not as familiar with this and was hoping you might have some idea.

Do you have any ideas? Have you encountered a similar problem?

Thanks ahead of time.

Eric Bresie
[email protected]

Servlet Newbie 11/10/05 12:22:30 PM EST

Very good article!

...however: I cannot seem to get the servlet running. I can see that it is deployed, but if I type http://localhost:8080/myapp/SampleServlet/
it gives me a required resource not found...

Help please

Eugenio Leal 11/01/05 07:47:57 PM EST

Eclipse sucks. Websphere sucks. Netbeans Rules.

Bernie's ramblings... 10/20/05 04:46:38 AM EDT

Trackback Added: Eclipse, J2SE5 and Tomcat; I’ve always liked to read about Eclipse, and knowing more about it has often made me able to work better. There’s always just some gurus out there that seems to be able to make programming a bit more bearable. An article I came across today...

Enterprise Open Source Magazine News Desk 10/17/05 03:31:03 PM EDT

Enterprise Open Source Magazine - How to Bring Eclipse 3.1, J2SE 5.0, and Tomcat 5.0 Together
We'll build a servlet that will demo some new Java 5.0 features and do some basic tasks like creating a session to track user visits to multiple Web pages. This code can easily be extended to store a user ID in the session that will travel with her as the site is navigated. The value of the visit counter is stored in the session so multiple visits to the page will be counted (this includes the page refreshes after pressing the browser's 'Reload' button). If the counter goes over five, the counter gets cleared.

IoT & Smart Cities Stories
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...