Integrate the Eclipse Web Tools Platform and Maven

Integrate the Eclipse Web Tools Platform and Maven

he Eclipse Web Tools Platform (WTP) and the M2Eclipse (M2) plugin are separate projects, each with high value for the developer who uses Eclipse. WTP is a tools bundle that extends the Eclipse platform for web and Java EE application development, while M2 integrates Maven tightly into the IDE. Leveraging both in the same project has compelling benefits for the developer. Unfortunately, Eclipse has yet to offer WTP and M2 integration OOTB (that’s Out Of The Box, if you didn’t know). That’s where this article comes in.

This article demonstrates basic web application development using both WTP and M2 as an integrated solution. By walking through a project-building exercise from setup through deployment, it will enable you to speed up your own Eclipse-based Java web development by applying the same process.

Environment Setup
The primary development environment for the project described in this article is Eclipse. Your Eclipse environment must include the following technologies to complete the exercise.

What You Need
WTP 2
M2 Plugin
The latest version of Java 5
The latest versions of Tomcat
The settings file from the Maven 2 install
(available in the apache-maven-2.0.8conf folder)
 
Figure 1. Server Configuration: Follow these steps to configure the server.

See Sidebar 1 for a more complete list of Eclipse download links.

WTP and M2Plugin Configurations
Before you begin, you must set some initial server, browser, and Maven configurations. In fact, when you launch Eclipse with the M2 plugin you may see an error message regarding a settings.xml file. Ignore the message. It will be resolved shortly.

Server Configuration
Configure your server to run the web application. From the Eclipse menu, follow these steps to configure the server (see Figure 1): Windows?Preferences?Server?Installed Runtimes?add.

Select the appropriate version of Tomcat. In the next page of this wizard screen, browse to the Tomcat home directory and press “finish.”

 
Figure 2. Maven Settings: Navigate through Eclipse Menu?Window?Preference and click on Maven in the left panel.

Configure Browser
When you launch a web application using WTP, it opens in an internal browser. You may prefer to have your web applications open in an external browser of your choice. If so, configure the external browser to launch using the Eclipse menu path Window?Web Browser.

Maven2 Configurations
Navigate through Eclipse Menu?Window?Preference and click on “Maven” in the left panel. This may take a short while. If so, please wait. Note the file path mentioned in the “User Settings file” field (see Figure 2). Ensure a valid settings.xml file is present in this location. If you don’t have a valid settings.xml file there, copy it from apache-maven-2.0.8conf. Press the “OK” button.

Now you can start the actual work of creating a dynamic WTP project and integrating it with the M2 plugin.

Project Setup
In this section, you will create a WTP dynamic web application project and enable Maven support using the M2 plugin. More specifically, you will learn the details behind the following tasks:

  • Modifying the project folder structure and Java build settings so that both correspond to Maven
  • Modifying a specific WTP metadata file for the same purpose
  • Making WTP use the pom.xml fully

Before you get started, explore the M2 plugin briefly by creating a new Maven web project.

New Maven Web Project
Launch the “New Maven2 project” wizard by navigating to File?New?Other?Maven?Maven Project. Enter the data in Table 2 below into the wizard screen pages. Accept defaults for all data except those shown in yellow-highlighted bold.

Page Data
Page 1
Project Name tempForRef
“Create in Workspace” radio button Select this button
Page 2
Group ID tempForRef
Artifact ID tempForRef
Version 0.0.1-SNAPSHOT
Packaging war
Description Leave blank or fill in with whatever is appropriate
Project Layout Ensure these checkboxes are checked: src/main/java, src/main/resources, src/test/java, src/test/resources, and src/main/webapp
Page 3 Ignore this page
Table 2. Data Details for Creating Maven 2 Project

You may be wondering whether you can convert this M2 project into a WTP dynamic web project. Yes, you can. But it’s easier to convert a WTP dynamic web project into a M2 project than a M2 project into a dynamic web project.

Now you’re ready to create a separate dynamic web project.

New Dynamic Web Project
Create a new dynamic project from the following menu path File?New?Other?Web?Dynamic Web Project. Use the project name sample1, and choose the defaults for everything else. If you are prompted to go into the “Java EE” perspective, accept it by pressing the “Yes” button.

Table 3 lists the values in each screen for reference. Note that the project name is the only value that needs to be entered.

Page Data
Page 1
Project Name sample1
Project Contents Use default (For Directory)
Target Runtime Apache Tomcat v6.0
Configurations Default Configuration for Apache Tomcat v6.0
Page 2
Dynamic Web Module Selected by default
Java Selected by default
Page 3
Context Root sample1
Content Directory WebContent
Java Source Directory src
Table 3. Data Details for Creating New Dynamic Web Project

It’s now time to use the M2 plugin on this project.

Enable Maven
Right click on the project, and in the popup menu, enable Maven by navigating to the path Maven?Enable Dependency Management. This will launch the POM creation wizard (see Figure 3).

 
Figure 3. POM Creation Wizard: Enable Maven by launching the POM creation wizard.

Choose “war” for packaging, and press the “finish” button.

After enabling Maven you still have a few steps to complete the integration:

  1. Creating Maven folder structure
  2. Updating source folders
  3. Some manual tweaking of WTP internals
  4. Configuring J2EE Module dependencies

Create Maven Folder Structure
Open the navigator view using Window?Show View?Other?General?Navigator. By default the dynamic project has a different structure, which interferes with the integration. So give the project a typical Maven folder structure. You can do this in two ways:

  1. Using the navigator view, go into the Maven project you created (tempForRef). Copy the folders “src” and “target.” Again in the navigator view, go into the project sample1 and carefully paste the folders there.
  2. Create these folders using File?New?Folder: src/main/java, src/main/resources, src/main/webapp, src/test/java, src/test/resources, target/classes, and target/test-classes.

Update Source Folders
By default the dynamic project also differs in its Java build settings (e.g., its source and output folders) from what’s needed for M2 integration. You need to the configure source folders for Java code. You can do this using either a manual approach and an automatic approach through a menu. This exercise uses the manual approach because it enables you to get everything working with the least effort.

In the project sample1, use navigator view to open the file .classpath. Verify that it has the following contents.

xml version="1.0" encoding="UTF-8"?><classpath>     <classpathentry kind="src" path="src"/>     <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>     <classpathentry kind="con" 
path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v6.0"/> <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/> <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/> <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/> <classpathentry kind="output" path="build/classes"/>classpath>

There may be some differences. For example, details of the Tomcat version mentioned in the XML may be different. In WTP 2.0.1 there is this entry for org.eclipse.jst.j2ee.internal.module.container, which is not there in WTP2.0. The highlighted sections are what you need to change. Therefore, don’t copy and paste the entire XML text. Directly edit this file and make the highlighted changes:

xml version="1.0" encoding="UTF-8"?><classpath>     <classpathentry kind="src" path="src/main/java"/>     <classpathentry kind="src" path="src/main/resources"/>     <classpathentry kind="src" output="target/test-classes" path="src/test/java"/>     <classpathentry kind="src" output="target/test-classes" path="src/test/resources"/>     <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>     <classpathentry kind="con" 
path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v6.0"/> <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/> <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/> <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/> <classpathentry kind="output" path="target/classes"/>classpath>

Note: The version of Tomcat mentioned in the actual .classpath file might differ. Do not modify the Tomcat details when making the changes. Remember to save the changes when done.

Some Manual Tweaking of WTP Internals
After updating the source folders you need to do some additional tweaking for better integration. Open the project in navigator view and edit the file .settings/org.eclipse.wst.common.component. If required open the source tab in the editor and do the following:

  • Replace /WebContent with /src/main/webapp.
  • Replace build/classes with target/classes.

Delete the entry for the following:

"/src/test/java"/>"/src/test/resources"/>

This should be the resulting XML:

xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0"><wb-module deploy-name="sample1"><wb-resource deploy-path="/" source-path="/src/main/webapp"/><wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/><wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/><property name="context-root" value="sample1"/><property name="java-output-path" value="target/classes"/>wb-module>project-modules> 
 
Figure 4. J2EE Module Dependencies: Link the maven2 dependencies with the J2EE Module dependencies.

Remember to save the changes when done.

Carefully move the folders META-INF and WEB-INF under /WebContent to src/main/webapp. In the navigator view, delete the folders WebContent and build.

Configuring J2EE Module Dependencies
Launch the project properties by right clicking on the project and selecting “Properties” in the pop up menu. Select “J2EE Module Dependencies” in the left panel. Link the maven2 dependencies with the J2EE Module dependencies by checking the checkbox shown on the screen (see Figure 4). Ignore any other checkboxes.

Pressing “Apply” button should clear the warning shown in Figure 4.

Review your previous steps and ensure everything was done properly. At this point you should have no error messages or warnings related to the sample1 and tempForRef projects in the Problem view in Eclipse.You are now set for actual development.

Development?Finally!
This section mainly deals with using Maven to perform the basic M2 plugin task of modifying a classpath by adding jars. It details how you can edit the pom.xml file using the editor and the repository search tool, and explains how to launch Maven goals. More trivially, it demonstrates how to launch and debug a “Mavenized” project using WTP. By the end, you will have written some code and created a very basic MVC application.

 
Figure 5. Repository Search for Adding Dependencies: Begin by adding a few dependencies.

In order to verify that the application works without any issues related to tag libraries, you will be using the displaytag library.

Dependency Management
Begin by adding a few dependencies. In the repository search (launched by right clicking on the project and in the pop up menu navigating to Maven?Add Dependencies), type in “tomcat,” select the highlighted servlet-api jar, and press the “OK” button to add the jar into the POM (see Figure 5).

Open the pom.xml file. In the editor, click on the “source” tab (if needed). Using the standard content assist in the editor, insert “provided” in the scope (see Figure 6). If you encounter any difficulty, just type provided in the appropriate location. Refer to the pom.xml file in Figure 6.

Likewise, add the JUnit and displaytag dependencies. The resulting pom.xml file looks like this:

 
Figure 6. The POM Editor: Using the standard content assist in the editor, insert “provided” in the scope.

xml version="1.0" encoding="UTF-8"?><project>  <modelVersion>4.0.0modelVersion>  <groupId>sample1groupId>  <artifactId>sample1artifactId>  <packaging>warpackaging>  <version>0.0.1-SNAPSHOTversion>  <description>description>  <dependencies>    <dependency>      <groupId>tomcatgroupId>      <artifactId>servlet-apiartifactId>      <version>5.5.15version>      <scope>providedscope>    dependency>        <dependency>      <groupId>junitgroupId>      <artifactId>junitartifactId>      <version>4.4version>      <scope>testscope>    dependency>        <dependency>      <groupId>displaytaggroupId>      <artifactId>displaytagartifactId>      <version>1.1.1version>    dependency>      dependencies>project>
 
Figure 7. Repository Search Highlights Existing Dependencies: Using the standard content assist in the editor, insert “provided” in the scope.

For JUnit’s and Tomcat’s servlet-api jars, the scope is test and provided, respectively.

Note: The servlet-api jar is not really needed when developing with WTP. However it’s needed for running Maven 2 goals from the command line.

The next time you perform the same search, the newly added dependencies will display in red to indicate their existence in the pom.xml file (see Figure 7). You won’t be able to add them again unless the dependency is first removed.

Maven Run Configurations
Create a run configuration for Maven called sample1.package by using the tool bar button circled in red in Figure 8. Then click on “Open External Tools Dialog.” Follow the instructions to create a new Maven run configuration by selecting “Maven Build” and pressing the button pointed to by the red arrow in Figure 8. Use the buttons “Browse Workspace” and “Select” to set the Base directory and the Goals, respectively.

The following is the data for your Maven run configuration:

 
Figure 8. Using External Tools for Maven Run Configurations: Create a new Maven run configuration.
  • Name: sample1.package
  • Base Directory: ${workspace_loc:/sample1}
  • Goals: package

Configuring such goals also allows you to pass additional arguments and VM arguments to the Maven command. Press the “Run” button. Thereafter, wait for the jars to be downloaded into the local repository and monitor the download progress from the Eclipse console.

After executing the target once, you can quickly access it using a drop down in the toolbar menu (see Figure 9).

For additional common Maven goals such as clean, test, and so on, right click on the project, execute them from the popup menu “Run As,” and select the appropriate ready-to-use Maven goal.

You have now progressed to the point where you can add some code.

 
Figure 9. Recently Used Maven Run Configurations: You can quickly access the target.

Adding Some Code
You can create servlets and JavaServer Pages (JSPs) using the wizard you’ll find in File?New?Other?Web. If you used this wizard to create a servlet, verify that the servlet is registered in web.xml (as it should). If it is not, web.xml is also provided with the downloadable code for the example application.

In this simple application example, index.jsp forwards to a servlet, which in turn forwards to a view JSP. The application also makes use of the displaytag tag library to display a table. You can use the downloadable code to quickly create the application. You can easily unzip it and copy the src folder contents into the src folder of the sample1 project. The pom.xml file, which is outside the src folder anyway, is the only other file that’s code-related.

Launching the Web Application from WTP
Now let’s test the debugging functionality:

  1. Put a breakpoint in the servlet doGetMethod.
  2. Launch the application by right clicking on the project and executing “Debug As” (see Figure 10).
  3. Select “Debug on Server”.
  4. If there is no option to use “Choose an existing server,” use “Manually define a new server” only.
 
Figure 10. Launching the Web Application: Launch the application by right clicking on the project and executing “Debug As”.

In the next page of the wizard screen, ensure that the project is showing up under “Configured projects”. You can experiment with the debugging capabilities of WTP by placing breakpoints in JSPs or the servlet?or, for that matter, in any other code. If you encounter issues, you may need to relaunch after deleting the server shown in Figure 11. (You won’t need it the first time.)

Eclipse will launch the browser and show the application in it. Depending on the breakpoint, Eclipse may go into the debug perspective. You can even set your breakpoints at runtime and see the effects. Alternatively, you can also launch using Run As?Run On Server in the same manner.

Verifying WTP and M2 Plugin Integration
Based on the output and debugging session, you can confirm whether or not the integration was successful.

Note: Changes you make to the servlet, simple classes, and JSPs get dynamically reflected in the output because WTP is pushing all changes into the server. If you don’t need this feature, feel free to stop the server, or delete the server from the server view discussed above. Running Maven goals of “package” does not affect this functionality in anyway. In fact, all other Maven goals can be executed in the same manner.

 
Figure 11. Servers View: Launch the application by right clicking on the project and executing “Debug As”.

For Further Consideration
The M2Eclipse plugin not only works nicely, but it can also integrate well with WTP. However, this integration does require some configuration even for web application projects as simple as this example used in this article.

The following are some additional tips to keep in mind when integrating M2 and WTP with the techniques described in this article:

  1. There is no need to maintain the .classpath file, nor is there a need to use the eclipse:eclipse goal that was used previously with the Maven Eclipse plugin. The .classpath is much cleaner because the pom.xml is used as a valid metadata for understanding the individual jars. All the referenced jars from the repository don’t show up in the .classpath.
  2. The key to doing a WTP and M2 integration is to understand folder structures, Java build path settings, and the file .settings/org.eclipse.wst.common.component.
  3. You can learn everything about the actual application that you deployed by examining the folder .metadata.pluginsorg.eclipse.wst.server.core inside the workspace. You will need to explore the subfolders to locate the actual location where the web application is being assembled when you execute “Run on Server”. A close look at it reveals that the servlet-api jar and the JUnit jar are not inside the assembled application’s WEB-INF/lib folder, because they had scopes of provided and test, respectively. The earlier builds of the M2 plugin had an issue in this regard.
  4. If you use Maven 2, you don’t need MAVEN_HOME or any other environment variable except JAVA_HOME and the correct path. And you need those only for executing Maven 2 from the command line.
  5. The M2 plugin uses a component of Maven called Maven Embedder. Embedder has been used by the Maven command line interface (CLI) since version 2.1.
  6. You must use Maven from the command line as part of continuous integrations and a regular non-IDE based build process. When running Maven from the command line to build and deploy the web application into Tomcat, refer to the Maven 2 documentation and the Maven 2 book Better Builds with Maven.

devx-admin

devx-admin

Share the Post:
AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s