Tomcat6.0 + ActiveMq5.1 + Spring2.5 (zhuan)

Tomcat6.0 + ActiveMq5.1 + Spring2.5 


需要的jar包(官方网下载:http://activemq.apache.org/activemq-520-release.html,其中已经包含所需要的所有包):
activemq-all-5.2.0.jar
commons-pool-1.4.jar
log4j-1.2.14.jar
spring-beans-2.5.5.jar
spring-context-2.5.5.jar
spring-core-2.5.5.jar
spring-jms-2.5.5.jar
spring-tx-2.5.5.jar
spring-web-2.5.5.jar
spring-webmvc-2.5.5.jar
xbean-spring-3.4.jar

1、applicationContext.xml(src根下):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:amq="http://activemq.apache.org/schema/core"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <bean id="jmsConnectionFactory"
        class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:comp/env/jms/ConnectionFactory"></property>
    </bean>

    <bean id="jmsQueue"
        class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:comp/env/jms/Queue"></property>
    </bean>

    <bean id="jmsTemplate"
        class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="jmsConnectionFactory"></property>
        <property name="defaultDestination" ref="jmsQueue"></property>
    </bean>

    <bean id="sender" class="message.Sender">
        <property name="jmsTemplate" ref="jmsTemplate"></property>
    </bean>

    <bean id="receive" class="message.Receiver"></bean>
    <bean id="listenerContainer"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="jmsConnectionFactory"></property>
        <property name="destination" ref="jmsQueue"></property>
        <property name="messageListener" ref="receive"></property>
    </bean>
</beans>

2、由于面的配置文件中使用了jndi,所以也得在Tomcat目录下的conf/context.xml配置,需加入
<Resource name="jms/ConnectionFactory"
  auth="Container"  
  type="org.apache.activemq.ActiveMQConnectionFactory"
  description="JMS Connection Factory"
  factory="org.apache.activemq.jndi.JNDIReferenceFactory"
  brokerURL="vm://localhost"
  brokerName="LocalActiveMQBroker"/>

<Resource name="jms/Queue"
auth="Container"
type="org.apache.activemq.command.ActiveMQQueue"
description="my Queue"
factory="org.apache.activemq.jndi.JNDIReferenceFactory"
physicalName="FOO.BAR"/>

3、java类:

SendMessage.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import message.Sender;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SendMessage extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public SendMessage() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * 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 {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the GET method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * 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 {

        ApplicationContext xt = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        Sender sender = (Sender) xt.getBean("sender");
       
        String Text = request.getParameter("text");
       
        sender.send(Text);
       
        response.encodeRedirectUrl("/index.jsp");
        System.out.println("asdfasdf");

    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException
     *             if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

Receiver.java

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class Receiver implements MessageListener {

    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            TextMessage text = (TextMessage) message;

            try {
                System.out.println("Receive:" + text.getText());
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

Sender.java

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;


public class Sender {

    private JmsTemplate jmsTemplate;

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }
   
    public void send(final String text){
        System.out.println("---Send:"+text);
        jmsTemplate.send(new MessageCreator(){

            public Message createMessage(Session arg0) throws JMSException {
                // TODO Auto-generated method stub
                return arg0.createTextMessage(text);
            }
           
        });
    }

}

4、web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- 配置启动JMS服务 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/classes/applicationContext.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>SendMessage</servlet-name>
    <servlet-class>action.SendMessage</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>SendMessage</servlet-name>
    <url-pattern>/servlet/SendMessage</url-pattern>
  </servlet-mapping>
   
</web-app>

5、jsp页面,index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <base href="<%=basePath%>">

        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    </head>

    <body>
        <form action="servlet/SendMessage" method="post">
            请输入:
            <input type="text" name="text">
            <br />
            <input type="submit" value="确定">

        </form>
    </body>
</html>

你可能感兴趣的:(activemq)