JMS ActiveMQ学习(一)(四)

2014-11-24 09:01:33 · 作者: · 浏览: 2
vlet implements MessageListener {

//定义初始化所需要的变量

private InitialContext initCtx;

private Context envContext;

private ConnectionFactory connectionFactory;

private Connection connection;

private Session jmsSession;

private MessageProducer producer;

public void onMessage(Message message) {

// TODO Auto-generated method stub

}

/**

* Constructor of the object.

*/

public MyPublish() {

super();

}

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

/**

* The doPost method of the servlet.

*

* This method is called when a form has its tag value method equals to post.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String content=request.getParameter("content");

//设置持久方式

try {

producer.setDeliveryMode(DeliveryMode.PERSISTENT);

Message testMessage = jmsSession.createMessage();

// 发布刷新文章消息

testMessage.setStringProperty("RefreshArticleId", content);

producer.send(testMessage);

// 发布刷新帖子消息

testMessage.clearProperties();

testMessage.setStringProperty("RefreshThreadId", content);

producer.send(testMessage);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* Initialization of the servlet.

*

* @throws ServletException if an error occurs

*/

public void init() throws ServletException {

// Put your code here

try {

initCtx = new InitialContext();

envContext = (Context) initCtx.lookup("java:comp/env");

connectionFactory = (ConnectionFactory) envContext.lookup("jms/NormalConnectionFactory");

connection = connectionFactory.createConnection();

jmsSession = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

producer = jmsSession.createProducer((Destination) envContext.lookup("jms/topic/MyTopic"));

} catch (NamingException e) {

e.printStackTrace();

} catch (JMSException e) {

e.printStackTrace();

}

}

}

最后,建一个MyPublish.jsp页面,加上一下代码

在web.xml中加上一下代码

This is the description of my J2EE component