跨服务的会话管理的实例
优质
小牛编辑
140浏览
2023-12-01
下面是一个跨服务的会话管理的实例。在这个例子中有两个WebService类:LoginService和SearchService,代码如下:
LoginService.java
package service; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.ServiceGroupContext; public class LoginService{ public boolean login(String username, String password){ if("bill".equals(username) && "1234".equals(password)){ // 第1步:设置key-value对 MessageContext mc = MessageContext.getCurrentMessageContext(); ServiceGroupContext sgc = mc.getServiceGroupContext(); sgc.setProperty("login", "成功登录"); return true; }else{ return false; } } public String getLoginMsg(){ // 第1步:获得key-value对中的value MessageContext mc = MessageContext.getCurrentMessageContext(); ServiceGroupContext sgc = mc.getServiceGroupContext(); return (String)sgc.getProperty("login"); } }
SearchService.java
package service; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.ServiceGroupContext; public class SearchService{ public String findByName(String name){ // 第1步:获得key-value对中的value MessageContext mc = MessageContext.getCurrentMessageContext(); ServiceGroupContext sgc = mc.getServiceGroupContext(); if (sgc.getProperty("login") != null) return "找到的数据<" + name + ">"; else return "用户未登录"; } }
services.xml文件中的配置代码如下:
<serviceGroup> <!-- 第2步:添加scope属性,并设置属性值为application --> <service name="loginService" scope="application"> <description> 登录服务 </description> <parameter name="ServiceClass"> service.LoginService </parameter> <messageReceivers> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" /> </messageReceivers> </service> <!-- 第2步:添加scope属性,并设置属性值为application --> <service name="searchService" scope="application"> <description> 搜索服务 </description> <parameter name="ServiceClass"> service.SearchService </parameter> <messageReceivers> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" /> </messageReceivers> </service> </serviceGroup>
下面是使用两个stub类的对象实例访问上面实现的两个WebService的客户端代码:
LoginServiceStub stub = new LoginServiceStub(); LoginServiceStub.Login login = new LoginServiceStub.Login(); login.setUsername("bill"); login.setPassword("1234"); if(stub.login(login).local_return){ System.out.println(stub.getLoginMsg().local_return); SearchServiceStub searchStub = new SearchServiceStub(); SearchServiceStub.FindByName fbn = new SearchServiceStub.FindByName(); fbn.setName("abc"); System.out.println(searchStub.findByName(fbn).local_return); }
在执行上面的代码后,将输出如下的信息:
成功登录 找到的数据<abc>
读者可以将scope属性值改成transportsession,看看会输出什么!