my data:
var test = {cars : []};
var cars = []
cars.push({
"name" : "Ford",
"year" : "2000"
});
cars.push({
"name" : "Audi",
"year" : "2002"
});
test.cars = cars;
var json = JSON.stringify(test);
$.get('/myservlet/', json, function(data) { // also tried .getJSON , .post
alert('Success');
})
In Java I get the "json" variable as parameter key, but no value.
public void doPost(...) // TRIED BOTH
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
for(Object a : req.getParameterMap().keySet()) {
System.out.println(a + " - " + req.getParameter((String)a));
}
//prints out
{"cars":[{"name":"Ford","year":"30"},{"name":"Audi","year":"2002"}]} -
This is unusable result, because the key is always changing, and is ridiculous to for-loop the params everytime. I need to have a specific key : req.getParameter("cars")
Change it to:
$.get('/myservlet/', 'cars='+ json, function(data) { // also tried .getJSON , .post
alert('Success');
You shouldn't have stringified the JSON at all. The whole JSON object test is supposed to be treated as the request parameter map. Just pass the JSON object unmodified.
$.get('/myservlet/', test, function(data) {
// ...
});
This way it's available in the servlet as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("cars[" + i + "][name]");
if (name == null) break;
String year = request.getParameter("cars[" + i + "][year]");
// ...
}
Update
Your question could be possible duplicate of
READ JSON String in servlet
Previous answer
I assume you are trying to post JSON to the servlet, if thats the case read on.
You would have to check for request body instead of request parameter. Something like
BufferedReader buff = req.getReader();
Check if this works for you
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
BufferedReader buff = req.getReader();
char[] buf = new char[4 * 1024]; // 4 KB char buffer
int len;
while ((len = reader.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, len);
}
}
Note that I have checked the above code for syntax errors. I hope you get the idea.
Related
I have list and return from controller and i'm trying to show in a mvc view using jquery each loop function.I can get to list and send to view but when jquery loop start i cannot get index and value.I checked Console and Sources,values are there.
This is my controller codes
public JsonResult electric()
{
int id = Convert.ToInt32(Session["id"]);
string cs = "data source=LNPC;initial catalog=db;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework";
SqlConnection connection = new SqlConnection(cs);
SqlCommand command = new SqlCommand("electrcic_bills", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<analiz> TestList = new List<analiz>();
analiz electric;
while (reader.Read())
{
electric= new analiz();
electric.jan= Convert.ToDouble(reader["jan"].ToString());
electric.feb= Convert.ToDouble(reader["feb"].ToString());
electric.march= Convert.ToDouble(reader["march"].ToString());
electric.april = Convert.ToDouble(reader["april"].ToString());
TestList.Add(electric);
}
return Json(new { List = TestList }, JsonRequestBehavior.AllowGet);
}
Jquery codes
$("#electric").click(function () {
$("canvas#myCharts").remove();
$("#canvas1").append('<canvas id="myCharts" width="200" height="200"></canvas>');
$.ajax({
type: "GET",
url: "/MainController/electric",
dataType: "json",
success: function (List) {
var data = List.List;
$.each(data, function (index, value) {
alert(data);
});
},
});
});
With this method i cannot get value but when i write electric.push(List.List[0].jan._bills_electric) like this i can get value manualy perfctly.
This my Source codes from browser
Local List:List: Array(1)
0:
jan_bills: null
jan_bills_electric: 135
dec_bills: null
dec_bills_electric: 60
You are using List word in your return Json() statement. This may be ambiguous for Java.
Try using another name with camel case typography to solve the problem.
In your Javascript, try to use
var data = List["List"];
instead of
var data = List.List;
Okey i found my answer and where l am wrong.
First- there is nothing wrong in my controller
Second- in each loop function,my array not only array,it is array in OBJECT.I've found this link and try each loop in a each loop and i got my items from jquery loop.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});
I am making an application which would be able to count the numbers written in formulas. In html I have put this:
<input type="text" size="20" id="number2" onblur="validate2()"
onFocus = "document.getElementById('msg2').innerHTML = ' '">
<br>
<div id = "message1"> </div>
I have created a javascript which is firstly validating the datas and later inserts them into the 'answer-formula':
function validate2() {
var idField2 = document.getElementById("number2");
var data2 = "number2=" + encodeURIComponent(idField2.value);
if (typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Validator"
req.open("GET", url, true);
req.onreadystatechange = inserter2
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
;
req.send(data2);
}
function inserter2() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg1 = req.responseText
if (msg1 == "") {
document.getElementById("message1").innerHTML = "<div style=\"color:red\">Zła nazwa</div>";
document.getElementById("org").value = ''
}
else
document.getElementById("org").value = msg2
}
}
}
And here's my code in which is sending it as doGet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("GET");
response.setContentType("text/html");
Writer out = response.getWriter();
String num2 = request.getParameter("number2");
System.out.println(num2);
String org = new String();
if(num2.matches("[\\p{Punct}\\d]+")) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
org = engine.eval(num2).toString() + " (" + request.getMethod() + ")";
} catch (Exception e) {
e.printStackTrace();
}
}
out.write(org != null ? org : "");
}
If we change all these things into the Post, this code will work, but now as it is with GET, it doesn't work at all. Another strange situation is that the formula with POST can read the written things in formula, but as we are using GET, the program see formula source as null.
If you send it as get, you need to put formula into request. This expression:
req.send(data2);
doesn't make sense when you send GET request, as GET request cannot contain any payload except in request string. So you have to add payload to your url. Something like this:
var url = "Validator/?" + data2;
req.open("GET", url, true);
req.onreadystatechange = inserter2;
req.send();
Hope that helps.
Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String s = request.getAttribute("stopName").toString();
response.getWriter().write(s);
}
Ajax Code
function makeRequest(i) {
var stopName = document.getElementById('newStopName' + i).value;
var Longitude = document.getElementById('newLongitude' + i).value;
var Latitude = document.getElementById('newLatitude' + i).value;
var Description = document.getElementById('newStopDesc' + i).value;
document.getElementById('hidnewStopName' + i).value = stopName;
document.getElementById('hidnewLongitude' + i).value = Longitude;
document.getElementById('hidnewLatitude' + i).value = Latitude;
document.getElementById('hidnewStopDesc' + i).value = Description;
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("GET", "Edit_Route", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send("stopName="+encodeURIComponent(stopName));
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState === 4) {
if (xmlHttpRequest.status === 200) {
alert(xmlHttpRequest.responseText);
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
i want send StopName and and again send to client using ajax please help me using javascript not jquery.Actually i want send data and save it to database that s way i want test it
I think this might be come because u have get parameter in wrong way.
String stopName = request.getParameter("stopName") != null ? request.getParameter("stopName").toString() : "null value";
it will also handle the null condition.
try this code.
Is the servlet path correct in ajax code ?
I mean "/Edit_Route" not "Edit_Route"
Maybe the ajax can not found your servlet ,i think
I am building web application using jsp and servlet, I send ajax request from jsp and I want to return two json objects from servlet. I tried to do the following but the code did not work.
// in jquery I wrote this code
var id = $(this).attr('id');
var paramenters = {"param":id};
$.getJSON("MyServlet", paramenters, function (data1,data2){
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
// in the servlet I wrote this code
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json1);
response.getWriter().write(json2);
can someone help me???
You should do it like this:
Server side:
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
response.getWriter().write(bothJson);
Client side:
$.getJSON("MyServlet", paramenters, function (data){
var data1=data[0], data2=data[1]; //We get both data1 and data2 from the array
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
Hope this helps. Cheers
Wrap them in JSON array:
[ {..}, {..}, {..}]
or, wrap them in another object:
{ "result1":{..}, "result2":{..} }
You could return a JSON array with both objects as elements of the array. Have your servlet return JSON that has a structure like this one:
[{"name": "object1"}, {"name": "object2"}]
Then your javascript code can be something like this:
$.getJSON("MyServlet", paramenters, function (data){
var data1 = data[0];
var data2 = data[1];
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
you're going to need to put both into a single json string like so
response.getWriter().write("[");
response.getWriter().write(json1);
response.getWriter().write(",");
response.getWriter().write(json2);
response.getWriter().write("]");
this puts them in a json array
you could also put them in a json object
response.getWriter().write("{\"object1\":");
response.getWriter().write(json1);
response.getWriter().write(",\"object2\":");
response.getWriter().write(json2);
response.getWriter().write("}");
#Edgar 's answer works for me. But I think we should avoid to form the array by ourselves, so I suggest to use a list. The codes will be something like this:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
...
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
ArrayList<Object> obj_arr = new ArrayList<Object>();
obj_arr.add(obj1);
obj_arr.add(obj2);
Gson gson = new Gson();
String tmp = gson.toJson(obj_arr);
resp.getWriter().write(tmp);
}
And in the front end, for the data we get, we can use data[0] to retrive obj1 and data[1] to retrive obj2. The codes will be something like this (I am using ajax here):
$('#facts_form').submit(function (e) {
e.preventDefault();
var data = new FormData(this);
var url = 'import';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false,
async: false,
cache: false,
success: function (data) {
for (var i = 1; i < data.length; i++){
//do whatever
}
},
error: function (xhr, status, error) {
alert(status + "\n" + error);
}
});
});
I have an HttpUriRequest instance, is there a way to print all the parameters it contains? For example, I can almost get them like:
HttpUriRequest req = ...;
HttpParams params = req.getParams();
for (int i = 0; i < params.size(); i++) { // ?
println(params.getParam(i); // ?
}
Is there a way to do this?
Thanks
You can simply iterate over all Header fields.
HttpUriRequest req = ...;
.......
Header[] headerFields = request.getAllHeaders();
for(int e = 0; e<header.length; e++){
System.out.println(headerFields[e].getName() + ": " + headerFields[e].getValue());
}
The suggested method params.toString() does not work.
Are you looking for the HTTP parameters or the URI parameters?
The HTTP parameters are things like user-agent, socket buffer size, protocol version, etc.
The URI parameters are the client values that get passed as part of the request, e.g.
?param1=value1¶m2=value2
If you're looking for the URI parameters, try something like this:
List<String> uriParams = Arrays.asList(request.getURI().getQuery().split("&"));
But if you do want the raw HTTP params, it's a little more complicated because not all implementations of HttpParams supports getNames(). You'd have to do something like this:
HttpParamsNames params = (HttpParamsNames)request.getParams();
Set<String> names;
if (params instanceof ClientParamsStack) {
names = new HashSet<>();
// Sorted by priority, see ClientParamsStack
ClientParamsStack cps = (ClientParamsStack)params;
if (cps.getApplicationParams() != null) {
names.addAll(((HttpParamsNames)cps.getApplicationParams()).getNames());
}
if (cps.getClientParams() != null) {
names.addAll(((HttpParamsNames)cps.getClientParams()).getNames());
}
if (cps.getRequestParams() != null) {
names.addAll(((HttpParamsNames)cps.getRequestParams()).getNames());
}
if (cps.getOverrideParams() != null) {
names.addAll(((HttpParamsNames)cps.getOverrideParams()).getNames());
}
} else {
names = params.getNames();
}
for (String name : names) {
System.out.println(name + ": " + request.getParams().getParameter(name));
}
HttpUriRequest extends HttpMessage, which has getAllHeaders(), getParams() etc.
Take a look here: http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/index.html, search for HttpMessage
You could create a work around by casting it to BasicHttpParams object.
BasicHttpParams basicParams = (BasicHttpParams) params;
This give you access to getNames() which contains a HashSet<String> of the parameters
You can then iterate through it printing out the parameter name alongside it's value.
See
https://stackoverflow.com/a/57600124/5622596
for possible solution