Building Java projects from source code to executable packages have come a long way: It started with manually calling the Java Compiler and managing the classpath and external libraries and went from there to a lot of different build tools. I want to give you a quick overview of how to setup your project to build a web application with Apache Maven.
Now over twenty years ago you had the javac command and compiled your project by manually calling the compiler from the command line. That being said you had to manage the classpath and external libraries -- like JAR files -- by yourself.
I remember that back in the nineties we used Make files to build our Java projects because we were used to it when working with C or C++ earlier.
After that one build tool after another was published. Ant, Ivy, Maven, Buildr, Gradle, Bazel, Buck, Pants, sbt and there are more tools that want to help you build your project.
If you ask ten software developers about their opinion how a build tool should work you will likely end up with eleven answers to your question. To be fair, some concepts and build tools may be better than others. But since Apache Maven is a solid choice -- of course based on my totally superior opinion -- I want to show you how to build a web app with it.
You can either create a project skeleton on the command line using the mvn command or you can do this with an IDE like Eclipse in this example.
You just select New Project and then Maven Project. If you want to the wizard creates a basic project structure for you and I selected webapp here. Fill in the details like the group and artifact id and you will end up with a project.
Surely you will notice the little error sign that is displayed and you can rid of this by adding the servlet-api dependency to the pom.xml file. This file holds you build definition.
<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency>
After that the error will be gone. You can then add the whole project to an application server like Apache Tomcat in this case and start it directly in Eclipse. When you then open a web browser you can check out whether the web app is running -- and it seems just fine here.
The actual build with Maven
But all that is not a build with Maven. You want to deploy your web application with a WAR file and to do that you right click on your project, select Run as and Maven build. In case a window pops up specify the “package” goal and click on Run again.
Once you’ve done that the target folder contains a WAR file that you can deploy in an application server. And that’s how you build a simple web application project with Apache Maven.