问题
I have a REST Server in Java JAX-RS and an HTML page.
I want to send a JSON array, a username, and an accountID from the HTML page through an xmlhttp
POST request by making all of them a single big String so I can use the xmthttp.send()
method.
The HTML sending code is:
function sendData() {
var req = createRequest();
var postUrl = "rest/hello/treeData";
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
var accID = "onthespot";
var username = "alex";
req.open("post", postUrl, true);
req.setRequestHeader("Content-type","text/plain");
req.send("data=" + JSON.stringify(dsdata) + "&username=" + username + "&accID=" + accID);
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
And the Server JAX-RS code is:
@Path("/treeData")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String storeTreeData(
@QueryParam("data") String data,
@QueryParam("username") String username,
@QueryParam("accID") String accID) {
System.out.println("Data= " + data + "\nAccID= " + accID + "\nUsername= " + username);
return "Done";
}
The problem is that all the variables are printed as null..
the storeTreeData
function should find the data
, username
, accID
variables through @QueryParam
and store them isn't that right?
Anyone know what's the problem here?
PS:The xmlhttp request is initiallized correctly and the connection is made but the parameters are not passed on the server.
回答1:
What you try to do:
@QueryParam is used to get parameters from the query of the request:
http://example.com/some/path?id=foo&name=bar
In this example id
and name
can be accessed as @QueryParam
.
But you are sending the parameters in the body of your request.
What you should do:
To get the parameters from the body, you should use @FormParam together with application/x-www-form-urlencoded:
@Path("/treeData")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public Response storeTreeData(
@FormParam("data") String data,
@FormParam("username") String username,
@FormParam("accID") String accID) {
// Build a text/plain response from the @FormParams.
StringBuilder sb = new StringBuilder();
sb.append("data=").append(data)
.append("; username=").append(username)
.append("; accId=").append(accID);
// Return 200 OK with text/plain response body.
return Response.ok(sb.toString()).build();
}
Edit:
You should also use
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in your JavaScript code.
来源:https://stackoverflow.com/questions/13344452/jax-rs-and-xmlhttp-communication