2014-11-02 39 views
6

一旦我得到這個問題的最新球衣例如不起作用回答,我遇到了另一個問題感到好奇:MediaType.APPLICATION_XML和MediaType.APPLICATION_JSON在新澤西州的演示應用程序

服務器,GET方法做工精細。我測試並添加了一些helloworld-pure-jax-rs示例的測試代碼,尤其是。增加了對JSON的POST請求:

package org.glassfish.jersey.examples.helloworld.jaxrs; 

import javax.ws.rs.Consumes; 
import javax.ws.rs.GET; 
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.PathParam; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response; 


@Path("helloworld") 
public class HelloWorldResource 
{ 
    public static final String CLICHED_MESSAGE = "Hello World!"; 

    @GET 
    @Produces(MediaType.TEXT_PLAIN) 
    public String getHello() 
    { 
     return CLICHED_MESSAGE; 
    } 

    @GET 
    @Produces(MediaType.APPLICATION_JSON) 
    public String getHelloJson() 
    { 
     return "{ \"message\":" + CLICHED_MESSAGE + "}"; 
    } 

    @GET 
    @Produces(MediaType.TEXT_HTML) 
    public String getHelloHtml() 
    { 
     return "<html> " + "<title>" + "Hello Jersey" + "</title>" + "<body><h1>" + CLICHED_MESSAGE 
       + "</body></h1>" + "</html> "; 
    } 

    @GET 
    @Produces(MediaType.TEXT_PLAIN) 
    @Path("/v2") 
    public String getHello2() 
    { 
     return CLICHED_MESSAGE + " v2"; 
    } 

    @GET 
    @Produces(MediaType.TEXT_PLAIN) 
    @Path("/{id}") 
    public String getHelloId(@PathParam("id") String id) 
    { 
     return CLICHED_MESSAGE + " Parameter: " + id; 
    } 

    @GET 
    @Produces(MediaType.TEXT_PLAIN) 
    @Path("/id/{id : [a-zA-Z][a-zA-Z_0-9]}") 
    public String getHelloIdId(@PathParam("id") String id) 
    { 
     return CLICHED_MESSAGE + " Parameter: " + id; 
    } 

    @POST 
    @Consumes(MediaType.TEXT_PLAIN) 
    @Produces(MediaType.TEXT_PLAIN) 
    public Response test(String test) 
    { 
     if (test.equals("test")) 
      return Response.status(400).entity("Error: " + test).build(); 
     return Response.status(200).entity(test).build(); 
    } 

    @POST 
    @Path("/test") 
    @Consumes(MediaType.APPLICATION_JSON) 
    @Produces(MediaType.APPLICATION_JSON) 
    public Response testJSON(Test test) 
    { 
     String result = "Test JSON created : " + test.getName() + "" + test.getAge(); 
     // return result; 
     return Response.status(200).entity(result).build(); 
    } 

    @POST 
    @Path("/test") 
    @Consumes(MediaType.APPLICATION_XML) 
    @Produces(MediaType.APPLICATION_XML) 
    public Response testXML(Test test) 
    { 
     String result = "Test XML created : " + test.getName() + "" + test.getAge(); 
     // return result; 
     return Response.status(200).entity(result).build(); 
    } 

} 

這裏IST類的其餘部分:

package org.glassfish.jersey.examples.helloworld.jaxrs; 

import java.io.IOException; 
import java.net.InetSocketAddress; 
import java.net.URI; 

import javax.ws.rs.core.UriBuilder; 
import javax.ws.rs.ext.RuntimeDelegate; 

import com.sun.net.httpserver.HttpHandler; 
import com.sun.net.httpserver.HttpServer; 

/** 
* Hello world application using only the standard JAX-RS API and lightweight 
* HTTP server bundled in JDK. 
* 
* @author Martin Matula (martin.matula at oracle.com) 
*/ 
@SuppressWarnings("restriction") 
public class App 
{ 

    /** 
    * Starts the lightweight HTTP server serving the JAX-RS application. 
    * 
    * @return new instance of the lightweight HTTP server 
    * @throws IOException 
    */ 
    static HttpServer startServer() throws IOException 
    { 
     // create a new server listening at port 8080 
     HttpServer server = HttpServer.create(new InetSocketAddress(getBaseURI().getPort()), 0); 

     // create a handler wrapping the JAX-RS application 
     HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new JaxRsApplication(), 
       HttpHandler.class); 

     // map JAX-RS handler to the server root 
     server.createContext(getBaseURI().getPath(), handler); 

     // start the server 
     server.start(); 

     return server; 
    } 

    public static void main(String[] args) throws IOException 
    { 
     System.out.println("\"Hello World\" Jersey Example Application"); 

     HttpServer server = startServer(); 

     System.out.println("Application started.\n" + "Try accessing " + getBaseURI() 
       + "helloworld in the browser.\n" + "Hit enter to stop the application..."); 
     System.in.read(); 
     server.stop(0); 
    } 

    private static int getPort(int defaultPort) 
    { 
     final String port = System.getProperty("jersey.config.test.container.port"); 
     if (null != port) 
     { 
      try 
      { 
       return Integer.parseInt(port); 
      } 
      catch (NumberFormatException e) 
      { 
       System.out.println("Value of jersey.config.test.container.port property" 
         + " is not a valid positive integer [" + port + "]." 
         + " Reverting to default [" + defaultPort + "]."); 
      } 
     } 
     return defaultPort; 
    } 

    /** 
    * Gets base {@link URI}. 
    * 
    * @return base {@link URI}. 
    */ 
    public static URI getBaseURI() 
    { 
     return UriBuilder.fromUri("http://localhost/").port(getPort(8080)).build(); 
    } 
} 


public class Test 
{ 
    public int  age  = 0; 
    public String name = ""; 

    /** 
    * 
    */ 
    public Test() 
    { 
     super(); 
    } 

    /** 
    * @param age 
    */ 
    public Test(int age) 
    { 
     super(); 
     this.age = age; 
    } 

    /** 
    * @param name 
    */ 
    public Test(String name) 
    { 
     super(); 
     this.name = name; 
    } 

    /** 
    * @param name 
    * @param age 
    */ 
    public Test(String name, int age) 
    { 
     super(); 
     this.name = name; 
     this.age = age; 
    } 

    public int getAge() 
    { 
     return age; 
    } 

    public String getName() 
    { 
     return name; 
    } 

    public void setAge(int age) 
    { 
     this.age = age; 
    } 

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

package org.glassfish.jersey.examples.helloworld.jaxrs; 

import java.util.Collections; 
import java.util.HashSet; 
import java.util.Set; 
import javax.ws.rs.core.Application; 

public class JaxRsApplication extends Application 
{ 
    private final Set<Class<?>> classes; 

    public JaxRsApplication() 
    { 
     HashSet<Class<?>> c = new HashSet<Class<?>>(); 
     c.add(HelloWorldResource.class); 
     classes = Collections.unmodifiableSet(c); 
    } 

    @Override 
    public Set<Class<?>> getClasses() 
    { 
     return classes; 
    } 
} 

這對於純文本消息後工作正常,但FPR的JSON(MediaType.APPLICATION_JSON)和XML部分(MediaType.APPLICATION_XML)失敗,說明不支持媒體類型。任何想法可能是錯的?

回答

4

JAX-RS有一堆內置的處理程序,可以從幾個不同的 到特定的Java類型進行編組。

一旦我們開始處理自定義數據綁定(對Java對象進行編組/解組),我們將處於不同的球類遊戲中。我們現在需要一些其他MessageBodyWritersMesageBodyReaders

幸運的是,已有讀者和作者可用於XML和JSON數據綁定。 JAX-RS帶有一個標準的XML編組/解組,我們必須使用JAXB註釋。因此,對於你Test類,假設是這樣的

public class Test { 
    private String name; 
    private int age; 

    public String getName() { return name; } 
    public void setName(String name) { this.name = name;} 
    public int getAge() { return age; } 
    public void setAge(int age) { this.age = age; } 
} 

做出允許JAXB 提供商來解讀/馬歇爾,我們應該提供,至少,一個@XmlRootElement

@XmlRootElement 
public class Test { 
    .... 
} 

這樣做應該允許XML工作。至於JSON,JSON綁定不是規範的標準參數,但我們可以簡單地向項目添加一個依賴項,它將自動註冊所需的提供程序來處理JSON綁定。您可以查看json-moxy示例的pom.xml。你會看到這需要依賴

<dependency> 
    <groupId>org.glassfish.jersey.media</groupId> 
    <artifactId>jersey-media-moxy</artifactId> 
</dependency> 

什麼的依賴性使應用程序做的,是元帥/解組JSON /從我們的Java對象,使用JAXB註釋。所以只需將這個依賴添加到pom.xml即可。該應用程序應該工作。剛剛測試過。

+0

感謝您的快速和非常優秀的答案。現在工作。 – user2737950 2014-11-02 09:04:00