好了,之前讲过了一个简单的Console App如何使用Maven进行管理,相信有了这些基础知识我们今天的课程更好理解。
1. 创建工程
大多数情况下我们的工程类型都是Java Web的,所以这里我们创建工程的时候略作修改:
mvn archetype:create -DgroupId=com.freesoft.mvn-webapp -DartifactId=mvnwebapp -DarchetypeArtifactId=maven-archetype-webapp
注意替换-DgroupId和-DartifactId为你自己的project Id。
工程创建后将其导入MyEclipse的Workspace。
2. 配置Tomcat
我们的J2EE容器使用Tomcat,为了Maven能够和Tomcat协同工作,我们这里需要配置Tomcat:
tomcat-users.xml文件的tomcat-users小节添加角色和用户:
<role rolename="manager" />
<role rolename="manager-gui" />
<role rolename="manager-script" />
<role rolename="manager-jmx" />
<role rolename="manager-status" />
<role rolename="admin" />
<role rolename="admin-gui" />
<user username="tomcat" password="123456" roles="admin-gui,admin,manager-gui,manager,manager-script,manager-jmx,manager-status" /
3. 配置Maven与Tomcat连接
下面还需要对Maven进行配置,确保其能够连接到Tomcat。
我们首先看看MyEclipse的Preferencec->Maven4MyEclipse中的User Settings有没有配置。如果你配置过那么就修改这个文件即可,否则找到Installations里面对应的配置文件,修改:
<servers>
<server>
<id>tomcat_localtest</id>
<username>tomcat</username>
<password>123456</password>
</server>
</servers>
注意这里的username和password需要和之前tomcat中配置的一致。
4. 修改仓库配置
这里同样是修改settings.xml文件的settings段中内容,修改profiles段:
<profiles>
<profile>
<id>dev_profile</id>
<!-- remote repository configuration -->
<repositories>
<repository>
<id>apache.releases</id>
<url>https://repository.apache.org/content/repositories/releases</url>
<!-- ONLY use release repository -->
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<!-- just same as repository -->
<pluginRepositories>
<pluginRepository>
<id>apache.releases</id>
<name>Apache Releases</name>
<url>https://repository.apache.org/content/repositories/releases</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>dev_profile</activeProfile>
</activeProfiles>
本来这里的repositories和pluginRepositories段都可以放到工程中,但考虑到我们这里使用的是公共仓库而不是私有仓库,我将其放到了settings.xml中。
对于项目相关的私有仓库应该放置到项目的pom.xml文件中。
5. 修改工程配置
现在本地的全局配置做完,开始对工程进行设置。修改pom.xml文件的build段:
<build>
<finalName>mvnwebapp</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<tomcat-url>http://localhost:8080/manager/html</tomcat-url>
<server>tomcat_localtest</server>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
6. 运行、测试
新建一个Debug/Run Configuration,目录选择工程目录,Goals选择“tomcat7:redeploy”,开始Run/Debug,即可部署开始测试。