1 |
package dk.thoerup.messagedriven; |
2 |
|
3 |
import java.io.IOException; |
4 |
|
5 |
import javax.annotation.Resource; |
6 |
import javax.jms.Connection; |
7 |
import javax.jms.ConnectionFactory; |
8 |
import javax.jms.MessageProducer; |
9 |
import javax.jms.Queue; |
10 |
import javax.jms.Session; |
11 |
import javax.jms.TextMessage; |
12 |
import javax.naming.InitialContext; |
13 |
import javax.naming.NamingException; |
14 |
import javax.servlet.ServletException; |
15 |
import javax.servlet.annotation.WebServlet; |
16 |
import javax.servlet.http.HttpServlet; |
17 |
import javax.servlet.http.HttpServletRequest; |
18 |
import javax.servlet.http.HttpServletResponse; |
19 |
|
20 |
|
21 |
@WebServlet(name = "ProducerServlet", urlPatterns = { "/ProducerServlet" }) |
22 |
public class ProducerServlet extends HttpServlet { |
23 |
private static final long serialVersionUID = 1L; |
24 |
|
25 |
|
26 |
// why doesn't @Resource work ?? |
27 |
@Resource(mappedName = "jms/helloFactory") |
28 |
private static ConnectionFactory connectionFactory; |
29 |
|
30 |
@Resource(mappedName = "jms/hello") |
31 |
private static Queue queue; |
32 |
|
33 |
|
34 |
@Override |
35 |
public void init() throws ServletException { |
36 |
|
37 |
try { |
38 |
InitialContext ic = new InitialContext(); |
39 |
if (connectionFactory == null) { |
40 |
connectionFactory = (ConnectionFactory)ic.lookup("jms/helloFactory"); |
41 |
System.out.println("@Resource failed for connection factory"); |
42 |
} |
43 |
if (queue == null) { |
44 |
queue = (Queue)ic.lookup("jms/hello"); |
45 |
System.out.println("@Resource failed for queue"); |
46 |
} |
47 |
} catch(NamingException ne) { |
48 |
throw new ServletException(ne); |
49 |
} |
50 |
} |
51 |
|
52 |
|
53 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { |
54 |
try { |
55 |
|
56 |
Connection connection = connectionFactory.createConnection(); |
57 |
|
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 |
throw new ServletException(e); |
68 |
} |
69 |
} |
70 |
|
71 |
|
72 |
} |