PDA

View Full Version : XMlHttpRequest to a servlet


nalin
07-02-2009, 09:09 PM
Hi My client code is trying to communicate with a servlet and sending data in json format.

Client code :

var myJSONObject = {"name":"hello","address":"xyz"};

var toServer = myJSONObject.toJSONString();
var request=new XMLHttpRequest();
request.open("POST", "http://localhost:8080/User/UserRegistration", true);
request.send(toServer);
return true;
}
catch(err)
{
alert(err.message);
}
}

Servlet Code :

public class UserRegistration extends HttpServlet {
@Override
public void doGet(
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String output = request.getParameter("toServer");
System.out.println(output);}}

The data recieved at the servlet is always null..Can someone explain me the reason behind this?

ckeyrouz
07-02-2009, 09:53 PM
I have been through this problem and I have solved it this way:
InputStream is = request.getInputStream();
byte[] charr = new byte[is.available()];
is.read(charr);
String t = new String(charr,"UTF-8");

nalin
07-02-2009, 11:04 PM
thanks...but this doesn't seem to work for me..I am just getting a blank string on the servlet instead of a null.. :(

ckeyrouz
07-03-2009, 10:21 PM
In this case I think that the problem is in your function toJSONString().
Try alerting the value of toServer to see what it is returning a value.

if the value is empty or null then the problem is there.

nalin
07-04-2009, 08:24 PM
i have tried sending hard coded strings also....

like

var toServer="Hello";

But again..i get a blank string at the server

ckeyrouz
07-05-2009, 08:05 AM
I want you to try something and that to make the call synchronous by doing the following:
request.open("POST", "http://localhost:8080/User/UserRegistration", false);
instead of
request.open("POST", "http://localhost:8080/User/UserRegistration", true);

By the way what browser you are using?