Running a Spring web application
In this recipe, we will use the Spring web application from the previous recipe. We will compile it with Maven and run it with Tomcat.
How to do it…
Here are the steps to compile and run a Spring web application:
- In
pom.xml
, add this boilerplate code under theproject
XML node. It will allow Maven to generate.war
files without requiring aweb.xml
file:<build> <finalName>springwebapp</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.5</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build>
- In Eclipse, in the left-hand side pane Package Explorer, select the
springwebapp
project folder. In the Run menu, select Run and choose Maven install or you can executemvn clean install
in a terminal at the root of the project folder. In both cases, atarget
folder will be generated with thespringwebapp.war
file in it. - Copy the
target/springwebapp.war
file to Tomcat'swebapps
folder. - Launch Tomcat.
- In a web browser, go to
http://localhost:8080/springwebapp/hi
to check whether it's working.
How it works…
In pom.xml
the boilerplate code prevents Maven from throwing an error because there's no web.xml
file. A web.xml
file was required in Java web applications; however, since Servlet specification 3.0 (implemented in Tomcat 7 and higher versions), it's not required anymore.
There's more…
On Mac OS and Linux, you can create a symbolic link in Tomcat's webapps
folder pointing to the .war
file in your project folder. For example:
ln -s ~/eclipse_workspace/spring_webapp/target/springwebapp.war ~/bin/apache-tomcat/webapps/springwebapp.war
So, when the.war
file is updated in your project folder, Tomcat will detect that it has been modified and will reload the application automatically.