How To Create A Java Web Application With Maven

In this tutorial, we will show you an easy way to create a Java web application project, using Apache Maven. Also, we will make it support Eclipse IDE. Finally, we will complete the tutorial, by showing how we can package our Java project into an executable “.jar” file.


Tools used :

  • Maven 3.0.5
  • Eclipse Juno
  • JDK 6
  • Tomcat 6.0


Web Application Project from Maven Template

Archetype is a Maven project templating toolkit that enables the creation of Maven project templates for users.

In this tutorial, we will show you an easy way to create a Java web application project, using Apache Maven. Also, we will make it support Eclipse IDE. Finally, we will complete the tutorial, by showing how we can package our Java project into an executable “.jar” file.


Tools used :

  • Maven 3.0.5
  • Eclipse Juno
  • JDK 6
  • Tomcat 6.0


Web Application Project from Maven Template

Archetype is a Maven project templating toolkit that enables the creation of Maven project templates for users.





First of all, using the terminal (Linux or Mac) or the command prompt (Windows), navigate to the folder where the new project shall be created Using the command

mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

This tell Maven to create a Java web application project from “maven-archetype-webapp” template.

Open command prompt and navigate to the folder where you want to create project(In my case I have created MavenProject folder inside D drive).Issue the following command.

mvn archetype:generate -DgroupId=com.javawebtutor -DartifactId=SampleWebApplication -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

This command creates a new Java web application project under the name SampleWebApplication, along with its entire directory structure.

maven web project


Layout of the project’s directory


maven web project

By default, the source code of the project is located under the folder “/src/main/resources/webapp”.

In addition, two files are automatically generated by Apache Maven. The first one is the pom.xml file and the second file is the standard deployment descriptor, called web.xml. These special files contain all necessary information about the project’s compilation and deployment.

pom.xml file is shown below:

pom.xml
<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>com.javawebtutor</groupId>
  <artifactId>SampleWebApplication</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SampleWebApplication 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>SampleWebApplication
  </build>
</project>



In generated web.xml – Servlet 2.3 is too old, consider upgrade to 2.5.The generated web.xml file is shown below:

web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


  Archetype Created Web Application



Generated index.jsp file is shown bellow:

index.jsp
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

Update POM :

We are going to create a simple servlet example that will print a simple message . Let us add servlet dependency in our pom.xml file as shown bellow.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>

It is recommended that you add the compiler plugin, in order to guide Maven for which JDK version to use for compiling your project. Add the following lines to your pom.xml file:

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>

Update the jUnit from 3.8.1 to latest 4.11.

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

The above XML snippet is called a “Maven Coordinate”. In order to declare the jUnit “.jar” file as a dependency to your project, you must find its corresponding Maven Coordinate. The same procedure must be executed for every external “.jar” file that poses as a dependency to your project, such as Apache Common, Spring, etc. For your convenience, visit the Maven Central Repository and choose the most appropriate Maven Coordinate for every dependency of your project.

The final form of our pom.xml file is given bellow

<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>com.javawebtutor</groupId>
	<artifactId>SampleWebApplication</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SampleWebApplication</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.0</version>
			</plugin>
		</plugins>
	</build>
</project>



Add the M2_REPO classpath variable in Eclipse IDE

The “M2_REPO” classpath variable is required by the Eclipse IDE, in order to locate all declared depencencies for a Maven project. This variable must point to Maven’s Local Repository.

  1. Open Eclipse IDE, and click on Windows -> Preferences.

  2. In the left panel, click on Java -> Build path -> Classpath Variables

  3. In the right panel, click on “New:” button and fill these values: Name: “M2_REPO” Path: “C:\Users\Username\.m2\repository\”

  4. Click on the “OK” button.


maven java project

maven java project



Eclipse IDE Integration


http://download.eclipse.org/technology/m2e/releases

You can install Maven plugin for Eclipse via update site, simply copy the above update site link address and paste it into Eclipse’s “Update” or “Install New Software” manager as explained below.

Step 1 :

Open Eclipse IDE and navigate to
Help -> Install New Software…

Copy this link http://download.eclipse.org/technology/m2e/releases for the latest Release into Eclipse and hit Enter.

Maven Eclipse Plugin

When the site loads, select the features to install, or click the Select All button. For our requirement select “Maven Integration for Eclipse” as shown above.

Step 2 :

Click Next -> Next and agree the license terms, and click Finish.

Step 3 :

If you get any warning message when installing, click OK to continue.

This will take few minutes to install the Maven plugin and once done restart the Eclipse.

Maven Eclipse Plugin

Thats all folks now we are ready to import our project into the Eclipse IDE:

Click on File > Import and Choose Maven > Existing Maven Projects and then, click on ‘Next’. As a root directory, enter the path of our web application project which we created earlier. Choose our web application project and click on ‘Finish’ as shown bellow.

maven web project

maven web project


Now Right click on our project, click on ‘Properties’ and in the left panel choose ‘Project Facets’, we shall see the following screen.In that screen choose Dynamic Web Module as 2.5 and Java as 1.6 as shown bellow and click on OK button.

maven web project


Directory Structure of Project in Eclipse :


maven web project


Create Servlet Class :

Create a package com.jwt.maven inside src\main\java andCreate a servlet file HelloWorldServlet.java in that package.

package com.jwt.maven;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1031422249396784970L;
 
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException  {
         
        resp.setContentType("text/html");
         
        PrintWriter out = resp.getWriter();
        out.print("Hello World from Servlet");
        out.flush();
        out.close();
    }
}


Update web.xml

Once the servlet is created, let us configure this in web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>HelloWorldServlet</display-name>
    <welcome-file-list>
        <welcome-file>hello-world</welcome-file>
    </welcome-file-list>
 
    <servlet>
        <servlet-name>HelloWorldServlet</servlet-name>
        <servlet-class>
            com.jwt.maven.HelloWorldServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorldServlet</servlet-name>
        <url-pattern>/hello-world</url-pattern>
    </servlet-mapping>
</web-app>

Package the Application into a .war file

We can now use Apache Maven to package our application into an executable “.war” file. The “packaging” element inside our pom.xml” file defines the packaging format or output.

Open command prompt and navigate to the SampleApplication project folder and execute the command:

mvn package

maven web project

war file will generate in target folder as shown bellow.

maven web project





comments powered by Disqus