Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Publish REST service with Java SE

Tags:

java

rest

I am trying to find a simple way to publish my RESTful web service using JAX-RS 2.0 with Java SE using Jersey and/or the Java SE build-in http server.

I want to keep my dependencies to the minimum so i wanted to avoid grizzly and also do not want to use any external application server.

Can you point me how to publish a rest service with this requirements?

Thanks in advance,

I mean to achieve somethig like this:

public static void main(String args[]) {
    try {
        final HttpServer server = GrizzlyHttpServerFactory.createHttpServer("http://localhost:8080/calculator/",new ResourceConfig(SumEndpoint.class));

        System.in.read();
        server.stop();

} catch (IOException ex) {
}

}

... but avoiding the grizzly dependency

like image 313
Rafael Avatar asked Aug 19 '13 13:08

Rafael


People also ask

How do I publish a RESTful web service?

To create a REST Web service, right-click on the view you want to publish, in the Server Explorer and click REST Web service on the menu New > Data service or click REST Web service in the menu File > New > Data service.

Is the Java API for RESTful Web services?

Full Stack Java developer - Java + JSP + Restful WS + SpringJAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013.

How do you consume a REST webservice in Java?

A REST Service in Java EE can be created using JAX-RS. The contents of such service can be consumed using ordinary HTTP requests to a URL. URLs are typically kept simple and have a logical pattern, so it's easy to type them manually in e.g. a browser.


1 Answers

If you just depend on

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-jdk-http</artifactId>
    <version>2.2</version>
</dependency>

you can then start the server

JdkHttpServerFactory.createHttpServer(URI.create("http://localhost:8090/root"),
        new MyApplication());

where MyApplication extends ResourceConfig to obtain resource scanning.

@ApplicationPath("/")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        packages("...");
    }
    @GET
    @Produces("text/plain")
    public Response foo() {

        return Response.ok("Hey, it's working!\n").build();
    }
}

There may a better way to control the server life cycle, but that eludes me for the moment.

like image 174
forty-two Avatar answered Sep 27 '22 22:09

forty-two