JAX-RS Hello world example With Wildfly

Hi, we are going to start a new tutorial series where we will learn about JAX-RS. It stands for REpresentational State Transfer. In this article we will create a JAX-RS Hello World example with Wildfly.

JAX-RS Hello World Example With Wildfly:

  • Java EE 7 downloaded from Oracle.
  • Eclipse Mars
  • Wildfly 9

Adding Wildfly In Eclipse:

We are going to use the JAX-RS implementation provided by Wildfly for our JAX-RS Hello World example with wildfly. To have all required libraries in our classpath, we need to have wildfly configured in eclipse.

Open Eclipse workspace and click on Servers tab where you will see an option to add server

When the dialog box opens, select wildfly 9.x. and choose the location where it is extracted.

Creating JAX-RS Hello World example with WIldfly:

Now let us create a project in eclipse from File > New > Dynamic Web Project and name it is JAX-RS_examples. You will see the project structure as below.Now we need to add JAX-RS Compatibility to it. So Right click on JAX-RS_examples and click properties, then click Project Facets. Here you need to select jax-rs. and make sure the Runtime is selected as Wildfly 9

Now we are done with project setup for jax-rs hello world example with wildfly. Let us try to write some code for web service.

  1. Create a package called com.thejavageek.jaxrs
  2. Create a class ExampleApplication
  3. Create a class HelloWorldService.

Code for respective class is as below

ExampleApplication.java

123456789package com.thejavageek.jaxrs; import javax.ws.rs.ApplicationPath;import javax.ws.rs.core.Application; @ApplicationPath(“/rest”)public class ExampleApplication extends Application { }

Points to note

  • @ApplicationPath  annotation defines the context of web services.
  • @ApplicationPath(“/rest”)  means that all web services will have a context root as “/rest”

HelloWorldService.java

123456789101112131415package com.thejavageek.jaxrs; import javax.ws.rs.GET;import javax.ws.rs.Path; @Path(“/HelloWorld”)public class HelloWorldService {  @GET @Path(“/sayHello”) public String sayHello() { return “<h1>Hello World</h1>”; } }

points to note here

  • @Path(“HelloWorld”)  applied at class level means that the URI to invoke the methods of this class should have “/HelloWorld” as suffix.
  • @GET annotation on sayHello() method denotes that when a HTTP GET method is invoked, then sayHello()  method should be called.
  • @Path(“/sayHello”)  means that when HTTP GET method is called with “/sayHello” then sayHello()  method should be executed.

Now we are done with jax-rs hello world example with wildfly. Simply deploy the application in server and start it. After it has started successfully, hit the url http://localhost:8080/JAX-RS_examples/rest/HelloWorld/sayHelloand you should be able to see below page.

I hope this article helped to create a jax-rs hello world example with wildfly