I know this is a topic much talked about, but I still wasn\'t able to find a correct and clear answer to my specific problem.
I\'ve got a JSON that looks like this:<
You aren't use JSON to send data to the server:
data : myData,
This specifies parameters as a JavaScript object, but not necessarily as JSON. What this means is that if you do a GET request with:
data: {name1: "value1", name2: "value2"}
The request will be:
http://some/page?name1=value1&name2=value2
This is basically what you're seeing with your first calls, where everything is being converted to a string, then sent as a form parameter.
What you're doing in the second version is almost what you're supposed to do. The only difference is that you need to use a JavaScript object as the parameter to data
, not just a string:
data: {arbitraryNameHere: JSON.stringify(myData)}
This will post your "myData" object as JSON, in the parameter named "arbitraryNameHere".
JSON to the server using jQuery ajax method
function send() {
var myData = {"gameID": 30,
"nrOfPlayers": 2,
"playerUIDs": [123, 124]
};
jQuery.ajax({
url: "servletName",
data: JSON.stringify(myData),
success: function(){
//console.log(JSON.stringify(myData));
},
error: function(data) {
console.log("Error: ", data);
},
type: "post",
timeout: 30000
});
}
Sender Button
<button onclick="send();" id="send">Send</button>
Java servlet processing
public class servletName extends HttpServlet {
class GameStart {
protected String gameID;
protected int nrOfPlayers;
protected int[] playerUIDs;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Gson gson = new Gson();
Enumeration en = request.getParameterNames();
GameStart start = null;
while (en.hasMoreElements()) {
start = gson.fromJson((String) en.nextElement(), GameStart.class);
}
System.out.println(start.gameID);
System.out.println(start.playerUIDs[0] +" "+ start.playerUIDs[1]);
}
}
In the real world you typically wouldn't send an actual json object to a servlet and you won't often handle populating values from a request in most circumstances. JSON is JavaScript object notation - and it's great when consumed for use in client side coding.
It's easier to use query string for params rather than a post with json (which it appears you are actually doing). host/url?gameId=5&nrPlayers=2
As far as how to populate values, convention-over-configuration is the way to go for cleanest code. You can use a frameworks like struts to offload all of the transfer of values onto the framework. Not sure what your whole application looks, your intention for writing (ie writing servlets from scratch is a great way to learn but not common practice in real application development environments) like so this may or may not be a helpful answer.