Using compenv Sending a JMS Message In a Java EE Container

Enhanced Support for Using WebLogic JMS with EJBs and Servlets 4-15 }

4.6.2 Sending a JMS Message In a Java EE Container

After you declare the JMS connection factory and destination resources, you can use them to send andor receive JMS messages inside an EJB or servlet. The following sections provide examples on how to send a message:

4.6.2.1 Using compenv

The following code fragment sends a message if you map to the java:compenv JNDI tree: Example 4–3 Sending a Message Using compenv . . . InitialContext ic = new InitialContext; QueueConnectionFactory qcf = QueueConnectionFactoryic.lookupjava:compenvjmsQCF; Queue destQueue = Queueic.lookupjava:compenvjmsTESTQUEUE; ic.close; QueueConnection connection = qcf.createQueueConnection; try { QueueSession session = connection.createQueueSession0, false; QueueSender sender = session.createSenderdestQueue; TextMessage msg = session.createTextMessageThis is a test; sender.sendmsg; } finally { connection.close; } This is standard code that complies with the Java EE specification and should run on any EJB or servlet product that properly supports Java EE — the difference is that it runs more efficiently on WebLogic Server, because under the covers various objects are pooled, as described in Section 4.3.5, Pooled JMS Connection Objects. Note that this code fragment uses a try...finally block to guarantee that the close method on the JMS Connection object is executed even if one of the statements inside the block throws an exception. If no connection pooling were being done, then this block would be necessary in order to ensure that the connection is closed, and to prevent server resources from being wasted. But since WebLogic Server pools some of the objects that are created by this code fragment, it is even more important that close be called; otherwise, the EJB or servlet container will not know when to return the object to the pool. Also, none of the transactional XA extensions to the JMS API are used in this code fragment. Instead, the container uses them internally if the JMS code is used inside a transaction context. But whether XA is used internally, the user-written code is the same, and does not use any JMS XA classes. This is what is specified by Java EE. Writing EJB code in this way enables you to run EJBs in an environment where transactions are present or in a non-transactional environment, just by changing the deployment descriptors. 4-16 Programming JMS for Oracle WebLogic Server

4.6.3 Dependency Injection