Java EE application

Let's create a simple Java EE application with a REST resource, which uses the GET method to serve the Hello world! message:

package org.packt.swarm;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

//1
@Path("/")

public class HelloWorldResource {

//2
@GET
//3
@Path("hello")

@Produces({ "text/plain" })
public String hello() {
return "Hello World!";
}

}

In the listing above, we create a simple resource taking advantage of JAX-RS annotations; we define the main path for the whole class (1) and create the "hello" method, which is annotated with GET(2) and Path(3) annotations so that the "hello" method is executed when the HTML get method is invoked on a "/hello" path.

Furthermore, we have to define the application on the Path (1) root to bootstrap the web application:

package org.packt.swarm;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

//1
@ApplicationPath("/")
public class HelloWorldApplication extends Application {
}

Finally, we have to configure pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<!-- 1 -->
<groupId>org.packt.swarm</groupId>
<artifactId>swarm-hello-world</artifactId>
<version>1.0</version>
<packaging>war
</packaging>

(...)

<!-- 2 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-7.0</artifactId>
<version>${version.jboss.spec.javaee.7.0}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<!-- 3 -->
<dependencies>
<dependency>
<groupId>org.jboss.spec.javax.ws.rs</groupId>
<artifactId>jboss-jaxrs-api_2.0_spec</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<!-- 4 -->
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>

</project>

We are creating the application with the war type (1) so that it can be used as a web application. We are referencing the Java EE (2) and jaxrs API (3) so that we are able to use annotations mentioned in the preceding paragraph. Finally, we have to tweak the war plugin to inform it that we will not use the web.xml file.

That's it. This is the simple REST HelloWorld resource. We will now be able to build it and deploy it on a Java EE application server.