How to decode the special characters sent from the url in Java? - java

I am sending the the value from my jsp to my servlet in url parsing.
The value contains the special character (), but when I am receiving the value it is &#40 and &#41.
How to decode this back to ()?
jsp code
var devicename=document.getElementById('s_loc_1').value;
var param=devicename;
param=encodeURIComponent(devicename);
var updatedevsaturl="http://"+window.location.host+"/services/PCEquipmentDevice?productid={}&action=updatePCDeviceStatus&reqby={}&param="+param;
var productId=document.getElementById('pid').value;
updatedevsaturl=sustituteParameter(updatedevsaturl,productId);
updatedevsaturl=sustituteParameter(updatedevsaturl,userUpi);
alert(updatedevsaturl);
$.ajax({
type : "GET",
timeout:20000,
url : updatedevsaturl,
async: false,
dataType : "xml",
success: function(data) { }, error: function (xhr, ajaxOptions, thrownError) {
alert('Service Unavailable - VPU List');
}
});
java code to decode
if(action.equals("updatePCDeviceStatus")){
System.out.println("param: "+param);
//String decodeparam3 = new String(param.getBytes("UTF-8"),"ASCII");
//String decodeparam3 =URLDecoder.decode(param, "UTF-8");
String decodeparam3= URLDecoder.decode(param, "ISO-8859-1");
System.out.println("decodeparam132 "+ decodeparam3);
I tried all the ways give on net but didnt workenter code here
input at jsp 2-in-1 Laptop (12.5 inches)
output at servlet 2-in-1 Laptop &#4012.5 inches&#41

This is ASCII code for "(". Look at this answer Java: How to unescape HTML character entities in Java? . You have to create a char from that html entity.

Related

Receive JSON Array response from Java servlet in UTF-8 charset

I am doing an ajax call to the java servlet. The servlet responds with a JSON Array with a charset set to UTF-8. However, once I get a response in the AJAX call, I get ??? characters in my strings. I went through a lot of testing and research and could not find a possible solution.
AJAX CALL:
$.ajax({
type: 'POST',
data: {curTableName: curTableName,curTableID: curTableID},
dataType: 'json',
url: '../ShowProducts',
success: function(productInfo){
var noOfProducts = productInfo.length;
for(var i = 0; i < noOfProducts; i++)
{
product.push(productInfo[i].product.substr(0,25) + "...");
webshop.push(productInfo[i].webshop);
price.push(productInfo[i].price);
availability.push(productInfo[i].availability);
lastChecked.push(productInfo[i].lastChecked);
checkFreq.push(productInfo[i].checkFreq);
url.push(productInfo[i].url);
DisplayProductInfo(product[i],webshop[i],price[i],availability[i],lastChecked[i],checkFreq[i],url[i]);
}
}
});
And my Java Servlet Response:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonArr.toString());
Based on my own research the java servlet seems to be correct, and maybe there is an issue with the javascript. Anybody has any good ideas. All help is greatly appreciated. :)
I have managed to get it work. The problem resided in the fact that the JSON needed to be encoded in the servlet, and decoded in the javascript. Thank you - isah.
CODE CHANGES:
AJAX CALL:
$.ajax({
type: 'POST',
data: {curTableName: curTableName,curTableID: curTableID},
dataType: 'json',
url: '../ShowProducts',
success: function(productInfo){
var noOfProducts = productInfo.length;
for(var i = 0; i < noOfProducts; i++)
{
productInfo[i].product = decodeURIComponent(productInfo[i].product);
productInfo[i].product = productInfo[i].product.replace(/\+/g, ' ');
product.push(productInfo[i].product.substr(0,25) + "...");
webshop.push(productInfo[i].webshop);
price.push(productInfo[i].price);
availability.push(productInfo[i].availability);
lastChecked.push(productInfo[i].lastChecked);
checkFreq.push(productInfo[i].checkFreq);
url.push(productInfo[i].url);
DisplayProductInfo(product[i],webshop[i],price[i],availability[i],lastChecked[i],checkFreq[i],url[i]);
}
}
});
JAVA SERVLET:
productSplit[0] = URLEncoder.encode( productSplit[0], "UTF-8");
Additional line has been added to Java servlet. Now the title gets encoded, and only after that it goes to the JSON object.

Jquery unescape response text from java servlet not working properly

java code
pResponse.setHeader("content-type", "text/plain;chartset=UTF-8");
pResponse.setContentLength(resultsJson.length());
Writer out = pResponse.getWriter();
String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
out.write(escapedJsonString);
The purpose to escape the return text is because there are some accented character in 'resultsJson' and even though I set charset=UTF-8, I still get garbled text from ajax. check this question from me ajax garbled text
ajax code
var option = {
type : 'POST',
url : $('#csrOrderExportform').attr('action'),
data : $('#csrOrderExportform').serialize(),
beforeSend : preAjaxReqest,
dataType:'text',
error : function(data, statustext, error){
$(".searchSubmitBtn").removeAttr("disabled");
setErrorMessage('No Records Found!');
},
success : function(data){
if (data) {
alert(unescape(data));}
}
};
$.ajax(option);
response text
[{\"orderNumber\":\"S301020000\",\"customerFirstName\":\"\u5F20\u79D1\",\"customerLastName\":\"\u5F20\u79D1\",\"orderStatus\":\"PENDING_FULFILLMENT_REQUEST\",\"orderSubmittedDate\":\"May 13, 2015 1:41:28 PM\"}]
after unescape the text from jquery, I am getting the same text.
expected output
[{"orderNumber":"S301020000","customerFirstName":"张科","customerLastName":"张科","orderStatus":"PENDING_FULFILLMENT_REQUEST","orderSubmittedDate":"May 13, 2015 1:41:28 PM"}]
This should work:-
pResponse.setContentType("application/json");
pResponse.setContentLength(resultsJson.length());
Writer out = pResponse.getWriter();
String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
out.println(escapedJsonString);

ajax POST cannot send data to servelet

I am working on a simple tomcat web application. The client side just send the username data in json to server side and server side return if this username is already registered.
Here is my code.
ajax part:
var udata = new Array();
udata.push({ name: uname});
$.ajax({
url: '/TestProj/Controller?action=checkuname',
type: 'POST',
dataType: 'json',
data: udata,
//contentType:'application/json, charset=utf-8',
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
servlet part:
I am using a controller to dispatch the request to checkname servlet.
String username = request.getParameter("name");
if (checkuser(username)){
status = "false";
}else{
status = "true";
}
response.setContentType("application/json");
PrintWriter o = response.getWriter();
o.println("{\"status\":\""+status+"\"}");
//o.println("{\"status\":\""+username+"\"}");
I try print out the content of "status" and "username", but they are both null. Does it mean that I did not successfully send out the data via ajax to servlet. I may mess up the json data part.
Any help will be appreciated.
Updated:
I change the ajax part to this and it works. Can someone let me know how to do it in the json way?
ajax part:
var udata = new Array();
udata.push({ name: uname});
$.ajax({
url: '/TestProj/Controller?action=checkuname&uname='+uname,
type: 'POST',
dataType: 'json',
data: udata,
//contentType:'application/json, charset=utf-8',
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
It doesn't really make sense to use a JSON object for such a simple thing as posting a username to a servlet. Just use a simple request parameter and save yourself a lot of trouble. But if you must do it with JSON, there are a few problems you'll need to resolve.
Unless you're handling multiple users at the same time, a javascript array is not a good choice of data type. A simple object would be better.
var udata = {name: uname};
Your post data should be a string, not a javascript object (array or otherwise). Use JSON.stringify() as in your error function.
$.ajax({
url: '/TestProj/Controller',
type: 'POST',
dataType: 'json',
data: 'action=checkuname&jsonObject=' + JSON.stringify(udata),
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
However, udata is such a simple javascript object that you might as well stringify it yourself, as the native JSON object is not going to be available in older browsers.
var udata = '{name:"'+uname+'"}';
$.ajax({
url: '/TestProj/Controller',
type: 'POST',
dataType: 'json',
data: 'action=checkuname&jsonObject=' + uname,
success: function(data){
checkstatus = data.status;
},
error: function(x,y,z){ console.log(JSON.stringify(x)); }
});
Also, although it may boil down to personal preference, the action parameter is better off in the post body rather in the query string. This is a post, after all.
request.getParameter() is not going to help you inspect a JSON string. It can only get the value of request parameters. So
String json = request.getParameter("jsonObject")
// this variable will have a value like "{name: 'somedude'}"
You'll need to parse this JSON string on the server. You could try to do this yourself with String methods, by a library like Gson is a much better option. You could obtain the username value like this:
String username = (String)(new Gson().fromJson(json, Map.class).get("name"));

how to read parsed json data in ajax success call

On Ajax success call, I'm getting already parsed data in JSON format from a Controller.
I want to read that data, so while I'm doing below one, I am getting undefined as an error.
How can I solve this?
success : function(response) {
alert(response.operatorId);
},
Here is an example of working code
success: function(json) {
console.log(JSON.stringify(json.topics));
$.each(json.topics, function(idx, topic){
$("#nav").html('' + topic.link_text + "");
});
}
It appears that the response coming into success function is not a JSON object. COuld you check if you have following set in your ajax call.
dataType: 'json',
contentType : 'application/json'
Alternatively, you may use the following to parse the json string to json object and then use dot notation to access the properties
success : function(response) {
var jsonData = $.parseJSON(response)
alert(jsonData.operatorId);
},

How do I get all values in a JIRA multi-checkbox customfield with SOAP?

I'm developing a web application that uses SOAP to communicate with JIRA. I have a custom field that contains several checkboxes, and I can get this field through SOAP, but I can't get to the actual checkboxes it contains. Is there a way to do this?
Since nobody has answered this so far, here is an old copy of some JavaScript I did for JIRA, reading customfields.
var unitlist_val = $("#unitList_0").val();
var errorlist_val = $("#errorList_0").val();
var larmlist_val = $("#larmList_0").val();
var URL= ""+jira+"/sr/jira.issueviews:searchrequest-xml/temp/SearchRequest.xml jqlQuery=project+%3D+"+problem+
"+AND+%22Symptom+1+-+Component%22+~+%22+"+unitlist_val+"%22+AND+%22Symptom+2+-+State%22+~+%22"+errorlist_val+
"%22+AND+%22Symptom+3+-+alarm%22+~+%22"+larmlist_val+
"%22&tempMax=1000&field=title&field=link&field=customfield_10422&field=customfield_10423&field=customfield_10424&field=customfield_10420&field=resolution&field=customfield_10440";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
cache: false,
beforeSend: function(request) {
request.setRequestHeader("Accept", "text/xml; charset=utf-8");
},
success: function(data){
$(data).find("item").each(function(){
// Make sure swedish chars, are handled properly. Append to page first, then get value.
var unitList = $("<div/>").html($(this).find("#customfield_10422 customfieldvalue").text()).text().split(",");
var errorList = $("<div/>").html($(this).find("#customfield_10423 customfieldvalue").text()).text().split(",");
var alarmList = $("<div/>").html($(this).find("#customfield_10424 customfieldvalue").text()).text().split(",");
var knownerror = $("<div/>").html($(this).find("#customfield_10420 customfieldvalue").text()).text() || "None";
var resolution = $("<div/>").html($(this).find("resolution").text()).text() || "None";
}
});
You can probably do something similar in Java and use a simple GET request. I cut out quite a lot of code, so some parts might be syntax error on.

Categories

Resources