2015-10-05 49 views
0

我正在Glassfish 4.1上製作Java EE 7應用程序(war)。
該應用程序是一個簡單的CRUD應用程序。
對於測試CRUD操作,我製作了一個Java SE客戶端(使用Jersey2客戶端API)。 奇怪的行爲是HTTP POST創建不檢測對象的一個​​領域:
我有一個「生日」屬性,來「」總是在服務器端。
我不明白爲什麼會發生這種情況,以及如何解決這個問題?Stange RESTful Java EE行爲

這裏是我正在使用服務器端的依賴關係:

<dependency> 
     <groupId>org.eclipse.persistence</groupId> 
     <artifactId>org.eclipse.persistence.core</artifactId> 
     <version>2.6.0</version> 
     <type>jar</type> 
    </dependency> 
    <dependency> 
     <groupId>javax</groupId> 
     <artifactId>javaee-web-api</artifactId> 
     <version>7.0</version> 
     <scope>provided</scope> 
    </dependency> 

下面是客戶端的依賴關係:

<dependency> 
     <groupId>org.glassfish.jersey.core</groupId> 
     <artifactId>jersey-client</artifactId> 
     <version>2.22</version> 
    </dependency> 
    <dependency> 
     <groupId>com.fasterxml.jackson.jaxrs</groupId> 
     <artifactId>jackson-jaxrs-json-provider</artifactId> 
     <version>2.6.2</version> 
    </dependency> 

這裏是在客戶端創建塊:

Client client = ClientBuilder.newClient(); 
    WebTarget webTarget = client.target("http://localhost:8080/MedicalCenter/rest/customers"); 

    Customer customer = new Customer("Jason", "Bourne", new Date(), "This is description", new ArrayList<Device>()); 

    ObjectMapper mapper = new ObjectMapper(); 

    String mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); 
    result = mapper.writeValueAsString(customer); 

    Response response = webTarget.request("application/json") 
      .post(Entity.entity(result, MediaType.APPLICATION_JSON_TYPE)); 

以下是發送的JSON的示例:

Here is an example {"id":null, 
"name":"Jason", 
"familyName":"Bourne", 
"birthDate":"2015-10-05T21:41:43‌​.044+0000", 
"description":"This is description", 
"creation":"2015-10-05T21:41:43.044+0000", 
"enabled":true, 
"system":t‌​rue, 
"version":null, 
"devices":[]} 

請幫幫我:) 謝謝!

+1

你打印出JSON的樣子嗎?數據序列化不會出現如何服務器期望。 – leeor

+0

檢查以確保沒有什麼是瞬態的 –

+0

這是什麼'String mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);'? – ACV

回答

0

當使用Jersey 1.19客戶端軟件包創建http post後,情況變得更加陌生。
所以我得到了一個確認,說這是一個在服務器端的反序列化問題的假設是錯誤的,因爲它與球衣1.19客戶端捆綁包一起工作。
我重新開始調查,我比較澤西1和澤西島2客戶端兩者的JSON輸出,並且我發現,所不同的是生日的日期格式:

  • Jeysey 2:「生日」:」 1990-05-04T22:00:00.000 + 0000"
  • 澤西1: 「生日」: 「2015-10-06T00:24:32.693 + 02:00」 < - 這是工作

所以我試圖迫使Jersey 2客戶端中的DateFormat:

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); 
//Jackson Object Mapper 
ObjectMapper mapper = new ObjectMapper(); 
mapper.setDateFormat(sdf); 

,這是工作的5/5

下一個問題是調用這個解決辦法,爲什麼只接受格式是這樣嗎?

希望這種解決方法可以幫助每個有相同問題的人!

+1

需要考慮的一件事是Glassfish中使用的實際默認JSON提供程序是MOXy,而不是Jackson,如[這裏]所述(http://stackoverflow.com/a /2587435分之29247558)。 –