I am sendin post request from jquery like this :
$.ajax({
type: "POST",
url: "Save",
data: { conr: conr ,expiry : expiry,settings : settings}
inside servlet , i am able to get parameters (conr , expiry , settings)
but the problem is that
the settings parameter contains serialized form data : like this :
high=true&ci=false&title=qTip+as+Button+Menu&private=true&email=abc#google.com
I know that i can use string tokenizer to get data but i want to make sure that- if their is any simple way or not?
You could use the HttpComponents and let URLEncodedUtils parse it for you.
So you could just invoke URLEncodedUtils.parse(yourString,Charset.forName("UTF-8")) and you receive as return a List<NameValuePair> containing name and value associated elements. In this case something like: hight = "true", title = "qTip as Button Menu" and so on. And this all with the right decoded.
You can also use split on the settings string with "&" as a regex.
Related
I have picked up a legacy project and I am in the process of debugging something.
I have come across a custom JavaScript function (encodeJsonIntoString) which encode URI components for JavaScript object before sending over via AJAX.
The AJAX is nothing fancy:
$.ajax({
url: URL,
method: 'POST',
datatype : 'json',
data : encodeJsonIntoString(myObj),
success: ...
});
There is no custom processData or contentType set in the ajax call. What really puzzle me is why the previous developers didn't let $.ajax's data attribute to convert the JavaScript object automatically into a URI-encoded string or didn't even try using JQuery.param() to do it but to write the whole function themselves.
For a test, I have made a simple object to test the function encodeJsonIntoString:
var testDataA = {
list: [
{
lastname:"Smith",
firstname:"John"
},
{
lastname:"Black",
firstname:"Jack"
},
{
lastname:null,
firstname:"Mary"
}
]
};
After decoding URI components, the result of the function is:
list[0][lastname=Smith&list[0][firstname=John&
list[1][lastname=Black&list[1][firstname=Jack&
list[2][lastname=null&list[2][firstname=Mary
Notice there are lack of closing square brackets(]) in some places and it uses "null" for null values.
If I run JQuery.param() and decode it, I get this:
list[0][lastname]=Smith&list[0][firstname]=John&
list[1][lastname]=Black&list[1][firstname]=Jack&
list[2][lastname]=&list[2][firstname]=Mary
See the difference? But somehow the result of the function is accepted by the server(Java/Spring - #ModelAttribute) and read into the correct list structure.
I don't have access to the server side here, but I wonder if that array syntax is correctly acceptable or is it just "tolerated" by the server? Will the server see both versions of object in the same structure format?
I am tempted to just replace it with JQuery.param() to handle more robust input data in the future which may also accept special characters.
I sent one request as URL with data to servlet, But by default servlet is modifying the data and sending as request. Can you please suggest how to maintain the request URL with data which i passed to servlet should remain same ?
Example:- when i am passing the data to servlet
http://localhost/helloservlet/servlet/ppd.abcd.build.coupons.CouponValueFormatterServlet?dsn=frd_abc_abcde&lang=ENG&val=PRCTXT|12345 &ABCDEFG
when it using the above url in servelt as request , like string abc = request.getParameter("val"), the val attribute is trimmed automatically and assigned as " val=PRCTXT|12345" but it supposed to be like " val = PRCTXT|12345 &ABCDEFG ". Please help me on this.
The servlet interprets each & in the URL as the start of a new parameter. So when it sees &ABCDEFG, it thinks you are sending a new parameter called ABCDEFG with no value (though this is technically a "keyless value" according to the specifications).
Two things to fix this, first is when you want to actually send an &, use %26 instead. This will be skipped by the code that divides up the parameters, but converted to a real & in the parameter's value.
Second is to replace spaces with +. Spaces in URLs work sometimes but can be problematic.
So your actual request URL should look like this:
http://localhost/helloservlet/servlet/ppd.abcd.build.coupons.CouponValueFormatterServlet?dsn=frd_abc_abcde&lang=ENG&val=PRCTXT|12345+%26ABCDEFG
If you're building these parameters in javascript, you can use encodeURIComponent() to fix all problem characters for you. So you could do something like this:
var userInput = *get some input here*
var addr = 'http://www.example.com?param1=' + encodeURIComponent(userInput);
I post to my servlet via AJAX this:
$.ajax({
url: 'myServlet?action=Doeth',
type: 'post',
data: {machine: i, name: txt, status:status}, // i have initilized the values before
success: function (data) {
$('#fep').val(data);
}
});
back in my servlet I have:
if(jspAction.equals("Doeth")){
int status = Integer.parseInt(request.getParameter("status"));
int name = Integer.parseInt(request.getParameter("name"));
String machine = request.getParameter("machine");
//do some stuff and assign in 2 variables
//fep = "a value" and var2="some more"
response.getWriter().write(String.valueOf(fep));
}
So in success the following input is filled with the value fep
<input id="fep" class="form-control" name="fep" required>
If I want to return not only one value but 2 from the servlet (lets say the variable var2, how I do this? I tried
response.getWriter().write(String.valueOf(fep));
response.getWriter().write(String.valueOf(var2));
but it didn't work
A Servlet can't return multiple results. It's function is to handle an HTTP request and produce a single corresponding HTTP response.
If you need to pass data in the response, you need to choose an appropriate format and serialise it. The most common thing you can use, is JSON.
JSON is a text - based data format, that can represent complex objects and data structures. There is also a wide variety of libraries for working with it.
I'm having some troubles with different back-end processing of POST rest calls. I have two different objects which are updated through two different POST methods in my back-end. I catch the objects as a JsonNode, and in order to parse the attributes which I need to update, i create an iterator like so :
final Iterator<String> fieldNames = attributes.fieldNames();
The problem comes when I send my data from angular, in one case I need to explicitly send it like angular.toJson(data) in order to properly grab all the field names, and in the other case I just send the data (without the angular json conversion). Why is this behavior occurring ? Does this have to do with how I create the $http post call ? Here are the two different calls from angular:
$http.post(URL, angular.toJson(data)).success(function(data){
/*whatever*/ }).error(function(data) {
/*whatever*/ });
//Second call looks like this
var promise = $http({method: 'POST', url:URL, data:data, cache:'false'});
//this one i resolve using $q.all
I truncated the code to just the important stuff. My data is created like this currently(tried multiple ways in order to skip the need for toJson):
var data = "{\"Attribute1:\"+"\""+$scope.value1+"\","+
"\"Attribute2:\"+"\""+$scope.value2+"\"}";
How do I need to send the json data in order for it to correctly be converted to a JsonNode in my back-end, so I can properly iterate the fieldNames ?
I did manage to come to a common solution which consumes the json correctly in my back-end. I declared my json objects in angular like this :
$scope.dataToSend = {
"SomeAttribute" : "",
"SomeOtherAttribute" : ""
};
And then added my values like so :
$scope.dataTosend.SomeAttribute = someValue;
$scope.dataTosend.SomeOtherAttribute = someOtherValue;
No longer need to send the data with angular.toJson().
I am not able to parse tje Json object returned from the servlet in ajax,
I need to put json object values in there relative field
From my java code i am sending the below String in the form of JSON
String webVisitorDetails = "{"+"companyName : \""+webVisitor.getCompanyName()+ "\","+
"address : \""+webVisitor.getProfessionalAddress()+ "\","+
"city : \""+webVisitor.getCity()+ "\","+
"zipCode : \""+webVisitor.getZipCode()+ "\","+
"clientId : \""+webVisitor.getCustomerAccountNumber()+ "\"}";
In ajax
$.ajax({
url: "ships",
data: {
email: email.toString()
},
success: function(data) {
$.each(data, function(k, v) {
console.log(k + " Value " + v);
$("#city").text(v.city);
$("#zipcode").text(v.getZipCode);
$("#Adress").text(v.getProfessionalAddress);
});
},
error: function(data) {
console.log("error:", data);
},
type: "post",
datatype:"json",
});
Note that the jQuery setting is dataType with a capital T. To do the JSON parsing manually, use the parseJSON function. However, if you set the Content-Type of your servlet response to application/json, the datatype should be auto-detected.
After you fixed this: Does it work? What is the value of the data argument of your success handler?
console.debug(data);
As Neal already said, JSON parsing expects valid JSON strings starting with jQuery 1.4. You can validate your JSON jsonlint.com.
In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
To avoid the manual building of JSON strings, use something like the JSON-java processor (from iNan's comment) or other Java implementations listed on json.org.
You json string is incorrect
The keys must be surrounded by double quotes.
Read the requirements here
If it's creating a problem because of the single-inverted comma ('), then just do:
jQuery.parseJSON(data.replace(/'/g, '"'))
If that is the case then it should work for you...