Creating a simple Java web application using a Maven archetype

Maven archetypes make it easy to create a base structure for some common Java applications. In this tutorial I am going to show you how to get a simple Java web application up and running in just a few minutes.

Tools I used:

Creating the project

In STS select File > New > Other… or just press Crtl + N. In the wizard search for maven and select Maven Project.

new_project_wizard_20140904

In the next window make sure you leave Create a simple project (skip archetype selection) unchecked as we want to create the project using an archetype. Below this option you can specify if you would like the project to be in the default workspace location or somewhere else. Both is fine, just remember which directory your project is in.

Clicking next again will take you to the archetype selection window. In the filter field type webapp and from the filtered list choose the one that has maven-achetype-webapp as it’s artifact id.

As the last step, fill in the desired parameters for the archetype. If want your app to be accessible from the same URL as in the example, please use the artifact id seen on the screenshot below.

archetype_parameters_20140904

Finally click Finish to create the project. A new Maven project is created for you with all the necessary files and folders for a basic web application.

directory_structure_20140904

 

 

Running the project

To open this web application in a browser you need an application server (e.g. Tomcat). Luckily with Maven’s Tomcat plugin you don’t need to install the server manually because Maven will automatically download an instance of it for you. You can set additional configuration options in the pom.xml for the server, but for this simple example this is not necessary.

To run this project navigate to the project’s directory in the command line and issue the following command:

mvn clean install tomcat:run

This will compile the project and install it in your local Maven repository and also deploy it to the Tomcat server. The server by default starts on the 8080 port. You can access the application by typing http://localhost:8080/simple-maven-webapp/ in your browser. The last part of this URL is in this case the same as the artifact id. This is because Maven automatically generated a pom.xml for you and set the <finalName> tag to the value of the artifact id.

<build>
    <finalName>simple-maven-webapp</finalName>
</build>

project_running_in_browser_20140904

Note: There are other ways to change the url under which your application is available, but if you don’t specify anything else, the finalName will be used.

How to set up Sonar with Maven on localhost

This tutorial describes how to set up Sonar to work with Maven projects on a local development machine. Sonar is a platform for continously inspecting code quality. It is now officially called SonarQube, but a lot of people know it by the original name.

Downloading

The first step is to download Sonar form it’s offical site (http://www.sonarqube.org) and extract it to a directory of your choice. At the time of writing the latest version is: SonarQube 4.4.

Configure Sonar and Maven

For Sonar to able to collect data about the code quality of projects, it needs to have access to a database where it can store the generated data. Also, we have to define a Maven profile that will be used to run our Maven project through Sonar code analysis. For this tutorial we will be using a MySQL database.

In the Sonar installation directory open the conf/sonar.properties file and configure the following properties:

sonar.jdbc.username=root
sonar.jdbc.password=root
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar_db?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true

In the Maven installation directory open the conf/settings.xml file and add a new profile inside the <profiles> tag:

<profile>
    <id>sonar</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <sonar.jdbc.url>
          jdbc:mysql://localhost:3306/sonar_db?useUnicode=true&characterEncoding=utf8
        </sonar.jdbc.url>
        <sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver>
        <sonar.jdbc.username>root</sonar.jdbc.username>
        <sonar.jdbc.password>root</sonar.jdbc.password>
        <sonar.host.url>http://localhost:9000</sonar.host.url>
    </properties>
</profile>

Of course, in both cases you need to configure you own username and password, and the schema name that you plan on using (in this case it is sonar_db). With this configuration the Sonar web application will be accessible at the http://localhost:9000 url.

Create the database schema

When we first start Sonar, it will automatically create the required database tables, but the DB schema that it uses must already exist. So create an empty database schema with the name you configured (sonar_db).

If you forget to create the schema you can see the following exceptions in the log file (logs/sonar.log)

org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Unknown database 'sonar_db')
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'sonar_db'
ActiveRecord::ConnectionNotEstablished: no connection available
org.jruby.rack.RackInitializationException: no connection available
org.jruby.exceptions.RaiseException: (ConnectionNotEstablished) no connection available

Start the Sonar server

For Maven to access the server, we need to launch the server first. Navigate to the bin directory of your installation and select the folder according to your environment. I have a Windows 7 64bit system, so I choose the windows-x86-64 directory and start the server by running the StartSonar.bat file.

In the console, you can see the following feedback if the server is started:

wrapper  | --> Wrapper Started as Console
wrapper  | Launching a JVM...
jvm 1    | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
jvm 1    |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
jvm 1    |
jvm 1    | 2014.08.29 10:32:43 INFO  Web server is started

Try to access the web application by entering http://localhost:9000/ in your browser. You should see something similar to this if it managed to start properly:

Sonar webapp

Run the analysis

Navigate to the directory of your Maven project and issue the following command to the perform code analysis:

mvn sonar:sonar

After this completes, you can go back to the web application and view the results there.

Where Maven puts files during build

If you build a project with Maven, you can notice that it creates a target folder, and copies the resource files, the compiled source files, the test resource files and the compiled test source files into specific directories. For example the target/classes directory will contain the compiled source files and the resource files. The questions that could arise are:

  • How Maven know that it needs to create the directories with these names?
  • How does it know where to find the source files to compile?
  • How does it know where are the resource files?

They must be configured somewhere, otherwise Maven wouldn’t know what are the names of these directories. The important thing to know here is that contents of pom.xml files can be inherited. These default settings that we get are  inherited from another pom xml file called the Super POM, from which every pom gets it’s default settings.

The directories mentioned above are defined in the Super POM similar to this:

<build>
    <directory>target</directory>
    <outputDirectory>target/classes</outputDirectory>
    <finalName>${artifactId}-${version}</finalName>
    <testOutputDirectory>target/test-classes</testOutputDirectory>
    <sourceDirectory>src/main/java</sourceDirectory>
    <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
    <testSourceDirectory>src/test/java</testSourceDirectory>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
    <testResources>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>
  </build>
</sxh>

Note the directories that are created can be different if you overwrite these configuration options in your project’s pom.xml file.

Download source

You can download the source files used in this project here.

If  you build this project using the mvn clean install command, you can check out the created target folder and the directories inside it.