使用maven构建web项目实例
用maven构建web项目,首先要知道标准的目录结构,和一般的maven项目相同,源文件存放在src/main/java中,配置文件存在src/main/resources目录下。测试的代码放在src/test/java下,
对应的资源文件放在src/test/resources目录下。除了这些目录外。web项目还有一个src/main/webapp目录,该目录必须存在,且必须有一个web.xml文件,用于对整个web项目的配置。
如maven-web-demo这个项目实例。该项目的目录结构如下图所示:
[size=medium]为了web项目的部署,该项目的打包方式必须显示声明为war方式,因为maven默认的打包方式为jar。
还有pom文件中必须引入servlet,jsp的相关jar包,scope设置为provided,表示它们最终不会打包到war项目中。因为几乎所有的web容器都提供有javax.servlet相关的jar包,如果war包中重复出现
就会出现版本冲突的错误。
为了测试web项目,可以使用jetty插件,需要在pom文件中给出相应的配置。[/size
]<plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.26</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <webAppConfig> <contextPath>/test</contextPath> <!-- http://host:port/test/ --> </webAppConfig> </configuration> </plugin>
<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.juvenxu.mvnbook.account</groupId><artifactId>maven-web-demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><build><plugins><plugin><groupId>org.mortbay.jetty</groupId><artifactId>maven-jetty-plugin</artifactId><version>6.1.26</version><configuration><scanIntervalSeconds>10</scanIntervalSeconds><webAppConfig><contextPath>/test</contextPath> <!-- http://host:port/test/ --></webAppConfig></configuration></plugin></plugins></build><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.4</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jsp-api </artifactId><version>2.0</version><scope>provided</scope></dependency><dependency><groupId> org.springframework </groupId><artifactId>spring-web</artifactId><version>2.5.6</version></dependency></dependencies></project>
<plugin><groupId>org.codehaus.cargo</groupId><artifactId>cargo-maven2-plugin</artifactId><version>1.0</version><configuration><container><containerId>Tomcat6x</containerId><home>D:\software installs\Tomcat6.0</home></container><configuration><type>standalone</type><home>${project.build.directory}/Tomcat6x</home><properties><cargo.servlet.port>8080</cargo.servlet.port></properties></configuration></configuration></plugin>