Monday, 9 March 2015

Creating Web Services and a Rest Server with JAX-RS and Jetty

Creating a WebService in Java is remarkably easy. To add it to a ServletContainer and deploy it to an embedded WebServer is only a few more lines of code. 

Let's create a simple calculator with a couple of functions as an example of a WebService. The calculator will compute the squareRoot and square of any number.  It will return a simple JSON response with the name of the action, the input and the output.

Before we start this is the Gradle configuration you will need:


This is the code for the Calculator:

The annotations determine the type of REST action to be applied to the method @GET, @PUT etc. The @Path annotation determines the URI of the request and the @Produces annotation determines how the response will be returned.  In our case we choose JSON, the conversion of which is all handled seamlessly.

In order to deploy our WebService we need a ServletContainer for which we will use Jersey and a WebServer into which we can drop the container for which we will use Jetty.

This is the code for the RestServer:



Once you have run the RestServer you will be able to test it with this URL.


http://localhost:8080/calculator/squareRoot?input=16


A really nice way to run queries from IntelliJ is to use the inbuilt REST Client which can be found under the tools menu.


  
When you run the REST Client you will get this Response:



It's a really easy way to test a RESTful server.

4 comments:

  1. Good article, but should it be JAX-RS instead of JAX-RX?
    Im just comment, because I ended up here looking for a rest server api with Observables, and because your title mentions JAX-RX, google brought me to your article.

    ReplyDelete
    Replies
    1. I know it's been a bit of a delay :) but you are correct.

      Delete
  2. thank you for your help,
    i can connect to licalhost:8080/... and recieve the JSOn data but
    when i try to connect to that link with websocket a gave an error: "Didn't switch protocols, expected status <101>, but got <200>"

    can u please help me to solve this. it is about 1 week that i couldn't solve that

    ReplyDelete
  3. How can I implement SSL for this server. Actually I am trying to implement REST Service server over HTTPS.

    ReplyDelete