2
votes

I have found that there are a number of Java libraries for doing web services (either XML-RPC or SOAP) that seem to integrate well with EJB. IE: the container that handles the dynamic code generation needed to handle a web services servlet is somewhat auto setup by the servlet/e container.

Now I am wondering if anybody knows of a Java library to do the same with just plain old Jetty and Guice. I really want to find a good library that requires minimal scaffolding to work well in a plain old servlet container (possibly with guice).

2

2 Answers

5
votes

You can use jetty plus guice plus jersey as your platform.

To do that you have to create a class Bootstrap with main method. In main method configure jetty

Server server = new Server(port);
Context root = new Context(server, "/", Context.SESSIONS);
root.addEventListener(new GuiceServletConfig());
root.addFilter(GuiceFilter.class, "/*", 0);

GuiceConfiguration is responsible for jersey configuration

public class GuiceConfiguration extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule() {
            @Override
            protected void configureServlets() {
                install(new RestServicesModule());    


                bind(MessageBodyReader.class).to(JacksonJsonProvider.class);
                bind(MessageBodyWriter.class).to(JacksonJsonProvider.class);

                serve("*").with(GuiceContainer.class, ImmutableMap.of("com.sun.jersey.config.feature.Trace",
                                "true"));
            }
        });
    }
}

Next you have to create your rest services and bind them in RestServicesModule.

For example you can create HelloWorld service:

@Path("/hello")
public class HelloWorld {

    @GET
    @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    @Path("{name}")
    public Person showPerson(@PathParam("name") String name) {
        return new Person(name);
    }

}

And a person is a simple POJO.

@XmlRootElement
public static class Person {
    private String name;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The last step is to register the service in RestServicesModule

class RestServicesModule extends AbstractModule {
    protected void configure() {
       bind(HelloWorld.class);
    }
}
2
votes

Apache CXF might be what you are looking for. It can run in a standard web container, and allows you to create both SOAP style and REST services.