1

Can I use WebServiceContext and the method getMessageContext() in a web service to get a HttpSession object for save and get a session value? I was trying use the HttpSession in a web service like this:

@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public class DummyWs {

    @Resource
    private WebServiceContext wsContext;

    @WebMethod(operationName = "sayHello")
    public String sayHello(@WebParam(name = "name") String name) {
        return "hello " + name;
    }

    @WebMethod(operationName="setValue")
    public void setValue(@WebParam(name = "value") String newValue) {
        MessageContext mc = wsContext.getMessageContext();
        HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
        session.setAttribute("value", newValue);
    }

    @WebMethod(operationName="getValue")
    public String getValue() {
        MessageContext mc = wsContext.getMessageContext();
        HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();
        return (String)session.getValue("value");
    }

}

I saw other examples that uses the @Stateful annotation, but I don't use this. Is necessary use the @Stateful annotation? What happened if I don't use this annotation?

userfb
  • 546
  • 4
  • 9
  • Not sure if the @Stateful annotation is actually doing anything to make the underlying transport to add session information to the HTTP session, but its always recommended to use the annotation. On another note, do you really need to use a stateful webservice? Its generally always recommended to use stateless webservices as much as possible. You might want to look at this too: http://stackoverflow.com/questions/988819/stateful-webservice – jbx Nov 04 '13 at 14:01

1 Answers1

0

Did you see the sample stateful included in the Reference Implementation zip distribution?

The sample use the annotation com.sun.xml.ws.developer.Stateful in the web service implementation and the class com.sun.xml.ws.developer.StatefulWebServiceManager for store the objects. As Java Web services are required to be stateless, we need to save the contents of the objects in a persistent storage across client calls.

In another way, you should prefer a staless service. The failure-handling, the interaction with transactional semantics is simple. And the reusability is enhanced.

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148