First, the MDB class:
package test;The servlet class:
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
@MessageDriven(mappedName="testQueue2",
activationConfig = { @ActivationConfigProperty(
propertyName="destinationType", propertyValue="javax.jms.Queue")})
public class MessageBean implements MessageListener {
Logger logger = Logger.getLogger("test");
public void onMessage(Message msg) {
try {
String name = msg.getStringProperty("name");
logger.info("Received msg " + msg + ", from " + name);
} catch (JMSException e) {
throw new RuntimeException(e);
}
}
}
package test;After compiling, package the two classes into a WAR file, say, mdb.war:
import java.io.IOException;
import javax.annotation.Resource;
import javax.jms.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(urlPatterns = "/MessageServlet")
public class MessageServlet extends HttpServlet {
@Resource(mappedName = "testQueue2")
private Queue queue;
@Resource(mappedName = "jms/QueueConnectionFactory")
private QueueConnectionFactory queueConnectionFactory;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
QueueConnection queueConnection = null;
try {
queueConnection = queueConnectionFactory.createQueueConnection();
queueConnection.start();
QueueSession queueSession = queueConnection.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
QueueSender sender = queueSession.createSender(queue);
TextMessage msg = queueSession.createTextMessage();
msg.setText("A message from MessageServlet");
msg.setStringProperty("name", "MessageServlet");
sender.send(msg);
} catch (JMSException e) {
throw new RuntimeException(e);
} finally {
try {
if (queueConnection != null) {
queueConnection.close();
}
} catch (JMSException e) { //ignore
}
}
}
}
WEB-INF/classes/test/MessageBean.classCreate the 2 JMS resources (testQueue2 & jms/QueueConnectionFactory) in the target application server. In GlassFish, you can do it in Admin GUI, or via asadmin CLI:
WEB-INF/classes/test/MessageServlet.class
./asadmin create-jms-resource --restype javax.jms.Queue testQueue2Deploy mdb.war by copying it to server autodeploy directory.
./asadmin create-jms-resource --restype javax.jms.QueueConnectionFactory jms/QueueConnectionFactory
Enter the URL in browser to invoke the servlet:
http://localhost:8080/mdb/MessageServlet
You will see the following log in server.log as a result of MDB processing:
[#|2010-04-14T17:28:49.900-0400|INFO|glassfishv3.0|test|_ThreadID=31;_ThreadName=Thread-1;|Received msg com.sun.messaging.jms.ra.DirectTextPacket@3ce177de, from MessageServlet|#]