Creating a java server with rest

2019-04-09 08:06发布

问题:

I need to create a rest server and client.

I stumbled upon this tutorial which uses sockets. I want to be able to use REST calls, possibly HTTP, because the clients will be actually in different languages.

Instead of using Socket api from java.net.* what should i use ? if i use Socket API can I use c++ and php to communicate with this server? or should i go with REST?

any directions appreciated.

回答1:

There's a lot of things you can use to create rest services, and then they can be consumed by almost anything. Of particular awesomeness is the ability to hit them in your web browser, just because we're all so familiar with them.

When I need a 'quick and dirty' rest solution, I use Restlet - I won't claim it's the only solution, but it's the easiest I've ever worked with. I've literally said in a meeting "I could have XYZ up in 10 minutes." Someone else in the meeting called me on it, and sure enough, using Restlet I was able to get a functioning REST server running with the (very simple) features I said I would get in the meeting. It was pretty slick.

Here's a barebones server that has one method, returning the current time. Running the server and hitting 127.0.0.1:12345/sample/time will return the current time.

import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;

/**
 * This Application creates an HTTP server with a singple service
 * that tells you the current time.
 * @author corsiKa
 */
public class ServerMain extends Application {

    /**
     * The main method. If you don't know what a main method does, you 
     * probably are not advanced enough for the rest of this tutorial.
     * @param args Command line args, completely ignored.
     * @throws Exception when something goes wrong. Yes I'm being lazy here.
     */
    public static void main(String...args) throws Exception {
        // create the interface to the outside world
        final Component component = new Component();
        // tell the interface to listen to http:12345
        component.getServers().add(Protocol.HTTP, 12345);
        // create the application, giving it the component's context
        // technically, its child context, which is a protected version of its context
        ServerMain server = new ServerMain(component.getContext().createChildContext());
        // attach the application to the interface
        component.getDefaultHost().attach(server);
        // go to town
        component.start();

    }

    // just your everyday chaining constructor
    public ServerMain(Context context) {
        super(context);
    }

    /** add hooks to your services - this will get called by the component when
     * it attaches the application to the component (I think... or somewhere in there
     * it magically gets called... or something...)
     */
    public Restlet createRoot() {
        // create a router to route the incoming queries
        Router router = new Router(getContext().createChildContext());
        // attach your resource here
        router.attach("/sample/time", CurrentTimeResource.class);
        // return the router.
        return router;
    }

}

And here's the 'current time resource' that it uses:

import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

/**
 * A resource that responds to a get request and returns a StringRepresentaiton
 * of the current time in milliseconds from Epoch
 * @author corsiKa
 */
public class CurrentTimeResource extends ServerResource {

    @Get // add the get annotation so it knows this is for gets
    // method is pretty self explanatory
    public Representation getTime() {
        long now = System.currentTimeMillis(); 
        String nowstr = String.valueOf(now); 
        Representation result = new StringRepresentation(nowstr);
        return result;
    }
}


回答2:

JAX-RS is the API for REST in Java. There are a lot of implementations, but the main ones are Jersey (the reference implementation), Apache's CXF and Restlet.



回答3:

Usually, you don't create a server. You create a web application and deploy it on the server or servlet container. Some servlet containers are embedable into your web application, e.g. Jetty. Poppular free servlet containers are Tomcat, Glassfish, Jetty, etc.

For Restlet, it is not a servlet container. It is a framework that allow you to create a wep application with RESTful styles. So this should not be confused.

If you decide to use servlet container, then the problem is how you can create a web application with the RESTful styles. REST is not a technology - it is a design principle. It is a concept of how you should create the interface.

The design of REST is stateless so you do not need to store the state of the transaction. All information from a request should be sufficient to produce a respose to client.

There are several servlet framework that allows you to implment the REST styles easily. Some of them are very sophisticated, e.g. Spring framework.



回答4:

Download JBoss 7. Problem solved.

Heres a restful service:

@Path("/myservice")
public class MyService {

    @GET
    @Produces(MediaTypes.TEXT_PLAIN)
    public String echoMessage(@QueryParam("msg") String msg) {
        return "Hello " + msg;
    }
}

Create a WAR. Deploy. Open up browser and go http://myserver/myapp/myservice?msg=World. Done!



回答5:

I would say go with an HTTP based RESTful service. It's rapidly becoming a defacto standard. Check my answer to this similar question for pros and cons.



回答6:

This is the best one out there. Spring MVC which has lot of REST capabilities in itself. This takes just a single jar file to be included. And you are all set to use all it's capabilities. Even as simple as the below guy explained in JBOSS and much more flexibility as well.

http://java.dzone.com/articles/spring-30-rest-example



回答7:

I use JBoss 6 with RestEasy. I have created a tutorial located here. I hope this helps you.



回答8:

You're also welcome to see my very simple example for REST server implementation here.