Creating Dynamic Web Project using Maven in Eclipse

While using Maven as build tool in our project, I found it very difficult to create a Dynamic Web Project which supports Maven dependencies and can execute in Eclipse! I have seen lot of people using Maven just as build tool and for local setup uses jar files in some /lib directory. I wanted to remove this dependencies on local /lib for jar files and resolve everything with Maven. My project should be a Dynamic web project with Maven dependencies enabled.

Here is a simple tutorial which you can go through to create Dynamic Web Project having Maven enabled in Eclipse. This project can be used as base project and can be easily converted to most kind of project like Struts based, Spring MVC based etc.

Required Tools

For this tutorial, I assume you have following setup in your machine.
1. JDK 1.5 or above (download)
2. Eclipse 3.2 or above (download)
3. Maven 2.0 or above (download)
4. M2Eclipse Plugin (download)

Step 1: Create Maven Project in Eclipse

Create a new project in Eclipse. Goto File > New > Project.. and select Maven Project from the list. Click Next.
eclipse-maven-new-project

Enter “MavenWeb” as Project name and click Next. On Configuration screen, select war in Packaging and also check the checkbox for src/main/webapp.

new-maven-project

Once done, click Finish. This will create a Maven project in Eclipse.

Step 2: Generate Eclipse Project with WTP

Let us convert the Maven project to Dynamic Web Project for Eclipse. For this we will use following maven command.

mvn eclipse:eclipse -Dwtpversion=1.5

Goto the folder where the new project is created and execute above command.

C:\Workspace\Test\MavenWeb>mvn eclipse:eclipse -Dwtpversion=1.5

[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------------------
[INFO] Building Unnamed - MavenWeb:MavenWeb:war:0.0.1-SNAPSHOT
[INFO]    task-segment: [eclipse:eclipse]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing eclipse:eclipse
[INFO] No goals needed for project - skipping
[INFO] [eclipse:eclipse]
[INFO] Adding support for WTP version 1.5.
[INFO] Using Eclipse Workspace: C:\Workspace\Test
[INFO] no substring wtp server match.
[INFO] Using as WTP server : Apache Tomcat v5.5
[INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER
[INFO] Not writing settings - defaults suffice
[INFO] Wrote Eclipse project for "MavenWeb" to C:\Workspace\Test\MavenWeb.
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4 seconds
[INFO] Finished at: Wed Jul 28 13:55:09 CEST 2010
[INFO] Final Memory: 7M/30M
[INFO] ------------------------------------------------------------------------

That’s it. We just created Dynamic Web Project from Maven project. Now refresh the project in Eclipse.

Step 3: Change Project Facet

The above step by default set the project facet to JDK 1.4. We need to modify this and set project facet to JDK 5. Right click on MavenWeb project and select Properties (shortcut: Alt+Enter). From the Properties dialog box, select Project Facets. Now click on “Modify Project…” button and change the project facet to Java 5.0
project-facet-maven-eclipse

Step 4: Setting Build Path

We need to specify the Maven jar dependencies in Java Build Path of our MavenWeb project. Open Properties.. dialog box (Alt+Enter) and select Java Build Path. Click “Add Library..” button and select “Maven Managed Dependencies” and click Finish.
maven-eclipse-build-path

Step 5: Hello World Servlet

Our dynamic web project with maven support is done now. Let us add a small Hello World servlet to this project and see how it works.

Open pom.xml from root folder and copy following content into it.

File: pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project>
	<modelVersion>4.0.0</modelVersion>
	<groupId>MavenWeb</groupId>
	<artifactId>MavenWeb</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<description></description>
	<build>
                <plugins>
                        <plugin>
                                <artifactId>maven-compiler-plugin</artifactId>
                                <configuration>
                                        <source>1.5</source>
                                        <target>1.5</target>
                                </configuration>
                        </plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.0</version>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
	</dependencies>
</project>

Also create a servlet file HelloWorldServlet.java. We will add this servlet in net.viralpatel.maven package.

File: /src/main/java/net/viralpatel/maven/HelloWorldServlet.java

package net.viralpatel.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();
	}
}

Once the servlet is created, let us configure this in web.xml. Note that in our maven project no web.xml is present. We will create one at /src/main/webapp/WEB-INF/ location.

File: /src/main/webapp/WEB-INF/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>
			net.viralpatel.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>

That’s All Folks

Our dynamic web project with Maven support in Eclipse is completed. Run the web project in eclipse (Alt+Shirt+X, R)
hello-world-maven-eclipse-web-project

Download Source

Click here to download the source code (7.0 kb)



39 Comments

  • Eugene Kuleshov 29 July, 2010, 22:26

    All you had to do is to install “Maven Integration for WTP”.

  • Rafal Borowiec 30 July, 2010, 1:33

    Some time ago I created a similar post on how to create dynamic web project with Eclipse 3.5. See http://blog.goyello.com/2010/06/15/how-to-create-java-web-application-with-eclipse-wtp-and-m2eclipse/. The project can be downloaded here: http://blog.goyello.com/wp-content/uploads/2010/06/wtp-m2eclipse-demo.zip

    Recently I found out that with Eclipse 3.6 and m2eclipse you could use webapp-jee5 archetype that works perfectly with WTP and Eclipse 3.6. Of course, Maven integration for WTP is required (available via m2eclipse extras update site)

  • Allaeas 9 September, 2010, 8:50

    thanks for sharing ;)

  • Jack 5 October, 2010, 13:03

    Thanks for sharing :) Really amazing !

  • springMvcBeginner 16 November, 2010, 18:47

    how can I configure Eclipse 3.2, Maven 2.0, and M2Eclipse Plugin together? sorry im just beginner. thanks.

  • springMvcBeginner 16 November, 2010, 18:57

    and how to integrate it to spring mvc3 framework?

  • DUD3 19 January, 2011, 0:51

    For integrating maven + eclipse you need to download and install the m2eclipse plugin from your Eclipse IDE (help -> update software, or eclipse marketplace). AND you HAVE TO download the Maven from the link provided in the beginning of this tutorial – Required software – 3. Maven 2.0 or above. Once you have it, scroll down the maven download page and check installation instructions for you system. That should all work together.

  • KADDOURI Kamal 16 February, 2011, 21:00

    thanks for your tutorial, but I want to notice that the version of hibernate-entitymanager is not well as far to lanch example, so to resolve this, I replace this :

    org.hibernate
    hibernate-entitymanager
    3.3.2.ga

    by this :

    org.hibernate
    hibernate-annotations
    3.3.1.GA

  • Alex 13 July, 2011, 14:19

    Hi,

    First of all i want to thank you I’ve learned a lot.

    Can you please help me with this
    Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist

  • Kurt Junshean Espinosa 29 August, 2011, 7:16

    Thank you my friend for writing this tutorial! Very very helpful.

  • Sachin 19 September, 2011, 11:57

    Thanks..Its helpful…

  • Vikrant 18 October, 2011, 16:26

    Thanks it was really helpful

  • KRGancheva 21 December, 2011, 16:48

    That’s one really useful and easy to follow tutorial. Thanks a lot for making it!

  • Adnan Saadeddin 2 May, 2012, 1:36

    Thanks man, great tutorial. :D

  • ram ganesh 23 May, 2012, 12:03

    Really very helpful…..:) :) :)

  • omg 24 May, 2012, 5:22

    HTTP Status 404 – Servlet HelloWorldServlet is not available
    :(

  • siva 3 June, 2012, 20:26

    Very useful article.Thanks for sharing

  • Rafa 19 June, 2012, 13:57

    Thank you. It’s awesome.

  • alvaro 18 July, 2012, 13:18

    Thanks very much man, but I have some question, When I compile the project its say:

    no web.xml present

    How can i solve it?

    Thanks :D

  • sridhar 18 July, 2012, 17:08

    sir i want how create my-eclipse basic strut plz send me mail id

  • DUD3 Student 3 August, 2012, 13:09

    How to get The Maven dependencies(the lib u are adding above) and what it will do. please guide me

  • Adrien 22 August, 2012, 21:57

    A quick update (2012):

    Creating Dynamic Web Project using Maven in Eclipse Indigo Service Release 2 (Build id: 20120216-1857)

    1. Tools I had during this config
    Note: depending on what version of Eclipse and/or M2E plugin you have, these steps may change
    a. JDK 1.7
    b. Eclipse, Version: Indigo Service Release 2, Build id: 20120216-1857
    c. Maven 3
    d. M2E Plugin installed

    2. Create a new project in Eclipse
    File > New > Project.. and select Maven Project from the list (webapp-javaee6). Click Next.
    Enter “com.maveneclipseweb.test” as GroupId, ArtifactId “MavenEclipseWeb”, & Package “com.maveneclipseweb.test”. Click Finish.

    3. Change Project Facet
    From the Properties dialog box, select Project Facets. Now click on “Convert to Faceted form..” button.
    Then tick Dynamic Web Module, below click on the box saying “Further configuration available” & put in Content directory “/src/main/webapp”.
    Click on OK.

    5. Modify the index.jsp
    Add some custom text so you can verify this is your web app…

    6. Run the Web App on Tomcat through Eclipse
    In Eclipse, Window >> Show View >> Servers
    Note: we assumed you have downloaded & installed Tomcat here
    Option 1: If there is no server, Click right anywhere in that window >> New >> Server >> Tomcat 7.0 >> Next, then Select your project >> Add >> Finish
    Option 2: If there is already a server, Click right >> Add/Remove, then Select your project >> Add >> Finish
    Finally, Click right >> Start

    7. Check this is working in your browser
    Go to http://localhost:8080/MavenEclipseWeb/
    You should see the custom text you entered earlier in your index.jsp page

    • hamsika 12 October, 2012, 2:34

      Hi,

      I am using Rational Application Developer 8 and I have followed the above steps and able to convert the Dynamic Web Project from Maven project. But I am not able to add created ear file to Web Sphere Application server. If possible could you please tell me the process.

      Thanks

  • Bharat 7 October, 2012, 15:12

    Hi Viral,

    I am new to Maven, can you plz share a web project build in struts 1.2 using Maven.

    I tried the above proj and it works fine for me but I am not able to convert it into struts 1.2 flow.

    Thanks,
    Bharat

  • charu agarwal 11 March, 2013, 22:15

    i am getting Error in custom provider, java.lang.TypeNotPresentException: Type javax.enterprise.inject.Typed not present
    pls help me…..thanks in advance

  • Jitendra 19 March, 2013, 18:59

    Thanks. It worked for me.
    Do you know for, how to publish automatically for ear deployment for a Maven project.

  • Application android 21 March, 2013, 19:58

    Many thans for you. Good article :)

  • Amol Pacharne 1 April, 2013, 14:19

    Thanks man ! it really helpful !

  • Ravindra 5 July, 2013, 11:56

    Getting the below error: any help will be appreciated.
    ==========================================
    Description Resource Path Location Type
    Could not calculate build plan: Missing:
    ———-
    1) org.apache.maven.plugins:maven-resources-plugin:maven-plugin:2.4.1

    Try downloading the file manually from the project website.

    Then, install it using the command:
    mvn install:install-file -DgroupId=org.apache.maven.plugins -DartifactId=maven-resources-plugin -Dversion=2.4.1 -Dpackaging=maven-plugin -Dfile=/path/to/file

    Alternatively, if you host your own repository you can deploy the file there:
    mvn deploy:deploy-file -DgroupId=org.apache.maven.plugins -DartifactId=maven-resources-plugin -Dversion=2.4.1 -Dpackaging=maven-plugin -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]

    ———-
    1 required artifact is missing.

    for artifact:
    org.apache.maven.plugins:maven-resources-plugin:maven-plugin:2.4.1

    from the specified remote repositories:
    central (http://repo1.maven.org/maven2, releases=true, snapshots=false)
    MavenWeb Unknown Maven Problem

  • Chetan Phanse 15 July, 2013, 16:16

    Can we have the Change Project Facet step automated though pom file or maven command directly?

  • Dilan 5 August, 2013, 0:49

    Can you please explain how to add the libraries wanted and required jars for this application.

    • Dilan 5 August, 2013, 0:51

      I meant that spring and hibernate jars.

  • Shiva 11 November, 2013, 20:03

    I deployed the project in Tomcat 6.0 and getting below error

    Throwable occurred: java.lang.ClassNotFoundException: net.viralpatel.maven.HelloWorldServlet

    I found that class file is getting created in target folder, but seems server is trying to locate in WEB-INF/classes folder. Any suggestions if am missing out something.

  • nagarjun 3 December, 2013, 13:48

    Hi i am trying to download the m2eclipse . i logged in sonatype but it shows a message

    “You do not have access to this page. Please contact the account owner of this Zendesk for further help.”

    why i am getting this message..

  • Raju 25 June, 2014, 2:16

    Thank you!!!!!!!

  • rajeev 13 July, 2014, 10:16

    What you have used vesions are quite old……….but still it is helpfull.If you will upgrade the versions like working with eclipse kepler is different then this bcoz plugin is already there , and some of the different things we have to do..

  • java developer 14 July, 2014, 13:58

    This was very helpful.thank you.

  • Viral 2 August, 2014, 18:11

    I feel the article is quite incomplete, however helpful till some extent for theoretic knowledge.

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *