Search code examples
javaweb-servicesjax-ws

Use variable between JAX-WS requests


I'm trying to do a web application using JAX -WS. My problem seems to be very simple, however I cannot understand how to resolve it. I have class variables which values I need to use in GET and POST requests. For example, I initiate 'response' in GET methode and I need to use it then in POST methode, but when I call POST api/conversation from js I receive an error because 'response' is still null. How can I save value for variables? Here is my code

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);
}

}


Solution

  • The Java class in question does not seem to be a container managed bean. When you make a rest service call to the GET and subsequently the POST methods, two separate instances of the Conversation class are created. Hence, the class field response will be null in the second POST call.

    There are multiple ways to solve this problem. However, the approach to take depends on answering the question: Should the service really be aware of two separate client requests? Or should the client make one GET call and then provide the subsequent POST with the required information.

    I would use approach 1 noted below, unless there is a good reason to use either 2, 3 or 4. (2, 3 and 4 are similar just they are different specifications / frameworks)

    1. The client caches the response of the GET and sends the required information back with the POST request
    2. Use an EE stateful session bean (http://docs.oracle.com/javaee/6/tutorial/doc/gipjg.html)
    3. Use a CDI session scoped bean (http://docs.oracle.com/javaee/6/tutorial/doc/gjbbk.html)
    4. Use spring session scoped bean (http://springinpractice.com/2008/05/08/session-scoped-beans-in-spring / https://tuhrig.de/making-a-spring-bean-session-scoped/)