Built-in jetty with json / xml response

I have a built-in berth server. I want to create a RESTful GET service that returns an XML / JSON response as a response. can someone give me one basic example how to write a handler for a berth? in the example shown, only text type output is shown.

+4
source share
4 answers

I suggest you use the java java framework for java (http://jersey.java.net/). The structure is easy to learn. You can use an Object to Xml converter such as JAXB to make your life easier.

+1
source

Hm. I have the same problem. I solved this by having a jar utility file that reads the properties file for setting contexts for jersey servlets, handlers, static files, exploded web applications, etc. Thus, the resulting application applicator automatically sets contexts and is launched from the command line.

I basically have a HandlerCollection and sequentially add servlets to it.

ServletHolder servletHolder = new ServletHolder(ServletContainer.class); servletHolder.setInitParameter( "com.sun.jersey.config.property.packages", clazz.getPackage().getName() ); ServletContextHandler context = new ServletContextHandler( server, "/some_path", ServletContextHandler.SESSIONS ); context.setClassLoader(Thread.currentThread().getContextClassLoader()); context.addServlet(servletHolder, "/"); context.setHandler(handler); handlers.addHandler(context); 

Then I have an example of a Jersey servlet:

 @Path("/user1") public class JerseyResource1 { public JerseyResource1() { } @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public ExamplePojo getUser() { log.debug("Inside ExampleJerseyResource1 getUser()"); ExamplePojo pojo = new ExamplePojo(); pojo.setNumber(100); pojo.setWords("hello world 1"); return pojo; } 

}

The first bells get a perfect hit as Jersey tunes the material, but it works just peachy.

The junit test is as follows:

 @BeforeClass public static void setUpClass() throws Exception { Thread startupThread = new Thread() { @Override public void run() { try { System.out.println("Starting Jetty..."); JettyMain.main(new String[] {}); // CHECKSTYLE_OFF: Because it does throw Exception! } catch (Exception ex) { // CHECKSTYLE_ON System.err.println("Error Starting Jetty: " + ex); } } }; startupThread.start(); System.out.println("Waiting a few seconds to ensure Jetty is started"); Thread.sleep(2000); System.out.println("Ok. Starting tests"); } @AfterClass public static void tearDownClass() throws Exception { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); WebResource service = client.resource( UriBuilder.fromUri( "http://localhost:8080/admin/stop?secret=YourSecret" ).build()); service.get(String.class); System.out.println("Sent stop command"); } @Test public void testJersey1() { System.out.println("Jersey1 returns correct 200 and body"); ClientResponse response = getService( "http://localhost:8080/jersey1/user1/" ).get(ClientResponse.class); assertEquals("Response is 200", 200, response.getStatus()); assertEquals( "Valid body", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<examplePojo><number>100</number><words>hello world 1</words></examplePojo>", response.getEntity(String.class) ); System.out.println("--> WORKED!"); } 

CURL requests are as follows:

 # Show static public files folder: curl -v http://localhost:8080/public/x.html curl -v http://localhost:8080/public/x.txt # Use baseline handlers: curl -v http://localhost:8080/handler1/?url=hello curl -v http://localhost:8080/handler2/?url=hello # Use raw servlets with specific contexts: curl -v http://localhost:8080/servlet1?url=hello curl -v http://localhost:8080/servlet2?url=hello # Call a Jersey servlet using default Accept header (xml): curl -v http://localhost:8080/jersey1/user1/ curl -v http://localhost:8080/jersey2/user2/ # Request Jersey servlet but want JSON: curl -v --header "Accept:application/json" http://localhost:8080/jersey1/user1/ # Use an exploded webapp: curl -v http://localhost:8080/www/x.html # Stop the server: curl -v http://localhost:8080/admin/stop?secret=MySecret 

Er ... The following is not a plugin. Jokes aside. This may be denied by the company ...

I have a complete solution by which 1 jar file was added as a dependency and several tiny files (app.properties, classpath.sh, log4j.properties and run.sh) that completely configure the Jetty8 instance for many contexts, Handlers, Servlets, JerseyServlets, StaticFiles, and ExplodedWebApps. The result is a standalone executable Jar that restarts, reloads, stops, etc. With almost zero effort. An added benefit is that it can act as a pseudo-class and avoid jar-hell. (A side effect is that mvn clean test works against it too)

If someone is interested, ping me, and I see if the company will allow me OpenSource and launch it on GitHub. Or maybe even document it through my own website http://www.randomactsofsentience.com

+1
source

Just FYI on the embedded Jetty as a whole ... I created a github project that I humbly imagine can cover most of the built-in jetty problems that continue to arise. See https://github.com/ZenGirl/EmbeddedJettyRepository for more details.

+1
source

Using a framework to handle JSON serialization is the way to go. However, here is a simple example:

 public class MyServer extends AbstractHandler { private static final int PORT = 8080; @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().print("{ \"my_data\": \"Hello from Java!\" }"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); } public static void main(String[] args) throws Exception { Server server = new Server(PORT); server.setHandler(new MeServer()); server.start(); System.out.println("Jetty started: http://localhost:" + PORT + "/"); server.join(); } } 
0
source

All Articles