在servlet之间进行通信时出现空指针异常

时间:2011-05-06 04:17:19

标签: java servlets

我在一个servlet中有登录代码:LoginGtalkServlet ..

 XMPPConnection connection;

 //@see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)


 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");

    System.out.println(userName);
    System.out.println(password);

    //ProxyInfo proxyInfo = new      
    ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com",5222,"gmail.com");
    connection = new XMPPConnection(config);
    config.setSASLAuthenticationEnabled(false);
    try {
        connection.connect();
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    try {
        connection.login(userName, password);
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    boolean status=connection.isAuthenticated();
    if(status==true)
    {
        System.out.println("Success");
        response.sendRedirect("GetRoster");
    }
    else
    {
        response.sendRedirect("Loginfailed.html");
    }

我的GetRosterServlet有用于撤销名单列表的代码

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
     Roster roster = connection.getRoster();
    Collection<RosterEntry> entries = roster.getEntries();
    for (RosterEntry r : entries) {
        String user = r.getUser();
        String name = r.getName();
        System.out.println(name + user);
    }
    roster.addRosterListener(new RosterListener() {
        // Ignored events public void entriesAdded(Collection<String>
        // addresses) {}
        public void entriesDeleted(Collection<String> addresses) {
        }

        public void entriesUpdated(Collection<String> addresses) {
        }

        public void presenceChanged(Presence presence) {
            System.out.println("Presence changed: " + presence.getFrom()
                    + " " + presence);
        }

        @Override
        public void entriesAdded(Collection<String> arg0) {

        }
    });

}

现在isssue是我的GetRosterServlet没有被告知我已经登录到Gtalk ..i。LoginGtalkServlet没有与GetRosterServlet通信,因此connection.getRoster()抛出Null指针异常......

如何让名册servlet知道用户已登录gtalk并因此获取好友列表

2 个答案:

答案 0 :(得分:0)

请注意,我熟悉XMPP / GTalk。

当您在LoginGtalkServlet中登录时,是否可以将某些会话ID传回?如果是这样,您可以将其作为查询参数或POST主体放入重定向URL,然后GetRosterServlet可以从request中提取会话ID,并通过该会话ID将其用于Gtalk。

注意:我刚刚编辑的只是为了解决一些不好的语法。没有实质性的改变。)

答案 1 :(得分:0)

您可以将连接对象保存在会话属性中。

session .setAttribute("connection", connectionObj);

可以使用session.getAttribute("connection");

获得