2017-02-18 118 views
0

我已經成功開發了使用Oracle Glass-fish服務器4.1版本的JMS隊列,然後我可以使用java EE應用程序成功發送和讀取消息,但是我需要將發送者代碼實現爲Swing應用程序,我使用了相同的代碼,Java EE應用程序,但它不做工精細,請參考下面的代碼使用java Swing發送消息給JMS隊列

public class SenderSwing {  
    /** 
    * @param args the command line arguments 
    */ 
public static void main(String[] args) { 
    try { 

     new SenderSwing().sendJMSMessageToDefaultQueue("Hi "+System.currentTimeMillis()); 

    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 
private void sendJMSMessageToDefaultQueue(Object messageData) throws JMSException, NamingException { 
    Context c = new InitialContext(); 
    ConnectionFactory cf = (ConnectionFactory) c.lookup("java:comp/DefaultJMSConnectionFactory"); 
    Connection conn = null; 
    Session s = null; 
    try { 
     conn = cf.createConnection(); 
     s = conn.createSession(false, s.AUTO_ACKNOWLEDGE); 
     Destination destination = (Destination) c.lookup("jms/defaultQueue"); 
     MessageProducer mp = s.createProducer(destination);    
     mp.send(createJMSMessageForjmsDefaultQueue(s, messageData)); 
    } finally { 
     if (s != null) { 
      try { 
       s.close(); 
      } catch (JMSException e) { 
       Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e); 
      } 
     } 
     if (conn != null) { 
      conn.close(); 
     } 
    } 
} 
private Message createJMSMessageForjmsDefaultQueue(Session session, Object messageData) throws JMSException { 
    // TODO create and populate message to send 
    TextMessage tm = session.createTextMessage(); 
    tm.setText(messageData.toString()); 


    return tm; 
} 

}

上面的代碼給我象下面這樣的例外,

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662) 
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313) 
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350) 
at javax.naming.InitialContext.lookup(InitialContext.java:417) 
at senderswing.SenderSwing.sendJMSMessageToDefaultQueue(SenderSwing.java:43) 
at senderswing.SenderSwing.main(SenderSwing.java:35) 

任何人都可以幫忙。

回答

1

在服務器環境之外,沒有默認的初始上下文工廠類。

試試這個一開始:

Hashtable env = new Hashtable(); 
env.put(Context.INITIAL_CONTEXT_FACTORY, 
"com.sun.enterprise.naming.SerialInitContextFactory"); 
Context c = new InitialContext(env); 

您需要GlassFish的命名(或嵌入所有)的容器作爲一個依賴。