简体   繁体   中英

JAX-WS, WebServiceContext and Session

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM