1 |
package dk.thoerup.messagedriven; |
2 |
|
3 |
import java.io.IOException; |
4 |
|
5 |
import javax.jms.Connection; |
6 |
import javax.jms.ConnectionFactory; |
7 |
import javax.jms.MessageProducer; |
8 |
import javax.jms.Queue; |
9 |
import javax.jms.Session; |
10 |
import javax.jms.TextMessage; |
11 |
import javax.naming.InitialContext; |
12 |
import javax.naming.NamingException; |
13 |
import javax.servlet.ServletException; |
14 |
import javax.servlet.annotation.WebServlet; |
15 |
import javax.servlet.http.HttpServlet; |
16 |
import javax.servlet.http.HttpServletRequest; |
17 |
import javax.servlet.http.HttpServletResponse; |
18 |
|
19 |
|
20 |
@WebServlet(name = "ProducerServlet", urlPatterns = { "/ProducerServlet" }) |
21 |
public class ProducerServlet extends HttpServlet { |
22 |
private static final long serialVersionUID = 1L; |
23 |
|
24 |
/** |
25 |
* @see HttpServlet#HttpServlet() |
26 |
*/ |
27 |
public ProducerServlet() { |
28 |
super(); |
29 |
// TODO Auto-generated constructor stub |
30 |
} |
31 |
|
32 |
// why doesn't @Resource work ?? |
33 |
//@Resource(mappedName = "jms/helloFactory") |
34 |
private static ConnectionFactory connectionFactory; |
35 |
|
36 |
//@Resource(mappedName = "jms/hello") |
37 |
private static Queue queue; |
38 |
|
39 |
|
40 |
@Override |
41 |
public void init() throws ServletException { |
42 |
try { |
43 |
InitialContext ic = new InitialContext(); |
44 |
connectionFactory = (ConnectionFactory)ic.lookup("jms/helloFactory"); |
45 |
queue = (Queue)ic.lookup("jms/hello"); |
46 |
} catch(NamingException ne) { |
47 |
throw new ServletException(ne); |
48 |
} |
49 |
} |
50 |
|
51 |
|
52 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
53 |
try { |
54 |
|
55 |
Connection connection = connectionFactory.createConnection(); |
56 |
|
57 |
//Connection connection = connectionFactory.createConnection(); |
58 |
|
59 |
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); |
60 |
MessageProducer producer = session.createProducer(queue); |
61 |
TextMessage message = session.createTextMessage(); |
62 |
message.setStringProperty("name", "World!!"); |
63 |
message.setText("this is the body"); |
64 |
producer.send(message); |
65 |
response.getWriter().print("Message sent" ); |
66 |
} catch (Exception e) { |
67 |
response.getWriter().print("Error:" + e.getMessage() ); |
68 |
} |
69 |
} |
70 |
|
71 |
|
72 |
} |