2017-05-31 68 views
0

我正在嘗試使用JAX -WS來執行Web應用程序。我的問題似乎很簡單,但我不明白如何解決它。我有我需要在GET和POST請求中使用的類變量。例如,我在GET方法中啓動「響應」,然後我需要在POST方法中使用它,但是當我從js調用POST api/conversation時,我收到一個錯誤,因爲'響應'仍然爲空。我如何保存變量的值?這裏是我的代碼在JAX-WS請求之間使用變量

import javax.ws.rs.*; 

@ApplicationPath("api") 
@Path("conversation") 
public class Conversation { 
    private final String conversationWorkspace = "myworkspace"; 
    private final static String CONVERSATION_ID = "myid"; 
    private final static String CONVERSATION_PASS = "mypass"; 

private MessageRequest request; 
private MessageResponse response; 

private ConversationService service; 

@GET 
@Produces("application/text") 
public String getInitiatePhrase(){ 
    service = new ConversationService("2017-05-26", CONVERSATION_ID, CONVERSATION_PASS); 
    response = service.message(conversationWorkspace, null).execute(); //here response gets its value 

    return response.getText().get(0); 
} 

@POST 
@Produces("application/text") 
@Consumes("application/text") 
public String getBotAnswer(String userText){ 
    System.out.println("response " + response); 
    request = new MessageRequest.Builder().inputText(userText).context(response.getContext()).build(); //response must not be null 
    response = service.message(conversationWorkspace, request).execute(); 

    return response.getText().get(0); 
} 

}

回答

0

有問題的Java類似乎並沒有成爲一個容器管理的Bean。當您對GET進行休息服務調用並隨後調用POST方法時,會創建兩個單獨的Conversation類實例。因此,第二次POST調用中的類字段響應將爲空。

有多種方法可以解決這個問題。但是,採取的方法取決於回答這個問題:服務是否應該真正意識到兩個單獨的客戶端請求?或者客戶端應該進行一次GET調用,然後爲後續的POST提供所需的信息。

我會使用方法1中記下面,除非有很好的理由爲使用2,3或4(圖2,3和4是類似的只是它們是不同規格/框架)

  1. 的客戶端緩存GET的響應和對POST請求
  2. 使用一個EE狀態會話bean發送所需的信息回到(http://docs.oracle.com/javaee/6/tutorial/doc/gipjg.html
  3. 使用CDI會話範圍的bean(http://docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html
  4. 使用彈簧會話作用域bean( http://springinpractice.com/2008/05/08/session-scoped-beans-in-spring/https://tuhrig.de/making-a-spring-bean-session-scoped/
+0

我使用了1種方法,它工作。謝謝! – Tanya