I am using an Android client to post data and some file in Google cloud storage:
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody("file", file);
entityBuilder.addTextBody("author", author);
On the server side I am using a servlet to get that request.
However, while I am able to get the file and store it, I don't know how to get what's in the addTextBody (the "author" String in my case)
I have been searching for a while and just found someone that posted quite the same question but no one answered him. (How to get the text from a addTextBody in a miltipartentitybuilder)
Assuming you're using Servlet 3.0+, just use HttpServletRequest#getParts(). For example, if you wanted the content of the multipart part named author, you'd configure your servlet with #MultipartConfig, retrieve the appropriate Part object and consume its InputStream.
#MultipartConfig()
#WebServlet(urlPatterns = { "/upload" })
public class UploadServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
if (!part.getName().equals("author"))
continue;
try (InputStream in = part.getInputStream()){
String content = CharStreams.toString(new InputStreamReader(in));
System.out.println(content); // prints the value of author
}
}
}
}
I created InformationServlet that whenever I need some details I can send it what I want (with AJAX) and it will return me the information.
I searched how to do it on Ajax and according to:
How to send parameter to a servlet using Ajax Call
I used: url: "InformationServlet?param=numberOfPlayers"
But on the servlet the request's attributes doesn't contain the parameter I sent so I suppose I am not doing it correctly:
you can see that the attributes size is zero
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new Gson();
Engine engine = (Engine)getServletContext().getAttribute("engine");
String responseJson = "";
if(request.getAttribute("numberOfPlayers") != null)
{
String numberOfPlayers = "";
numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
responseJson = numberOfPlayers;
}
out.print(responseJson);
} finally {
out.close();
}
}
JavaScript (AJAX request):
function getNumberOfPlayersAndPrintSoldiers()
{
$.ajax({
url: "InformationServlet?param=numberOfPlayers",
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(numberOfPlayers) {
var r = numberOfPlayers;
}
});
}
Edit:
you probably want to use getParameter and not getAttribute
Moreover, please pay attention to the order of parameter name and his value:
request.getParameter("param");
instad of:
request.getParameter("numberOfPlayers");
because the url form contains parameter name first and then the parameter value. for example:
myurl.html?param=17
and if more parameters needed then use the separator & sign
myurl.html?firstName=bob&age=5
Here is my AJAX code which triggers the Servlet 'CalculateLace'
laceTd.dblclick(function() {
var jsonObj= { jsonObj: [ {"rowID": $(nRow).attr('id')} ]};
$.ajax({
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
traditional: true,
url: "CalculateLace"
});
});
And here is my Java Servlet code:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String id = req.getParameter("rowId");
//do something
}
But I keep getting String id as null. I also tried
String id = req.getParameter("id");
but to no avail. What am I doing wrong here?
Try this way -
var jsonObj= {"rowId": $(nRow).attr('id')};
and get rowID in your servlet this way - You can get library to parse your json here JSON.org
req.getParameter("rowId");
I pass parameters to the server line
"login=testAva4&nick=testAvaNick&social=vk&saurl=http://domain.example?param1=1¶m2=2¶m3=3&maurl=1"
waiting as the value saurl="http://domain.example?param1=1¶m2=2¶m3=3"
but i get http://domain.example?param1=1 and param2=2 param3=3
From Eclipse debug
req->_parameters
{maurl=1, nick=testAvaNick, param2=2, saurl=http://domain.example?param1=1, param3=3, social=vk, login=testAva4}
Gets the parameters in the code like this:
public class AddProfileServlet extends PlacerServlet {
//Add new profile method
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//Receive variables from URL
String login = req.getParameter("login");
String nick = req.getParameter("nick");
String social = req.getParameter("social");
String saurl = req.getParameter("saurl");
You should use URLEncoding on the saurl parameter.
Look at URLCodec at the commons codec enter link description here project.
I don't think you will need to encode the entire parameters part, but just the value for this specific parameter.
You can encode a string using:
URLCodec codec = new URLCodec();
String encodedValue = codec.encode(valueToEncode);
And you should use encodedValue as the value passed to the saurl parameter.
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:
var myData = { "gameID" : gameID,
"nrOfPlayers" : 2,
"playerUIDs" : [123, 124]
};
The Question I have is exactly what is the correct way (or best way, style wise) to parse this in a Java servlet (using GSON for example)? First I send this JSON to the server using jQuery ajax method like this:
jQuery.ajax({
url : path,
data : myData,
success : successFunction,
error : function(data) {
console.log("Error: ", data);
} ,
type : "post",
timeout : 30000
});
Now in the servlet I've learned that I should have been able to parse that JSON like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
String gameID = gson.fromJson(request.getParameter("gameID"), String.class);
String nrOfPlayers = gson.fromJson(request.getParameter("nrOfPlayers"), String.class);
String[] playerUIDs = gson.fromJson(request.getParameter("playerUIDs"), String[].class);
log.info(gameID);
log.info(nrOfPlayers);
log.info(playerUIDs[0] +" "+ playerUIDs[1]);
}
But the playerUIDs variable IS NULL and of course playerUIDs[0] throws an exception!
Digging deeper I found that when looping over the request parameter names, it contained a parameter named "playerUIDs[]" with the value of only 123 (the first int in the array). This was strange cause I didn't seem to be able to access the next values at all.
Then I read that JSON objects should be stringifyed before POST-ing so I added JSON.stringify(myData), but now the request parameter names only contained ONE name which was the JSON object itself in a stringified state:
INFO: Parameter name = {"gameID":"b6a51aabb8364b04bce676eafde1bc87","nrOfPlayers":2,"playerUIDs":[123,124]}
The only way I seemed to get this to work was by creating a inner class:
class GameStart {
protected String gameID;
protected int nrOfPlayers;
protected int[] playerUIDs;
}
And parsing the JSON from the request parameter name, like this:
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);
}
log.info(start.gameID);
log.info(String.valueOf(start.nrOfPlayers));
log.info(start.playerUIDs[0] +" "+ start.playerUIDs[1]);
}
Now all values are there, but this seems more like a hack (reading JSON from request parameter name) than an elegant solution, so I thought I'd ask you guys what exactly would be the "correct" way of doing this? Am I missing something obvious?
Thanks in advance!
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".
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.
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]);
}
}