2013-02-01 12 views
1

我想使用相同的restful webservice路徑來生成xml或json,或者帶有xsl頭的xml。 是否有可能在java中使用任何框架(球衣或resteasy)? 如:有沒有辦法通過java中的參數來改變寧靜web服務的輸出類型?

@Path("/person") 
public class PersonService { 

    @GET 
    @Path("/find") 
    public Person find(@QueryParam("name") String name, @QueryParam("outputformat") String outputformat) { 
      // do some magic to change output format 
      return dao.findPerson(name); 
    } 
} 

回答

3

也許你可以寫一個servlet過濾器,需要查詢字符串,並使用它來設置請求的接受標頭相應地,然後球衣應派遣到任何方法註釋@Consumes匹配。例如,servlet篩選器攔截請求「?outputFormat = xml」並將Accept標頭設置爲「application/xml」。然後,球衣應該派遣到您的資源無論採用哪種方法與註解:@Consumes("application/xml")

這個問題可能會有所幫助:REST. Jersey. How to programmatically choose what type to return: JSON or XML?

+0

謝謝!那是我需要的。 – AlanNLohse

+0

太好了,很高興幫助。隨意投票和/或接受答案。 – Upgradingdave

1

你可以使用新澤西州和使用註釋@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})。您還需要在應用程序中爲POJO添加映射功能。該包括在web.xml文件將是

<filter> 
    <init-param> 
     <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> 
     <param-value>true</param-value> 
    </init-param> 
</filter> 

其他配置是必要的,但它是所有的文檔http://jersey.java.net/nonav/documentation/latest/user-guide.html

1

你也可以輕鬆地定製球衣ServletContainer,你會不會需要其他參數去傳遞下去。您可以在URL中使用.json或.xml協商表示。

public class MyServletContainer extends ServletContainer { 

    @Override 
    protected void configure(ServletConfig servletConfig, ResourceConfig resourceConfig, WebApplication webApplication) { 
    super.configure(servletConfig, resourceConfig, webApplication); 
    resourceConfig.getMediaTypeMappings().put("json", MediaType.APPLICATION_JSON_TYPE); 
    resourceConfig.getMediaTypeMappings().put("xml", MediaType.APPLICATION_XML_TYPE); 
    } 

} 

在您的web.xml中,您可以定義自定義servlet,如下所示。

<servlet> 
    <servlet-name>Jersey Web Application</servlet-name> 
    <servlet-class>com.sun.jersey.MyServletContainer</servlet-class> 
    <init-param> 
     <param-name>javax.ws.rs.Application</param-name> 
     <param-value>com.sun.jersey.MyWebApplication</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
    </servlet> 
相關問題