| 1 46 47 package com.coridan.sample.basic.servlet; 48 49 import javax.servlet.ServletException ; 50 import javax.servlet.RequestDispatcher ; 51 import javax.servlet.ServletContext ; 52 import javax.servlet.http.HttpServletRequest ; 53 import javax.servlet.http.HttpServletResponse ; 54 import javax.naming.InitialContext ; 55 import javax.jms.*; 56 import java.io.IOException ; 57 58 public class PublisherServlet extends javax.servlet.http.HttpServlet { 59 60 private ServletContext ctx; 61 private QueueConnection connection; 62 private Queue queue; 63 64 public void init() throws ServletException { 65 66 this.ctx = getServletContext(); 67 68 String connectionFactoryName = "java:comp/env/jms/broker"; 69 String queueName = "java:comp/env/jms/queue/DefQueue"; 70 71 try { 72 InitialContext naming = new InitialContext (); 73 74 QueueConnectionFactory connectionFactory = 76 (QueueConnectionFactory) naming.lookup(connectionFactoryName); 77 78 connection = connectionFactory.createQueueConnection(); 80 81 queue = (Queue) naming.lookup(queueName); 83 } 84 catch(Exception e) { 85 e.printStackTrace(); 86 throw new ServletException (e); 87 } 88 } 89 90 public void destroy() { 91 if (connection != null) { 92 try { 93 if (connection != null) { 94 connection.close(); 95 } 96 } 97 catch (Exception e) { } 98 } 99 } 100 101 public void doPost(HttpServletRequest request, HttpServletResponse response) 102 throws ServletException , IOException { 103 doGet(request, response); 104 } 105 106 public void doGet(HttpServletRequest request, HttpServletResponse response) 107 throws ServletException , IOException { 108 109 QueueSession publishSession = null; 110 RequestDispatcher rd = null; 111 112 try { 113 publishSession = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); 114 QueueSender sender = publishSession.createSender(queue); 115 sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT); 116 TextMessage message = publishSession.createTextMessage(new java.util.Date ().toString()); 117 sender.send(message); 118 } 119 catch(Exception e) { 120 throw new ServletException (e); 121 } 122 finally { 123 try { 124 if (publishSession != null) { 125 publishSession.close(); 126 } 127 } 128 catch (Exception e) {} 129 } 130 } 131 } 132 | Popular Tags |