How to create a Web Application Project with Maven
In this tutorial, we will show you how to use Maven to create a Java web application (with Spring MVC) project, and make it support Eclipse IDE.
Tools used :
- Maven 3.0.5
- Eclipse 4.2
- JDK 6
- Spring 3.2.0.RELEASED
- Tomcat 7
1. Web Application Project from Maven Template
In a terminal (*uix or Mac) or command prompt (Windows), navigate to the folder you want to store the project. Issue following 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.
For example,
$ pwd /Users/mkyong/Documents/workspace $ mvn archetype:generate -DgroupId=com.mkyong -DartifactId=CounterWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building Maven Stub Project (No POM) 1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] Generating project in Batch mode [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: groupId, Value: com.mkyong [INFO] Parameter: packageName, Value: com.mkyong [INFO] Parameter: package, Value: com.mkyong [INFO] Parameter: artifactId, Value: CounterWebApp [INFO] Parameter: basedir, Value: /Users/mkyong/Documents/workspace [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: /Users/mkyong/Documents/workspace/CounterWebApp [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.147s [INFO] Finished at: Thu Dec 20 20:35:19 MYT 2012 [INFO] Final Memory: 12M/128M [INFO] ------------------------------------------------------------------------
In above case, a new web application project named “CounterWebApp“, and the entire project directory structure is created automatically.
2. Maven Directory Layout
Maven created following web application directory layout. A standard deployment descriptor web.xml and Maven pom.xml are created.
CounterWebApp |-src |---main |-----resources |-----webapp |-------index.jsp |-------WEB-INF |---------web.xml |-pom.xml
Please check this official guide to understand more.
<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.mkyong</groupId> <artifactId>CounterWebApp</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>CounterWebApp 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>CounterWebApp</finalName> </build> </project>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app>
<html> <body> <h2>Hello World!</h2> </body> </html>
3. Eclipse IDE Support
To convert the Maven web project to support Eclipse IDE, in terminal, navigate to “CounterWebAPp” folder, issue this command :
mvn eclipse:eclipse -Dwtpversion=2.0
You must add the -Dwtpversion=2.0 argument to make it as a Eclipse web project. Imports it into Eclipse IDE, a globe icon on top of project, means this is a web project in Eclipse.

Many users are confused, again, if you just issue
mvn eclipse:eclipse, it will only convert the project as Eclipse Java project, add extra -Dwtpversion=2.0 argument to make it as Eclipse web project.Done. This web project is ready to deploy. Attached to Eclipse’s Tomcat server plugin, and start it.

You can access the hello world jsp via – http://localhost:8080/CounterWebApp/
4. Update POM
To make above Maven web project to support Spring MVC framework, we need to touch up on the existing pom.xml :
- Add compiler plugin to specify JDK6 to compile this project (default is using JDK1.4).
- Add Spring frameworks dependencies.
- Update jUnit to latest 4.11.
<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.mkyong</groupId> <artifactId>CounterWebApp</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>CounterWebApp Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>3.0.5.RELEASE</spring.version> <junit.version>4.11</junit.version> <jdk.version>1.6</jdk.version> </properties> <dependencies> <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>CounterWebApp</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.0</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> </project>
5. Spring MVC REST
Create a Spring MVC controller class, with two simple methods to print a message.
package com.mkyong.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/") public class BaseController { @RequestMapping(value="/welcome", method = RequestMethod.GET) public String welcome(ModelMap model) { model.addAttribute("message", "Maven Web Project + Spring 3 MVC - welcome()"); //Spring uses InternalResourceViewResolver and return back index.jsp return "index"; } @RequestMapping(value="/welcome/{name}", method = RequestMethod.GET) public String welcomeName(@PathVariable String name, ModelMap model) { model.addAttribute("message", "Maven Web Project + Spring 3 MVC - " + name); return "index"; } }
Create a Spring configuration file, defines the Spring view resolver.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.mkyong.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
Update existing web.xml to support Servlet 2.5 (the default Servlet 2.3 is too old), and also integrates Spring framework into this web application project via Spring’s listener ContextLoaderListener.
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Counter Web Application</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app>
Move existing index.jsp inside folder WEB-INF, to protect user access it directly. In additional, edit the file to print out the ${message} variable that pass by the controller.
<html> <body> <h2>Hello World!</h2> <h4>Message : ${message}</h1> </body> </html>
Review the final directory structure

6. Eclipse + Tomcat
In order to start or debug this project via Eclipse server plugin (Tomcat or other container). You need to issue following command again, in order to make all dependencies attached to the project web deployment assembly.
mvn eclipse:eclipse -Dwtpversion=2.0
Before this command, project dependencies are empty.

After this command, now project dependdencies are here!

Many developers are trapped here, and failed to perform the starting or debugging in Eclipse server plugin, all failed by showing dependencies not found error message. Right click on your project properties, make sure all dependencies are inside the web deployment assembly, otherwise issue
mvn eclipse:eclipse -Dwtpversion=2.0 again!7. Maven Packaging
Review the pom.xml again, the packaging tag defining what is the packaging format or output.
<project ...> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong</groupId> <artifactId>CounterWebApp</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version>
Package the project to deploy is easy, just issue mvn package, it compiles and package the web project into a “war” file and store in project/target folder.
For example :
$pwd /Users/mkyong/Documents/workspace/CounterWebApp Yongs-MacBook-Air:CounterWebApp mkyong$ mvn package [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building CounterWebApp Maven Webapp 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] -- omitted for readability [INFO] [INFO] --- maven-war-plugin:2.1.1:war (default-war) @ CounterWebApp --- [INFO] Packaging webapp [INFO] Assembling webapp [CounterWebApp] in [/Users/mkyong/Documents/workspace/CounterWebApp/target/CounterWebApp] [INFO] Processing war project [INFO] Copying webapp resources [/Users/mkyong/Documents/workspace/CounterWebApp/src/main/webapp] [INFO] Webapp assembled in [87 msecs] [INFO] Building war: /Users/mkyong/Documents/workspace/CounterWebApp/target/CounterWebApp.war [INFO] WEB-INF/web.xml already added, skipping [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.936s [INFO] Finished at: Thu Dec 20 22:28:53 MYT 2012 [INFO] Final Memory: 14M/206M [INFO] ------------------------------------------------------------------------
Done, just copy the project/target/CounterWebApp.war file and deploy to your container.
8. Demo
Start the web application.
http://localhost:8080/CounterWebApp/welcome

http://localhost:8080/CounterWebApp/welcome/mkyong

Download Source Code
References
- Apache Maven Project
- How To Create A Java Project With Maven
- Spring 3 REST Hello World Example
- A Simple Web Application

Everything was working until the last part of the tutorial. I tried to access http://localhost:8080/CounterWebApp/welcome/mkyong
Then i got :
HTTP Status 500 – Request processing failed; nested exception is org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public java.lang.String com.mkyong.controller.BaseController.welcomeName(java.lang.String,org.springframework.ui.ModelMap)]; nested exception is java.lang.IllegalStateException: No parameter name specified for argument of type [java.lang.String], and no parameter name information found in class file either.
Strange, i was able to access http://localhost:8080/CounterWebApp/welcome/mkyong after rebooting my laptop the next day.
Hi Can you tell me how can you access the war version name in index.jsp??
Suppose the war i create is like appName-1.1.2.war.
I want to print the version i.e. “1.1.2″ in my index.jsp.
How is that possible?
The tutorial is awesome, it saves me lots of time on troubleshooting. Thank you so much.
BTW, I encountered error of “Java compiler level does not match the version of the installed Java project facet” when I tried the step 1 for the first time. I was still able to run the project, but had a red cross on the project. The solution can be found here, http://stackoverflow.com/questions/7715260/java-compiler-level-does-not-match-the-version-of-the-installed-java-project-fac
I am using Maven 3.0.5, jdk 1.7.0_10, Eclipse Java EE Juno. But later I was not able to reproduce it.
Super useful article! Saved me hours, very nicely done MK!
Hi, are you using Java EE for this example or just Java SE ?
I have learn several just right stuff here. Definitely worth bookmarking for revisiting.
I surprise how a lot effort you put to make such a excellent informative web site.
Hi ,
Can you let me know how to import a web project in eclipse ?I am not able to do it.
Regards
Chinmay
Hello,
if you want to import other project into eclipse just Right click on your project explorer and select import –> General—->Existing Projects into workspace, in this window you need to browse for the actual path where your project has to imported
you are a cool guy MK, your tutorial really helped me getting started with Maven… all this XML is a nightmare anyway. I am looking for alternatives because all that XML visual noise drives me crazy.
Hello,
I’m a newbie for eclipse and java. my background was Delphi and VB. now I’m learning java and eclipse. it is quite interesting to build web application using maven. but what if I want to create java project using maven, what archetype should I use, while in eclipse when I choose the maven project a lot of maven archetype can we select, and what if I separate the front end project (web application) and back end project (i.e for connecting to database) what should I do then.
thank you
when i am trying to run the mvn package from eclipse i am gettin the error as mentioned below, but when i am runningfrom command prompt, its working fine can you please suggest how we can run through eclipse.
Error getting default plugin information: for project org.apache.maven.project.ProjectBuildingException: Error getting default plugin information: for project
at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:141)
at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:81)
at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:293)
at org.apache.maven.DefaultMaven.getProjectsForMavenReactor(DefaultMaven.java:241)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:109)
at org.apache.maven.embedder.MavenEmbedder.execute(MavenEmbedder.java:534)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:167)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:408)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:351)
at org.codehaus.classworlds.Launcher.main(Launcher.java:31)
Caused by: org.apache.maven.lifecycle.LifecycleExecutionException: Error getting default plugin information:
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.getDefaultPluginConfiguration(DefaultLifecycleExecutor.java:914)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.populateDefaultConfigurationForPlugin(DefaultLifecycleExecutor.java:884)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.populateDefaultConfigurationForPlugins(DefaultLifecycleExecutor.java:895)
at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:136)
… 16 more
Caused by: org.apache.maven.plugin.PluginResolutionException: Plugin could not be resolved: Missing:
———-
1) org.apache.maven.plugins:maven-jar-plugin:maven-plugin:2.2
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-jar-plugin -Dversion=2.2 -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-jar-plugin -Dversion=2.2 -Dpackaging=maven-plugin -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]
———-
1 required artifact is missing.
for artifact:
org.apache.maven.plugins:maven-jar-plugin:maven-plugin:2.2
from the specified remote repositories:
central (http://repo1.maven.org/maven2, releases=true, snapshots=false)
org.apache.maven.plugins:maven-jar-plugin:maven-plugin:2.2
from the specified remote repositories:
central (http://repo1.maven.org/maven2, releases=true, snapshots=false)
at org.apache.maven.plugin.DefaultPluginManager.loadPlugin(DefaultPluginManager.java:145)
at org.apache.maven.plugin.DefaultPluginManager.getMojoDescriptor(DefaultPluginManager.java:672)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.getDefaultPluginConfiguration(DefaultLifecycleExecutor.java:906)
… 19 more
Hi, I do believe this is an excellent web site. I stumbledupon it ;)
I am going to revisit yet again since I bookmarked it.
Money and freedom is the greatest way to change, may you be rich and continue to guide other people.
I know this if off topic but I’m looking into starting my own weblog and was wondering what all is needed to get setup? I’m assuming having a blog
like yours would cost a pretty penny? I’m not very internet smart so I’m not 100% positive. Any recommendations or advice would be greatly appreciated. Thanks
I’m really enjoying the theme/design of your site. Do you ever run into any internet browser compatibility issues? A couple of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Chrome. Do you have any ideas to help fix this problem?
Hi there is a little mistake in your project:
please add this line in your dispatcher xml file
otherwise controller is not being found…
Hi , when I download your source zip folder and try to deploy it displays an error in console”
I suppose in mvc-dispatcher-servlet.xml there should be this line:
can you please help me?
i’m having the same issue. how do i fix this?? thanks!
I have a maven web project and defined tomcat7 as web server in eclipse. But I couldn’t add this project to tomcat server because it is not in the available list.
How could I add a maven web project to eclipse tomcat server?
Many Thanks.
Hi MK for me .class and .project file is not created please help to resolve this problem asap
Hello sir, how can I create a Maven Java Application with Netbeans ?
For convenience, we can declare maven-eclipse-plugin in file pom.xml to avoid typing the parameter “-Dwtpversion=2.0″ when use command
mvn eclipse:eclipse.Thanks for your invaluable input :)
I tried this, when I tried to import it into Eclipse, eclipse bailed out with an internal error.
I then attempted to repeat the procedure from within eclipse, following the instructions from https://docs.sonatype.org/display/M2ECLIPSE/WTP+mini+howto, which is the offical support site for the maven plugin used in this demo.
[Also includes instructions on how to create a java source folder]
Result Eclipse did not die and I can correctly configured eclipse/maven web project.
Hi MK,
maven-archetype-webapp creates directory structure without standard src/main/java folder. In this tutorial i can’t find part where src/main/resources is renamed to src/main/java.
Thanks,
Igor
Create the folder structure manually :)
this should be done, else the target has the java file not the class files. In ‘basecontroller’ also import import org.springframework.web.bind.annotation.PathVariable;
for a new bee every thing should be same else we need to spend hours in making the project work.
thanks for your work, mkyong
thank you very much very nice and usful lesson .i bookmark this site ,i love it coz i want learn programming .. thanks alot
Hi mkyong,
I have a maven3/jpa2/tomcat7/eclipse project, which has these jpa related dependencies in its pom.xml:
After running ‘mvn eclipse:eclipse’ command, I could see hiberante-entitymanager-3.6.5.Final.jar in the project. But after running ‘mvn package’ commeand, this jar file did not go $my_project\target\my_project\WEB-INF\lib fold. When I deply the war file to tomcat, I need to manually copy/paste this jar file to tomcat to run it.
Do you know why this issue happened? Any idea is greatly appreciated.
Thank you so much.
Delete the “scope” tag, “provided” means your container will provide this jar, so it will not package into the war file.
Your way works perfect!
Thank you so much!
thanks for your posting, this is very detailed and helpful. thanks again.
Hi Mkyong, this is cool! Thanks for a very detailed (and working) solution. :-)
Hi, will you please explain the details of running in tomcat?
>In Eclipse, create a server instance, add above “primefaces” web project and start it.
i did same what you have written in the above but the directory mkyongweb-core is created but in that folder webapp->WEB-INF-> web.xml is not created.
why is not created ?
How can i resolve this problem?
Thanks,
Pradeep
Just tested the command again, and the web.xml is created successful. May be you can try the command again, or send me your command.
The command is right. But you need to remove the invisible NL char between the second and first line.
using the -DgroupId=com.store.controllers here.. was needless since it didn’t create the package although the webApp was successfully created.
I would say .. that the project folder structure was partially created ..
well but at least I am happy that I am learning maven no matter if in parts.. haha..
But thanks .. mkyong!!! you are the best when it comes to practising technologies.
Agreed with you, Maven should generate the packaging folder as well.
Hi Mkyong
can you please tell me how can i generate package structure with web project
Hey MK you are awesome. Thanks for these tutorials they have saved me so much time!