如何将聊天记录保存到数据库中?

时间:2015-07-11 11:17:42

标签: java websocket

我正在使用java websocket编写聊天应用程序,现在我需要保存聊天记录,所以在调用onMessage方法时我创建了我的对象,设置其属性并将其保存到数据库,但没有理由它没有收到坚持部分,这​​是我的代码:

@OnMessage
public void onMessage(final Session session,
        final ChatMessageBean chatMessage) {
    String sender = (String) session.getUserProperties().get("user");

    try {

        for (Session s : session.getOpenSessions()) {
            if (s.isOpen()
                    && ((chatMessage.getReceiver()).equals(s
                            .getUserProperties().get("user")) || sender
                            .equals(s.getUserProperties().get("user")))) {
                s.getBasicRemote().sendObject(chatMessage);

                System.err.println("chatMessage is : " + chatMessage);
                System.err.println("user is : "
                        + s.getUserProperties().get("user"));
            }

        }

    } catch (IOException | EncodeException e) {
        log.log(Level.WARNING, "onMessage failed", e);

    }
    ChatMessage chatConv = new ChatMessage();
    chatConv.setMessage("hihii");
    chatConv.setRecievedDate(new Date());
    chatConv.setSeenStaus(true);
    chatConv.setSenderId("7923");
    chatConv.setReciever("702");
    chatCrud.addChat(chatConv);

}

和我在chatCrud Class上的addChat方法:

public class ChatCrud {

@Inject
EntityManager em;

public String addChat(ChatMessage chat) {
    try{
    em.getTransaction().begin();
    em.persist(chat);
    em.getTransaction().commit();
    }catch(Exception e){
        System.out.println("!!!!!! "+e);
    }
    return "OK";
}
   }

我改变了我的方法以捕获异常,sysout结果是:

!!!!!! org.jboss.weld.context.ContextNotActiveException: WELD-001303 No active contexts for scope type javax.enterprise.context.RequestScoped

onMessage方法是保存聊天记录的错误位置吗?

0 个答案:

没有答案