Deploying Maven Projects to Tomcat

Reading Time: 2 minutes

In this tutorial I will show you how to easily deploy your project on your favorite. We have a few of code and file changes thats all. First of all lets start out with the pom file. We need maven tomcat plugin to deploy our war file, copy and paste the below code between build tags in your pom.xml file and edit it the way you want

<plugins>  
    <!-- this maven plugin directly does deploy the project to tomcat7 -->
    <!-- also check out tomcat users and maven settings for the equality of credentials -->
    <!-- if credentials do not match maven will fail to deploy the project to AS -->
          <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.1</version>
              <configuration>
                  <url>http://localhost:8080/manager/text</url>
                  <!-- Refer to the server settings in your ~/.m2/settings.xml -->
                  <server>dev-tomcat</server>
                  <path>/PROJECTNAME</path>
              </configuration>
          </plugin>
            <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>

We now need to alter our tomcat-users.xml file which is located under conf folder in your main tomcat file. Add the line below in your tomcat-users.xml file

<tomcat-users>
 <role rolename="manager-gui"/>
 <role rolename="manager-script"/>
 <role rolename="manager-jmx"/>
 <role rolename="manager-status"/>
 <role rolename="admin-gui"/>
 <role rolename="admin-script"/>

 <user username="tomcat" password="password"  roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script"/>
</tomcat-users>

And now one more file left to be altered, settings.xml file once again located in conf folder in your main maven folder. Add this line between servers tag

<server>
   <id>dev-tomcat</id>
   <username>tomcat</username>
   <password>password</password>
  </server>

We are all setup right now. To give you the advice if you are working on STS or Eclipse you will need to add m2e plugin from eclipse market to run the desired project with the goal

mvn clean tomcat7:deploy

If you redeploy it please do not forget to change the goal. If your favorite IDE is IntelliJ then it is still easy. Expand Maven Projects side on the right(If you cant find it navigate to View > Tool Buttons) and go to Plugins expand tomcat7 and click on tomcat7:deploy

After these settings navigate to your serverpath/projectname to see all works.