Deploying and testing the web application with Maven/m2eclipse
It is time to test our web application! We want to see if Maven can build our project and create a WAR file from it and we want to see if our WAR file will run in Tomcat.
Creating a JSP
First, we need a JSP file to generate some output.
- Create a file called index.jsp directly under the webapp folder.
- Copy the following code into index.jsp.
<%@ page import="java.util.Calendar" %> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <% Calendar cal = Calendar.getInstance();%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello, the time is <%= cal.getTime() %> </h1> </body> </html>
Configuring and running the Maven build with m2eclipse
Next, we need Maven to build the web application archive (WAR) for us. This m2eclipse plugin can do this for us. Its functionality is a bit hidden and you need to do some fidling around to get ot to work nicely (its an Eclipse plugin after all), so let me show you how to do this.
- In Eclipse go to Run configurations...
- In the Run Configurations window, create a new Maven
In the Name field, provide a name. "Clean package" for example.
In the Base directory field, fill out the base directory of your project. The "Browse Workspace.." button can help you here.
In the Goals field fill out 'clean package'
- Click Apply and Run to run the build.
- You can repeat these steps to create a clean install configuration as well. (If you are unfamiliar with the Maven lifecycle, look here)
Eclipse will remember the last run configurations you ran, so your Clean package configuration is now accessible in the run configurations menu (see the first image on this page for an example).
Deploying to Tomcat
If your build succeeded Maven should have now created a target folder inside your project's base directory. The target folder should contain a war file.
The last thing you should do, is deploy the war file to Tomcat.
- Optionally rename your war file to ROOT.war and drop it in Tomcat's webapps directory.
I usually throw away all pre-installed applications from Tomcat's webapps directory (like the manager app) and just rename my own application to ROOT.war, so it is published directly under localhost:8080/ instead of under a subdirectory like localhost:8080/my-app-name.
Now test it!
- Visit localhost:8080 with your browser
If you see the test page: congratulations, you built yourself a web application and used Maven to package it into a war file.
Next up is Spring MVC! Finally! We are going to do a lot of configurations on the next page, so grab yourself another coffee and hang in there.