Coding a simple REST Service with Vert-x
We will now run a bit more advanced example which will leverage a REST Service. This service, exposes a @GET Resource which will print out the parameter passed on the PATH URL of your Web application:
package org.demo.vertx;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
[@Path](https://my.oschina.net/u/149240)``(``"/"``)
public class HelloWorldService {
[@GET](https://my.oschina.net/get)
[@Path](https://my.oschina.net/u/149240)``(``"/{name:.*}"``)
public Response doGet(``@PathParam``(``"name"``) String name) {
if (name == null || name.isEmpty()) {
name = "World"``;
}
return Response.status(``200``).entity(``"Hello " + name).build();
}
}
Some changes will be required in your Verticle as well to build the JAX-RS controller deployment, adding to the JAX-RS registry the HelloWorldService:
package org.demo.vertx;
import io.vertx.core.AbstractVerticle;
import org.jboss.resteasy.plugins.server.vertx.VertxRequestHandler;
import org.jboss.resteasy.plugins.server.vertx.VertxResteasyDeployment;
public class DemoV extends AbstractVerticle {
@Override
public void start() throws Exception {
VertxResteasyDeployment deployment = new VertxResteasyDeployment();
deployment.start();
deployment.getRegistry().addPerInstanceResource(HelloWorldService.``class``);
// Start the front end server using the Jax-RS controller
vertx.createHttpServer()
.requestHandler(``new VertxRequestHandler(vertx, deployment))
.listen(``8080``, ar -> {
System.out.println(``"Server started on port "``+ ar.result().actualPort());
});
}
}
In order to be able to build it, you need to include resteasy vert-x dependency:
1
2
3
4
5
<``dependency``>
<``groupId``>org.jboss.resteasy</``groupId``>
<``artifactId``>resteasy-vertx</``artifactId``>
<``version``>3.1.0.Final</``version``>
</``dependency``>
Let's test it!
1
2
$ curl http:``//localhost``:8080``/Frank
Hello Frank


