我已经使用Oracle Glass-fish服务器4.1版本成功开发了JMS队列,然后我可以使用java EE应用程序成功发送和读取消息,但我需要将实现代码实现到Swing应用程序,我使用相同的代码作为Java EE申请,但工作不正常,请参考下面的代码
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)
任何人都可以为此提供帮助。
答案 0 :(得分:1)
在服务器上下文之外,没有默认的初始上下文工厂类。
一开始就试试这个:
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.enterprise.naming.SerialInitContextFactory");
Context c = new InitialContext(env);
您需要将glassfish命名(或嵌入式全部)jar作为依赖项。