Create a Web Application Project with Maven

Archetype is a Maven plugin that allows the user to create a Maven project from an existing template. This system helps the developers to get started quickly on a new project and introduces new users to the best practices employed by Maven.

By default Maven offers a set of predefined archetypes, one of which is the web application archetype.

To create a web application project with Maven, issue the following command:

mvn archetype:generate \
    -DarchetypeGroupId=org.apache.maven.archetypes \
    -DarchetypeArtifactId=maven-archetype-webapp \
    -DgroupId={project-groupId} \
    -DartifactId={project-artifactId} \
    -Dversion={project-version}

Replace the values {project-groupId}, {project-artifactId} and {project-version} with something meaningful for your project.

The above command will create a folder called {project-artifactId} that contains a simple pom.xml file and a src folder which contains the basic structure of the web application.

Issuing the following command:

mvn archetype:generate \
     -DarchetypeGroupId=org.apache.maven.archetypes \
     -DarchetypeArtifactId=maven-archetype-webapp \
     -DgroupId=groupID \
     -DartifactId=artifactID \
     -Dversion=0.1

Will create the following project structure:

tree artifactID/
artifactID/
├── pom.xml
└── src
    └── main
        ├── resources
        └── webapp
            ├── index.jsp
            └── WEB-INF
                └── web.xml
 
5 directories, 3 files

An important note is that your Java code should go under the folder src/main/java/ which is not created by default. Maven uses convention over configuration. So you have to put your Java files in this specific folder, otherwise Maven won't know where to find the source files and it won't compile them.

The pom.xml file has the following contents:

<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/maven-v4_0_0.xsd">
 
  <modelVersion>4.0.0</modelVersion>
  <groupId>groupID</groupId>
  <artifactId>artifactID</artifactId>
  <packaging>war</packaging>
  <version>0.1</version>
  <name>artifactID Maven Webapp</name>
  <url>http://maven.apache.org</url>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
 
  <build>
    <finalName>artifactID</finalName>
  </build>
</project>

Comments

Mind sharing how you learned to use Maven? I tried learning it a few months ago and gave up in frustration. I read through the books offered by Sonatype (www.sonatype.com), but still couldn't wrap my head around Maven.

Add new comment