JAX-WS, WebServiceContext and Session



我可以在Web服务中使用WebServiceContext和getMessageContext()方法来获取用于保存的HttpSession对象并获取会话值吗?我尝试在这样的Web服务中使用HttpSession:

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

我看到了其他使用 @Stateful 注释的示例,但我不使用它。是否有必要使用@Stateful注释?如果我不使用此注释会发生什么情况?

您是否看到示例stateful包含在参考实现 zip 发行版中?

此示例使用 Web 服务实现中的批注com.sun.xml.ws.developer.Stateful和用于存储对象的类com.sun.xml.ws.developer.StatefulWebServiceManager。由于 Java Web 服务需要无状态,因此我们需要跨客户端调用将对象的内容保存在持久存储中。

换句话说,您应该更喜欢无状态服务。故障处理,与事务语义的交互很简单。并且可重用性得到增强。

最新更新