http://www.mkyong.com/maven/how-to-create-a-web-application-project-with-maven/

不念不忘少年蓝@ 2022-08-13 12:39 250阅读 0赞



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 :

  1. Maven 3.0.5
  2. Eclipse 4.2
  3. JDK 6
  4. Spring 3.2.0.RELEASED
  5. 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 :

  1. 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,

  1. $ pwd
  2. /Users/mkyong/Documents/workspace
  3. $ mvn archetype:generate -DgroupId=com.mkyong -DartifactId=CounterWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
  4. [INFO] Scanning for projects...
  5. [INFO]
  6. [INFO] ------------------------------------------------------------------------
  7. [INFO] Building Maven Stub Project (No POM) 1
  8. [INFO] ------------------------------------------------------------------------
  9. [INFO]
  10. [INFO] Generating project in Batch mode
  11. [INFO] ----------------------------------------------------------------------------
  12. [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
  13. [INFO] ----------------------------------------------------------------------------
  14. [INFO] Parameter: groupId, Value: com.mkyong
  15. [INFO] Parameter: packageName, Value: com.mkyong
  16. [INFO] Parameter: package, Value: com.mkyong
  17. [INFO] Parameter: artifactId, Value: CounterWebApp
  18. [INFO] Parameter: basedir, Value: /Users/mkyong/Documents/workspace
  19. [INFO] Parameter: version, Value: 1.0-SNAPSHOT
  20. [INFO] project created from Old (1.x) Archetype in dir: /Users/mkyong/Documents/workspace/CounterWebApp
  21. [INFO] ------------------------------------------------------------------------
  22. [INFO] BUILD SUCCESS
  23. [INFO] ------------------------------------------------------------------------
  24. [INFO] Total time: 3.147s
  25. [INFO] Finished at: Thu Dec 20 20:35:19 MYT 2012
  26. [INFO] Final Memory: 12M/128M
  27. [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 descriptorweb.xml and Maven pom.xml are created.

  1. CounterWebApp
  2. |-src
  3. |---main
  4. |-----resources
  5. |-----webapp
  6. |-------index.jsp
  7. |-------WEB-INF
  8. |---------web.xml
  9. |-pom.xml

Note
Please check this official guide to understand more.

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/maven-v4_0_0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.mkyong</groupId>
  7. <artifactId>CounterWebApp</artifactId>
  8. <packaging>war</packaging>
  9. <version>1.0-SNAPSHOT</version>
  10. <name>CounterWebApp Maven Webapp</name>
  11. <url>http://maven.apache.org</url>
  12. <dependencies>
  13. <dependency>
  14. <groupId>junit</groupId>
  15. <artifactId>junit</artifactId>
  16. <version>3.8.1</version>
  17. <scope>test</scope>
  18. </dependency>
  19. </dependencies>
  20. <build>
  21. <finalName>CounterWebApp</finalName>
  22. </build>
  23. </project>

web.xml – Servlet 2.3 is too old, consider upgrade to 2.5

  1. <!DOCTYPE web-app PUBLIC
  2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4. <web-app>
  5. <display-name>Archetype Created Web Application</display-name>
  6. </web-app>

index.jsp – A simple hello world html file

  1. <html>
  2. <body>
  3. <h2>Hello World!</h2>
  4. </body>
  5. </html>

3. Eclipse IDE Support

To convert the Maven web project to support Eclipse IDE, in terminal, navigate to “CounterWebAPp” folder, issue this command :

  1. 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.

project structure

You want Eclipse web project NOT Eclipse Java project.
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.

tomcat in eclipse

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 existingpom.xml :

  1. Add compiler plugin to specify JDK6 to compile this project (default is using JDK1.4).
  2. Add Spring frameworks dependencies.
  3. Update jUnit to latest 4.11.

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4. http://maven.apache.org/maven-v4_0_0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.mkyong</groupId>
  7. <artifactId>CounterWebApp</artifactId>
  8. <packaging>war</packaging>
  9. <version>1.0-SNAPSHOT</version>
  10. <name>CounterWebApp Maven Webapp</name>
  11. <url>http://maven.apache.org</url>
  12. <properties>
  13. <spring.version>3.0.5.RELEASE</spring.version>
  14. <junit.version>4.11</junit.version>
  15. <jdk.version>1.6</jdk.version>
  16. </properties>
  17. <dependencies>
  18. <!-- Spring 3 dependencies -->
  19. <dependency>
  20. <groupId>org.springframework</groupId>
  21. <artifactId>spring-core</artifactId>
  22. <version>${spring.version}</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-web</artifactId>
  27. <version>${spring.version}</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-webmvc</artifactId>
  32. <version>${spring.version}</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>junit</groupId>
  36. <artifactId>junit</artifactId>
  37. <version>${junit.version}</version>
  38. <scope>test</scope>
  39. </dependency>
  40. </dependencies>
  41. <build>
  42. <finalName>CounterWebApp</finalName>
  43. <plugins>
  44. <plugin>
  45. <groupId>org.apache.maven.plugins</groupId>
  46. <artifactId>maven-compiler-plugin</artifactId>
  47. <version>3.0</version>
  48. <configuration>
  49. <source>${jdk.version}</source>
  50. <target>${jdk.version}</target>
  51. </configuration>
  52. </plugin>
  53. </plugins>
  54. </build>
  55. </project>

5. Spring MVC REST

Create a Spring MVC controller class, with two simple methods to print a message.

/src/main/java/com/mkyong/controller/BaseController.java

  1. package com.mkyong.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.ModelMap;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestMethod;
  6. @Controller
  7. @RequestMapping("/")
  8. public class BaseController {
  9. @RequestMapping(value="/welcome", method = RequestMethod.GET)
  10. public String welcome(ModelMap model) {
  11. model.addAttribute("message", "Maven Web Project + Spring 3 MVC - welcome()");
  12. //Spring uses InternalResourceViewResolver and return back index.jsp
  13. return "index";
  14. }
  15. @RequestMapping(value="/welcome/{name}", method = RequestMethod.GET)
  16. public String welcomeName(@PathVariable String name, ModelMap model) {
  17. model.addAttribute("message", "Maven Web Project + Spring 3 MVC - " + name);
  18. return "index";
  19. }
  20. }

Create a Spring configuration file, defines the Spring view resolver.

/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:context="http://www.springframework.org/schema/context"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  9. <context:component-scan base-package="com.mkyong.controller" />
  10. <bean
  11. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  12. <property name="prefix">
  13. <value>/WEB-INF/pages/</value>
  14. </property>
  15. <property name="suffix">
  16. <value>.jsp</value>
  17. </property>
  18. </bean>
  19. </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 listenerContextLoaderListener.

/src/main/webapp/WEB-INF/web.xml

  1. <web-app xmlns="http://java.sun.com/xml/ns/javaee"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  4. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. version="2.5">
  6. <display-name>Counter Web Application</display-name>
  7. <servlet>
  8. <servlet-name>mvc-dispatcher</servlet-name>
  9. <servlet-class>
  10. org.springframework.web.servlet.DispatcherServlet
  11. </servlet-class>
  12. <load-on-startup>1</load-on-startup>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>mvc-dispatcher</servlet-name>
  16. <url-pattern>/</url-pattern>
  17. </servlet-mapping>
  18. <context-param>
  19. <param-name>contextConfigLocation</param-name>
  20. <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
  21. </context-param>
  22. <listener>
  23. <listener-class>
  24. org.springframework.web.context.ContextLoaderListener
  25. </listener-class>
  26. </listener>
  27. </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.

/src/main/webapp/WEB-INF/pages/index.jsp

  1. <html>
  2. <body>
  3. <h2>Hello World!</h2>
  4. <h4>Message : ${message}</h1>
  5. </body>
  6. </html>

Review the final directory structure

final project 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.

  1. mvn eclipse:eclipse -Dwtpversion=2.0

Before this command, project dependencies are empty.

web deployment assembly

After this command, now project dependdencies are here!

web deployment assembly

Important!
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.

pom.xml

  1. <project ...>
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>com.mkyong</groupId>
  4. <artifactId>CounterWebApp</artifactId>
  5. <packaging>war</packaging>
  6. <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 inproject/target folder.

For example :

  1. $pwd
  2. /Users/mkyong/Documents/workspace/CounterWebApp
  3. Yongs-MacBook-Air:CounterWebApp mkyong$ mvn package
  4. [INFO] Scanning for projects...
  5. [INFO]
  6. [INFO] ------------------------------------------------------------------------
  7. [INFO] Building CounterWebApp Maven Webapp 1.0-SNAPSHOT
  8. [INFO] ------------------------------------------------------------------------
  9. [INFO] -- omitted for readability
  10. [INFO]
  11. [INFO] --- maven-war-plugin:2.1.1:war (default-war) @ CounterWebApp ---
  12. [INFO] Packaging webapp
  13. [INFO] Assembling webapp [CounterWebApp] in [/Users/mkyong/Documents/workspace/CounterWebApp/target/CounterWebApp]
  14. [INFO] Processing war project
  15. [INFO] Copying webapp resources [/Users/mkyong/Documents/workspace/CounterWebApp/src/main/webapp]
  16. [INFO] Webapp assembled in [87 msecs]
  17. [INFO] Building war: /Users/mkyong/Documents/workspace/CounterWebApp/target/CounterWebApp.war
  18. [INFO] WEB-INF/web.xml already added, skipping
  19. [INFO] ------------------------------------------------------------------------
  20. [INFO] BUILD SUCCESS
  21. [INFO] ------------------------------------------------------------------------
  22. [INFO] Total time: 3.936s
  23. [INFO] Finished at: Thu Dec 20 22:28:53 MYT 2012
  24. [INFO] Final Memory: 14M/206M
  25. [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

demo1

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

demo2

Download Source Code

Download it – CounterWebApp.zip (13 KB)

References

  1. Apache Maven Project
  2. How To Create A Java Project With Maven
  3. Spring 3 REST Hello World Example
  4. A Simple Web Application

发表评论

表情:
评论列表 (有 0 条评论,250人围观)

还没有评论,来说两句吧...

相关阅读