Skip to content

Instantly share code, notes, and snippets.

@sarnobat
Last active September 20, 2017 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sarnobat/62999927ce2d29562975131c549b12b8 to your computer and use it in GitHub Desktop.
Save sarnobat/62999927ce2d29562975131c549b12b8 to your computer and use it in GitHub Desktop.
Jersey Hello World Servlet Resource
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.json.JSONException;
import org.json.JSONObject;
import com.sun.net.httpserver.HttpServer;
/**
* After launching this program, go to the following URL in your browser:
*
* http://localhost:9099/helloworld/json
*/
public class Server {
public static void main(String[] args) throws URISyntaxException {
HttpServer server = JdkHttpServerFactory.createHttpServer(
new URI("http://localhost:9099/"), new ResourceConfig(HelloWorldResource.class));
}
@Path("helloworld")
public static class HelloWorldResource { // Must be public
@GET
@Path("json")
@Produces("application/json")
public Response json(
@QueryParam("key") Integer iValue)
throws JSONException {
JSONObject json = new JSONObject();
json.put("foo", iValue);
return Response.ok().header("Access-Control-Allow-Origin", "*")
.entity(json.toString()).type("application/json").build();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment