加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

EJB的WebService

发布时间:2020-12-16 23:48:49 所属栏目:安全 来源:网络整理
导读:? 第一个EJB项目 -hxzon -ejbcode? 一,新建一个EJB项目。命名为firstEjb。 1,新建一个接口。 package hxzon; public interface Hello { public String saySomething(String name); } 2,新建一个无状态会话bean。 package hxzon; import javax.ejb.Remote;

?

第一个EJB项目 -hxzon -ejbcode?
一,新建一个EJB项目。命名为firstEjb。
1,新建一个接口。
package hxzon;
public interface Hello {
public String saySomething(String name);
}
2,新建一个无状态会话bean。
package hxzon;
import javax.ejb.Remote;
import javax.ejb.Stateless;
@Stateless
@Remote
public class HelloBean implements Hello { public String saySomething(String name) {
?? return "hello,"+name;
}
}
3,部署到JBoss。
--------------------------------------------------------------
二,新建一个java项目,作为客户端。
1,项目添加JBossClient依赖包。
2,项目添加firstEjb项目,因为要使用到Hello接口。
3,新建客户端类。
package hxzon;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class HelloClient {
public static void main(String[] args){
?? try {
??? InitialContext ctx=new InitialContext();
??? Hello ejb=(Hello)ctx.lookup("HelloBean/remote");
??? System.out.print(ejb.saySomething("hxzon"));
?? } catch (NamingException e) {
??? // TODO Auto-generated catch block
??? e.printStackTrace();
?? }
}
}
4,编写jndi属性文件。放在类根路径下。
该文件可在jboss4.2.2.GAserverdefaultconf文件夹下找到。
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
5,运行客户端程序。成功。
=====================================================================
=====================================================================
EJB部署为WebService -hxzon -wscode -ejbcode

一,新建EJB项目。
1,这里借用firstEjb项目,只需添加两个注解。
package hxzon; import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService; @Stateless
@Remote
@WebService
public class HelloBean implements Hello { @WebMethod
public String saySomething(String name) {
?? return "hello,"+name;
} }
2,部署。在网址中输入http://localhost:8080/firstEjb/HelloBean?wsdl
可以看到wsdl文件。
路径为http://localhost:8080/jar文件名/发布的实现类名?wsdl
http://127.0.0.1:8080/jbossws/services?查看webservice的发布情况 ---------------------------------------------------------------------------- 二,新建客户端项目。 1,这里我们借用axis-bin-1_4.zip里的 samples.client.DynamicInvoker类来充当WebService客户端。 记得项目导入axis依赖包。 package samples.client; import org.apache.axis.Constants; import org.apache.axis.utils.XMLUtils; import org.apache.axis.encoding.ser.SimpleDeserializer; import org.apache.axis.encoding.ser.ElementSerializerFactory; import org.apache.axis.encoding.ser.ElementDeserializerFactory; import org.apache.axis.encoding.ser.ElementDeserializer; import org.apache.axis.wsdl.gen.Parser; import org.apache.axis.wsdl.symbolTable.BaseType; import org.apache.axis.wsdl.symbolTable.BindingEntry; import org.apache.axis.wsdl.symbolTable.Parameter; import org.apache.axis.wsdl.symbolTable.Parameters; import org.apache.axis.wsdl.symbolTable.ServiceEntry; import org.apache.axis.wsdl.symbolTable.SymTabEntry; import org.apache.axis.wsdl.symbolTable.SymbolTable; import org.apache.axis.wsdl.symbolTable.TypeEntry; import org.w3c.dom.Element; import javax.wsdl.Binding; import javax.wsdl.Operation; import javax.wsdl.Port; import javax.wsdl.Service; import javax.wsdl.extensions.soap.SOAPAddress; import javax.xml.namespace.QName; import javax.xml.rpc.Call; import javax.xml.rpc.encoding.Deserializer; import javax.xml.rpc.encoding.DeserializerFactory; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector;? public class DynamicInvoker { ??? private Parser wsdlParser = null; ??? public DynamicInvoker(String wsdlURL) throws Exception { ??????? // Start by reading in the WSDL using Parser ??????? wsdlParser = new Parser(); ??????? System.out.println("Reading WSDL document from '" + wsdlURL + "'"); ??????? wsdlParser.run(wsdlURL); ??? } ??? private static void usage() { ??????? System.err.println( ??????????????? "Usage: java " + DynamicInvoker.class.getName() + " wsdlLocation " ??????????????? + "operationName[(portName)] " ??????????????? + "[argument1 ...]"); ??????? System.exit(1); ??? } ??? public static void main(String[] args) throws Exception { ??????? if (args.length < 2) { ??????????? usage(); ??????? } ??????? String wsdlLocation = (args.length > 0) ??????????????? ? args[0] ??????????????? : null; ??????? String operationName = (args.length > 1) ??????????????? ? args[1] ??????????????? : null; ??????? String portName = null; ??????? try { ??????????? portName = operationName.substring(operationName.indexOf("(") + 1,?????????????????????????????????????????????? operationName.indexOf(")")); ??????????? operationName = operationName.substring(0,operationName.indexOf("(")); ??????? } catch (Exception ignored) { ??????? } ??????? DynamicInvoker invoker = new DynamicInvoker(wsdlLocation); ??????? HashMap map = invoker.invokeMethod(operationName,portName,args); ??????? for (Iterator it = map.entrySet().iterator(); it.hasNext();) { ??????????? Map.Entry entry = (Map.Entry) it.next(); ??????????? String key = (String) entry.getKey(); ??????????? Object value = entry.getValue(); ??????????? if (value instanceof Element) { ??????????????? System.out.println("====== " + key + " ======"); ??????????????? XMLUtils.ElementToStream((Element) value,System.out); ??????????????? System.out.println("========================="); ??????????? } else { ??????????????? System.out.println(key + "=" + value); ??????????? } ??????? } ??????? System.out.println("nDone!"); ??? } ??? public HashMap invokeMethod( ??????????? String operationName,String portName,String[] args) ??????????? throws Exception { ??????? String serviceNS = null; ??????? String serviceName = null; ??????? String operationQName = null; ??????? System.out.println("Preparing Axis dynamic invocation"); ??????? Service service = selectService(serviceNS,serviceName); ??????? Operation operation = null; ??????? org.apache.axis.client.Service dpf = new org.apache.axis.client.Service(wsdlParser,service.getQName()); ??????? Vector inputs = new Vector(); ??????? Port port = selectPort(service.getPorts(),portName); ??????? if (portName == null) { ??????????? portName = port.getName(); ??????? } ??????? Binding binding = port.getBinding(); ??????? Call call = dpf.createCall(QName.valueOf(portName),?????????????????????????????????? QName.valueOf(operationName)); ??????? ((org.apache.axis.client.Call)call).setTimeout(new Integer(15*1000)); ??????? ((org.apache.axis.client.Call)call).setProperty(ElementDeserializer.DESERIALIZE_CURRENT_ELEMENT,Boolean.TRUE); ???????? ??????? // Output types and names ??????? Vector outNames = new Vector(); ??????? // Input types and names ??????? Vector inNames = new Vector(); ??????? Vector inTypes = new Vector(); ??????? SymbolTable symbolTable = wsdlParser.getSymbolTable(); ??????? BindingEntry bEntry = ??????????????? symbolTable.getBindingEntry(binding.getQName()); ??????? Parameters parameters = null; ??????? Iterator i = bEntry.getParameters().keySet().iterator(); ??????? while (i.hasNext()) { ??????????? Operation o = (Operation) i.next(); ??????????? if (o.getName().equals(operationName)) { ??????????????? operation = o; ??????????????? parameters = (Parameters) bEntry.getParameters().get(o); ??????????????? break; ??????????? } ??????? } ??????? if ((operation == null) || (parameters == null)) { ??????????? throw new RuntimeException(operationName + " was not found."); ??????? } ??????? // loop over paramters and set up in/out params ??????? for (int j = 0; j < parameters.list.size(); ++j) { ??????????? Parameter p = (Parameter) parameters.list.get(j); ??????????? if (p.getMode() == 1) {?????????? // IN ??????????????? inNames.add(p.getQName().getLocalPart()); ??????????????? inTypes.add(p); ??????????? } else if (p.getMode() == 2) {??? // OUT ??????????????? outNames.add(p.getQName().getLocalPart()); ??????????? } else if (p.getMode() == 3) {??? // INOUT ??????????????? inNames.add(p.getQName().getLocalPart()); ??????????????? inTypes.add(p); ??????????????? outNames.add(p.getQName().getLocalPart()); ??????????? } ??????? } ??????? // set output type ??????? if (parameters.returnParam != null) { ??????????? if(!parameters.returnParam.getType().isBaseType()) { ??????????????? ((org.apache.axis.client.Call)call).registerTypeMapping(org.w3c.dom.Element.class,parameters.returnParam.getType().getQName(),??????????????????????????? new ElementSerializerFactory(),??????????????????????????? new ElementDeserializerFactory()); ??????????? } ??????????? // Get the QName for the return Type ??????????? QName returnType = org.apache.axis.wsdl.toJava.Utils.getXSIType( ??????????????????? parameters.returnParam); ??????????? QName returnQName = parameters.returnParam.getQName(); ??????????? outNames.add(returnQName.getLocalPart()); ??????? } ??????? if (inNames.size() != args.length - 2) ??????????? throw new RuntimeException("Need " + inNames.size() + " arguments!!!"); ??????? for (int pos = 0; pos < inNames.size(); ++pos) { ??????????? String arg = args[pos + 2]; ??????????? Parameter p = (Parameter) inTypes.get(pos); ??????????? inputs.add(getParamData((org.apache.axis.client.Call) call,p,arg)); ??????? } ??????? System.out.println("Executing operation " + operationName + " with parameters:"); ??????? for (int j = 0; j < inputs.size(); j++) { ??????????? System.out.println(inNames.get(j) + "=" + inputs.get(j)); ??????? } ??????? Object ret = call.invoke(inputs.toArray()); ??????? Map outputs = call.getOutputParams(); ??????? HashMap map = new HashMap(); ??????? for (int pos = 0; pos < outNames.size(); ++pos) { ??????????? String name = (String) outNames.get(pos); ??????????? Object value = outputs.get(name); ??????????? if ((value == null) && (pos == 0)) { ??????????????? map.put(name,ret); ??????????? } else { ??????????????? map.put(name,value); ??????????? } ??????? } ??????? return map; ??? } ??? private Object getParamData(org.apache.axis.client.Call c,Parameter p,String arg) throws Exception { ??????? // Get the QName representing the parameter type ??????? QName paramType = org.apache.axis.wsdl.toJava.Utils.getXSIType(p); ??????? TypeEntry type = p.getType(); ??????? if (type instanceof BaseType && ((BaseType) type).isBaseType()) { ??????????? DeserializerFactory factory = c.getTypeMapping().getDeserializer(paramType); ??????????? Deserializer deserializer = factory.getDeserializerAs(Constants.AXIS_SAX); ??????????? if (deserializer instanceof SimpleDeserializer) { ??????????????? return ((SimpleDeserializer)deserializer).makeValue(arg); ??????????? } ??????? } ??????? throw new RuntimeException("not know how to convert '" + arg ?????????????????????????????????? + "' into " + c); ??? } ??? public Service selectService(String serviceNS,String serviceName) ??????????? throws Exception { ??????? QName serviceQName = (((serviceNS != null) ??????????????? && (serviceName != null)) ??????????????? ? new QName(serviceNS,serviceName) ??????????????? : null); ??????? ServiceEntry serviceEntry = (ServiceEntry) getSymTabEntry(serviceQName,????????????????????????????????????????????????????????????????? ServiceEntry.class); ??????? return serviceEntry.getService(); ??? } ??? public SymTabEntry getSymTabEntry(QName qname,Class cls) { ??????? HashMap map = wsdlParser.getSymbolTable().getHashMap(); ??????? Iterator iterator = map.entrySet().iterator(); ??????? while (iterator.hasNext()) { ??????????? Map.Entry entry = (Map.Entry) iterator.next(); ??????????? QName key = (QName) entry.getKey(); ??????????? Vector v = (Vector) entry.getValue(); ??????????? if ((qname == null) || qname.equals(qname)) { ??????????????? for (int i = 0; i < v.size(); ++i) { ??????????????????? SymTabEntry symTabEntry = (SymTabEntry) v.elementAt(i); ??????????????????? if (cls.isInstance(symTabEntry)) { ??????????????????????? return symTabEntry; ??????????????????? } ??????????????? } ??????????? } ??????? } ??????? return null; ??? } ??? public Port selectPort(Map ports,String portName) throws Exception { ??????? Iterator valueIterator = ports.keySet().iterator(); ??????? while (valueIterator.hasNext()) { ??????????? String name = (String) valueIterator.next(); ??????????? if ((portName == null) || (portName.length() == 0)) { ??????????????? Port port = (Port) ports.get(name); ??????????????? List list = port.getExtensibilityElements(); ??????????????? for (int i = 0; (list != null) && (i < list.size()); i++) { ??????????????????? Object obj = list.get(i); ??????????????????? if (obj instanceof SOAPAddress) { ??????????????????????? return port; ??????????????????? } ??????????????? } ??????????? } else if ((name != null) && name.equals(portName)) { ??????????????? return (Port) ports.get(name); ??????????? } ??????? } ??????? return null; ??? } } 2,运行samples.client.DynamicInvoker类。 运行时需要在open run dialog配置三个参数。 在arguments标签中输入 http://localhost:8080/firstEjb/HelloBean?wsdl saySomething hxzon 运行成功。 可看到控制台输出 Reading WSDL document from 'http://localhost:8080/firstEjb/HelloBean?wsdl' Preparing Axis dynamic invocation Executing operation saySomething with parameters: saySomething>arg0=hxzon saySomethingResponse>return=hello,hxzon Done! ============================================================ ============================================================ wsdl文件,该文件自动生成。 <definitions name='HelloBeanService' targetNamespace='http://hxzon/' xmlns='http://schemas.xmlsoap.org/wsdl/' xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' xmlns:tns='http://hxzon/' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <types> ?? <xs:schema targetNamespace='http://hxzon/' version='1.0' ??? xmlns:tns='http://hxzon/' ??? xmlns:xs='http://www.w3.org/2001/XMLSchema'> ??? <xs:element name='saySomething' type='tns:saySomething' /> ??? <xs:element name='saySomethingResponse' ???? type='tns:saySomethingResponse' /> ??? <xs:complexType name='saySomething'> ???? <xs:sequence> ????? <xs:element minOccurs='0' name='arg0' ?????? type='xs:string' /> ???? </xs:sequence> ??? </xs:complexType> ??? <xs:complexType name='saySomethingResponse'> ???? <xs:sequence> ????? <xs:element minOccurs='0' name='return' ?????? type='xs:string' /> ???? </xs:sequence> ??? </xs:complexType> ?? </xs:schema> </types> <message name='HelloBean_saySomethingResponse'> ?? <part element='tns:saySomethingResponse' ??? name='saySomethingResponse'> ?? </part> </message> <message name='HelloBean_saySomething'> ?? <part element='tns:saySomething' name='saySomething'></part> </message> <portType name='HelloBean'> ?? <operation name='saySomething' parameterOrder='saySomething'> ??? <input message='tns:HelloBean_saySomething'></input> ??? <output message='tns:HelloBean_saySomethingResponse'></output> ?? </operation> </portType> <binding name='HelloBeanBinding' type='tns:HelloBean'> ?? <soap:binding style='document' ??? transport='http://schemas.xmlsoap.org/soap/http' /> ?? <operation name='saySomething'> ??? <soap:operation soapAction='' /> ??? <input> ???? <soap:body use='literal' /> ??? </input> ??? <output> ???? <soap:body use='literal' /> ??? </output> ?? </operation> </binding> <service name='HelloBeanService'> ?? <port binding='tns:HelloBeanBinding' name='HelloBeanPort'> ??? <soap:address ???? location='http://127.0.0.1:8080/firstEjb/HelloBean' /> ?? </port> </service> </definitions> =================================================== =================================================== 消息bean简单例子 -ejbcode -hxzon 一,新建Ejb项目。 实现MessageListener接口,添加@MessageDriven注解。 package hxzon; import javax.ejb.MessageDriven; import javax.ejb.ActivationConfigProperty; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; @MessageDriven( activationConfig={ ??? @ActivationConfigProperty(propertyName="destinationType",????? propertyValue="javax.jms.Queue"),??? @ActivationConfigProperty(propertyName="destination",????? propertyValue="queue/myqueue") } ) public class HelloMDB implements MessageListener{ public void onMessage(Message msg) { ?? TextMessage tmsg=(TextMessage)msg; ?? try { ??? System.out.println("已接收消息。。。"+tmsg.getText()); ?? } catch (JMSException e) { ??? e.printStackTrace(); ?? } } } 二,新建客户端项目。 package hxzon; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.TextMessage; import javax.naming.InitialContext; public class MDBClient { public static void main(String[] args) { ?? try { ??? InitialContext ctx=new InitialContext(); ??? QueueConnectionFactory factory=(QueueConnectionFactory)ctx.lookup("ConnectionFactory"); ??? QueueConnection con=factory.createQueueConnection(); ??? QueueSession session=con.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE); ??? Queue queue=(Queue)ctx.lookup("queue/myqueue"); ??? TextMessage msg=session.createTextMessage("hello,hxzon"); ??? QueueSender sender=session.createSender(queue); ??? sender.send(msg); ??? session.close(); ??? System.out.println("已发送消息"); ?? } catch (Exception e) { ??? e.printStackTrace(); ?? } } } 运行成功。 上述是点到点模型,也可使用发布-预定模型。只需将Queue改为Topic即可。QueueSender改为TopicPublisher,调用publish(msg)方法。 ---------------------------------------------------------------------------- package hxzon; import javax.ejb.ActivationConfigProperty; import javax.ejb.MessageDriven; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; @MessageDriven( ?? activationConfig={ ???? @ActivationConfigProperty(propertyName="destinationType",?????? propertyValue="javax.jms.Topic"),???? @ActivationConfigProperty(propertyName="destination",?????? propertyValue="topic/mytopic") ?? } ) public class HelloTopicMDB implements MessageListener { public void onMessage(Message msg) { ?? TextMessage tmsg=(TextMessage)msg; ?? try { ??? System.out.println("已接收消息。。。"+tmsg.getText()); ?? } catch (JMSException e) { ??? e.printStackTrace(); ?? } } } ---------------------------------------------------------------------- package hxzon; import javax.jms.TextMessage; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.naming.InitialContext; public class TopicMDBClient {? public static void main(String[] args) { ?? try { ??? InitialContext ctx=new InitialContext(); ??? TopicConnectionFactory factory=(TopicConnectionFactory)ctx.lookup("ConnectionFactory"); ??? TopicConnection con=factory.createTopicConnection(); ??? TopicSession session=con.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE); ??? Topic topic=(Topic)ctx.lookup("topic/mytopic"); ??? TextMessage msg=session.createTextMessage("hello,hxzon"); ??? TopicPublisher publisher=session.createPublisher(topic); ??? publisher.publish(msg); ??? session.close(); ??? System.out.println("已发送消息"); ?? } catch (Exception e) { ??? e.printStackTrace(); ?? } } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读