How do I use Ajax to connect to Java servlets?

2019-08-08 03:18发布

问题:

I am developing a chat client using java. I was able to connect to gtalk as well as chat using SMACK API. Now I need to do the same with jsp servlets and ajax.

I could do the authentication and getting the buddy list with jsp and servlets only. But I have to use Ajax for the chat (so that page won't be refreshed).

for sending and receving msgs I use the api s classes in java. The code is below:

public void sendMessage(String message, String to) throws XMPPException
{
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}

public void processMessage(Chat chat, Message message)
{
if(message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}

Now how do I do the same in Ajax? Can I use the API methods along with ajax? Or use these in servlets and get the response from servlets with ajax and populate the msg s on the page?

回答1:

Have a look at DWR



回答2:

You need to make an XML Http request to the Servlet for that you need to make a XML Http object in the javascript in your HTML/JSP page

var myxmlhttpobj=new GetXmlHttpObject();
function GetXmlHttpObject()
    {
        if (window.XMLHttpRequest)
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            return new XMLHttpRequest();
        }
        if (window.ActiveXObject)
        {
            // code for IE6, IE5
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
        return null;
    }

Now you need to make a request to the Servlet from the javascript

var url="urlofServlet";
var para="parmeter1=value1&parameter2=valu2;
myxmlhttpobj.open("POST",url,true);
myxmlhttpobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myxmlhttpobj.setRequestHeader("Content-length", para.length);
myxmlhttpobj.setRequestHeader("Connection", "close");
myxmlhttpobj.onreadystatechange=ajaxComplete;
myxmlhttpobj.send(para);

At the server you need to process the result and sent it back as string:

PrintWriter out=response.getWriter();

///Process the input

Write the out put

out.println(outputAsString);

When the request comes back the myxmlhttpobj.onreadystatechange=ajaxComplete; will be called

function ajaxComplete(){


    if(myxmlhttpobj.readyState==4){

      ///Display the result on the HTML/JSP Page 

    }
}

That should help...

Also have a look at jQuery Ajax API.