Java EE 5 web application with Maven

Java web application created using STS and Maven. First servlet and doGet() method. How to create a WAR (Web Application ARchive) file using Maven. How to use Tomcat integrated with Eclipse and embedded Tomcat using Maven.

Let's create a Java web application in STS aka SpringSource Tool Suite using Maven. I could do the same in plain Eclipse with Maven plugin installed, but this saves me lots of time.

Let's create a new project. New -> Other -> Maven Project. We will use archetype. Search for jee5. If you cannot find this archetype, goto Window -> Show view -> Other -> Maven repositories and rebuild index of central repository. This will take a while, so meanwhile grab a coffee.

Once the index has been rebuilt, choose artifact with Artifact ID webapp-jee5, set Group ID: com.javavids.webapp, Artifact ID: HelloWorldWeb, package the same as Group ID and press Finish.

If you do it the first time, it may take several seconds to create a project as you see it here. Maven will meanwhile download archetype and create this project structure.

It's a classic Maven project, inside src/main/java are Java classes, inside src/main/webapp are public files and WEB-INF directory with web.xml. Inside project is pom.xml file, where are dependencies.

As you can see, we already have index.jsp file with hello world message. Let's create a Servlet. Let's call it HelloServlet and map it to "/hello.html". Because I created a Java EE 5 project, there's no @WebServlet annotation, but servlet mapping is defined in web.xml.

Delete constructor and doPost() method and into doGet() method add this code:

PrintWriter out = response.getWriter();
out.println("Hello from first servlet!");

To deploy this project to server, just simply drag and drop this project to appropriate server.

Test index.jsp page and hello.html page.

To create a WAR file, right click on this project, Run As -> Maven build -> and add goal "package". This will create a standard WAR file inside target directory. If you do it the first time, Maven will download some files, so it will take a little bit longer than here.

Using Maven you can even startup your project without local server. Stop your local server and run this Maven project with goal tomcat:run. This will download Tomcat and next it will deploy this application on this embedded server. I use this for demoing purposes, but for development I use Tomcat integrated with Eclipse as I demonstrated earlier.