Managing Java Projects With Apache Maven

349 VIEWS

·

An important decision to be made at the outset of any Java development project is choosing a project management tool. When discussing project management for a Java project, we are referencing a tool responsible for tasks such as managing dependencies, compiling classes, packaging the project and deploying. One such tool is Apache Maven.

Maven provides the developer with a convenient and easy-to-use model for managing dependencies as well as easy-to-use instructions for packaging and deploying the application. Below, we will construct a simple Java web application as well as an additional Java dependency for use within the web application. We will use Maven to manage both of these projects and describe the process for building and deploying the web application to a local Apache Tomcat server.

If you wish to follow along with the development aspect of the projects, you will need to be configured for Java development and you’ll need to successfully install the following on your machine:

Apache Maven (I will be using v3.6.1)
Apache Tomcat (I will be using v9.0)

What is a POM file?

In the context of Maven, the acronym POM stands for Project Object Model. Each Maven project contains a POM file. This POM file is an XML file where all of the information necessary for managing the project is held. This file is appropriately named pom.xml, and it lives in the root directory for the project.

The full list of available tags and functionality for a POM file can be found by visiting the online documentation for Apache Maven, but for the purposes of this article, we can simplify the list and reference several tags of note. These include the following:

  1. project – The parent tag for pom.xml. The remaining tags reside within this project tag.
  2. modelVersion – The version for the POM file. For the most recent version of Maven (3.6.1) the modelVersion must reference 4.0.0.
  3. groupId – Unique value amongst an organization or project. Often recorded using dot notation.
  4. artifactId – Typically refers to the name of the project.
    version – Refers to the version of the project being developed.
  5. packaging – Defines how we will package the project. For a web application, we need to produce a WAR file. Therefore, the value should be war. For a typical Java library, we need to produce a JAR file and thus the value should be jar. There are other values as well, but these are the two we will be dealing with today.
  6. dependencies – Parent tag, or all dependencies utilized within the project. The individual libraries themselves will be referenced within dependency tags.
  7. dependency – Child tags that live within the dependencies’ parent tag. These tags are what we use to reference individual external projects that the project in question depends upon.
  8. Additionally, one point to mention would be the ability to add references to other repositories within your pom.xml file where your project can look for dependencies. That being said, in this particular example, this is not a concern, as all of the utilized dependencies will be stored in the Maven local repository on our local machine or in the Maven central repository. These projects are configured by default to reference these repositories.

    Creating/Building/Installing a Java project in a local Maven repository

    The initial step in our example will be to create a Java project using Maven. This Maven project will serve as a dependency for the web application that we will create later. Following the successful installation of Maven on your machine, the simplest way to create a Maven project is to open a command prompt, navigate to the directory in which you want your Maven project to reside, and run the following command:

    mvn -B archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.sample.helpers -DartifactId=sample-helpers

    The result of this command is the creation of a Maven project with the following pom.xml at the root directory of the project:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     
     <modelVersion>4.0.0
     <groupId>com.sample.helpers
     <artifactId>sample-helpers
     <version>1.0-SNAPSHOT
     <packaging>jar
    
     <name>sample-helpers
     <url>http://maven.apache.org
    
     <properties>
      UTF-8
     </properties>
    
     <dependencies>
      <dependency>
       <groupId>junit
       <artifactId>junit
       <version>3.8.1
       <scope>test
      </dependency>
     </dependencies>
    </project>
    

    There are several important aspects of this pom.xml file that should be noted. For instance, as a result of the arguments provided with the command that created the project, the groupId for the project is com.sample.helpers and the artifactId is sample-helpers. In addition, the version for the project was defaulted to 1.0-SNAPSHOT. All of this information will be critical to referencing this library in the web application we have yet to develop. Finally, the packaging type for this application was set to jar. This means that upon packaging our sample-helpers application, Maven will know to produce a jar file.

    Next, let’s add some code to our project. The idea is to give our web application some functionality to leverage when referencing the sample-helpers application as a dependency. For the sake of this example, I plan to create a simple multiply function that takes two BigDecimal arguments and returns the value of those two arguments multiplied by each other.

    From within your IDE, navigate to within the src/main/java folder for your sample-helpers project. Within that directory, the following package should exist, if it doesn’t then feel free to create it:
    com.sample.helpers

    Within that package, create a Java class by the name of MathUtil.java. The code within this file should be as follows:

    package com.sample.helpers;
    
    import java.math.BigDecimal;
    
    public class MathUtil {
    	
    	public static BigDecimal multiply(BigDecimal x, BigDecimal y) {
    		return x.multiply(y);
    	}
    }
    

    Now we have a static method (MathUtil.multiply(x, y)) that we can refer to within our web application.
    This brings us to our next steps — creating the JAR file for our sample-helpers project and installing it in our local Maven repository to be referenced by other projects. The default location for this repo will be /.m2/repository.

    The process to package and install the application is really a two-step process. The first command will remove all previous local build files associated with our project and produce new class files and a new JAR file to be installed in our local Maven repository. The second command we run will actually take that JAR file and install it in the proper location in our local Maven repo.

    Within a command prompt, navigate to the base directory for sample-helpers and run the following Maven command:

    mvn clean package
    

    The first step in this command, “clean” removes the following directory from our project structure /target. The “clean” command isn’t necessarily required, especially in your first instance packaging your project, but it never hurts to clean up the remnants of previous builds. The second step “package” produces class files and the associated JAR file for the application and places them in a newly created /target folder.

    After successfully creating the JAR file, run the following command to install the JAR file in its proper location in your local Maven repository (/.m2/repository by default):

    mvn install
    

    Upon successful installation of your JAR file within your local Maven repository, we are ready to build our web app and reference our sample-helpers project as a dependency.

    Creating a Java Web Application

    Much like the process for creating our sample-helpers project, our web application can be produced through the use of a single Maven command:

    mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=com.sample.webapp -DartifactId=sample-webapp
    

    This gives us the template for a Java web application as a Maven project. Below, you can see that I’ve modified pom.xml to reference the sample-helpers library, being sure to list the proper version for the installed library (1.0-SNAPSHOT). I’ve also included the tomcat7-maven-plugin which we will use to deploy our packaged web application to our local Tomcat server. Notice that the version for this web application is also 1.0-SNAPSHOT and the packaging type is “war” — the latter ensuring that our “mvn package” command produces a WAR file so that our application can be referenced as a web app. See the pom.xml below:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0
     <groupId>com.sample.webapp
     <<artifactId>sample-webapp
     <version>1.0-SNAPSHOT
     <packaging>war
     .
     .
     .
     <dependencies>
      <dependency>
       <groupId>com.sample.helpers
       <artifactId>sample-helpers
       <version>1.0-SNAPSHOT
      </dependency>
     </dependencies>
    
     <build>
      <finalName>sample-webapp
      <pluginManagement>
       <plugins>
        .
        .
        .
        <plugin>
         <groupId>org.apache.tomcat.maven
         <artifactId>tomcat7-maven-plugin
         <version>2.2
         <configuration>
          <url>http://localhost:8080/manager/text
          <server>tomcat
          <path>/samplewebapp
         </configuration>
        </plugin>
       </plugins>
      </pluginManagement>
     </build>
    </project>
    

    Next, I’ve added some code to the existing index.jsp file within sample-webapp. The implementation is very basic. We import the MathUtil class from our external library as well as the Java data type BigDecimal. Then we add a span tag to denote that we are looking for the result of 2 x 2. Lastly, we reference our MathUtil.multiply method to perform the function of 2 x 2 and print the result on the page. If our sample-helpers library is referenced properly in our pom.xml, we should see the text “2 x 2 = 4” on our screen when the page loads. That being said, first, we need to package our application and deploy.

    <%@ page import="com.sample.helpers.MathUtil, java.math.BigDecimal" %>
    <html>
    <body>
    <span>2 x 2 = <% out.println(MathUtil.multiply(new BigDecimal(2), new BigDecimal(2))); %>
    </body>
    </html>

    Building and deploying your Java Web Application

    Much like preparing to install our sample-helpers library in our local Maven repo, we’ll need to run a command to build and package our web application — except this time, we’ll need to navigate to our sample-webapp root directory in a command prompt prior to running the following:

    mvn clean package

    After this command has been successfully executed, a WAR file representing our packaged web application will exist in /target. With this, we are now prepared to deploy this WAR file to our local Tomcat server.

    Through the use of the tomcat7-maven-plugin that we referenced in our pom.xml earlier, we are provided with certain “goals” that can be utilized to deploy our WAR file to our local Tomcat server (which must be running for the goal to succeed). The “deploy” goal can be executed with the following Maven command, once again to be run from our project’s base directory:

    mvn tomcat7:deploy

    This will install the WAR file for sample-webapp in the webapps directory, located where Tomcat is installed on the local machine. In the POM file for sample-webapp, we specified the path for our Tomcat plugin configuration to be “/samplewebapp”. Therefore, we can visit our page by navigating to the following URL within a web browser:

    http://localhost:8080/samplewebapp

    See figure 1 for the result of the page load:

    Fig. 1: sample-webapp running on tomcat server

    Conclusion

    When managing a Java software project, Apache Maven is one of the more intuitive project management tools for the job. Primarily done through the use of a POM file and Maven commands, a developer can quickly get up to speed in the areas of dependency management and installation for Java projects meant to serve as libraries, as well as the deployment of Java web applications.


Scott Fitzpatrick has over 5 years of experience as a software developer. He has worked with many languages, including Java, ColdFusion, HTML/CSS, JavaScript and SQL.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu