I build the JSON Object like this:
var key = //some calculated key
var key = //some calculated value
var list = {item: []};
list.item.push({
"key" : key,
"value" : value
});
Then I send the array like this:
sendData = function() {
$.ajax({
url :'<html:rewrite action="/sendData"/>',
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data : {"list":list.item},
success:function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error");
}
});
}
How can I retrieve in my action the JSONArray/JSONObject and handle it?
I've tried this:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String list = request.getParameter("list"); //null, I supposed to find a string formatted like json
return null;
}
Even GSON library is allowed!
You will get significant improvement if you convert your object to string when sending it as parameter.
data : {list: JSON.stringify(list.item)}
Related
My Ajax code looks like this
$.ajax({
type : 'post',
url : url,
async : false,
data: {'txToClose': '1234,5678','sno':'0195'},
contentType : "application/x-www-form-urlencoded; charset=utf-8",
dataType : "json",
success : function(result,status,xhr){
console.log(result);
}
});
The txToClose value 1234,5678 will be coming from a textbox as comma separated string. The user will type them as comma separated.
Im trying to receive them in controller as
#PostMapping("/txToClose")
public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response) throws BBException
{
logger.info("Called txToClose controller");
ResultDto resultDto = new ResultDto();
String txToClose= request.getParameter("txToClose");
String sno= request.getParameter("sno");
logger.info("Transactions to close :"+txToClose+", Serial Num :"+sno);
}
Output is
Transactions to close :null, Serial Num :null
What am I missing here?
You're posting your data as request body, which of course using request.getParameter() will give you null. getParameter() was used to retrieve value from URL parameter.
I'm not quite experience with SpringMVC but try to change your method parameter into
public ResultDto txToClose(#RequestBody ResultDto resultDto ) throws BBException
{
logger.info("Called txToClose controller");
String txToClose= resultDto.getTxtToClose();
String sno= resultDto.getSno();
logger.info("Transactions to close :"+txToClose+", Serial Num :"+sno);
}
I assume your ResultDto is same as your JSON format.
remove the line
contentType : "text/plain; charset=utf-8",
or use default contentType
contentType : "application/x-www-form-urlencoded; charset=utf-8",
It should work.
I solved the issue by adding #RequestBody ObjectNode json in the signature.
public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response,#RequestBody ObjectNode json) throws BBException
{
logger.info("Called txToClosecontroller");
ResultDto result = new ResultDto();
String txToClose= json.get("txToClose").asText();
}
Client side I have:
keyList = ["560", "565", "566"]
I need to send it to server with POST request.
So, I decided to use JSON.
var jsonString= {keyList:JSON.stringify(keyList)};
$.ajax({
type: 'POST',
url: url,
data: {"keyList":jsonString},
dataType: "json"
});
Server side I done:
#RequestMapping(value = "/Controller/parsingJSON", method = RequestMethod.POST)
public void parsingJSON(#RequestParam("keyList") String keyList, HttpServletResponse response, HttpServletRequest request){
List<String> listRes= new ArrayList<String>(Arrays.asList(keyList.split(",")));
System.out.println(listRes);
}
listRes = [["560", "565", "566"]]
If I print the first element I get ["560"
I need the listRes was ["560", "565", "566"] and not [["560", "565", "566"]].
If you send JSON string as parameter to keyList, you should do it like this
$.ajax({
type: 'POST',
url: url,
data: {"keyList":JSON.stringify(keyList)},
dataType: "json"
});
On the server you will get a JSON string, and if you want to deserialize it to object you should manually parse this string.
I have a Spring MVC controller that I am calling via JQuery.ajax.
The mapping in the controller is:
#RequestMapping(value = "/remove", method = RequestMethod.POST)
#ResponseBody
public void remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
}
The ajax call is:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
The POST call completes successfully with HTTP status 200. However, in the Firefox console the following is output:
no element found ... myscript.js:1
If I change my controller to return a boolean then this error disappears. However, according to this question having #ResponseBody on a method with void return type is valid.
Is there anything I can change to remove this message?
As described in the JQuery Bugs and in Firefox Bug, it is a Firefox problem that occurs when response entity body is null.
To fix it, you have to return such a ResponseEntity in your Controller method.
Try to add dataType: 'text' in your request:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
dataType: 'text',
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
and modify your Controller to return a ResponseEntity with a String as first parameter
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public ResponseEntity<String> remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
return new ResponseEntity<String>("OK!!!",HttpStatus.NO_CONTENT);
}
The test looks like this :
#Test
public void testSave() throws Exception {
request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
request.setContentType("application/json");
// request.setMethod("post");
ActionProxy proxy = getActionProxy("/save");
actions.MyAction myAct = (actions.MyAction) proxy.getAction();
String result = proxy.execute();
System.out.println("test id : " + myAct.getId());
System.out.println("test name : " + myAct.getName());
assertEquals("success", result);
System.out.println(response.getContentAsString());
}
I'm trying to post a JSON to a struts2 action and I'm getting :
test id : null
test name : null
Although, if I try the same using a JSP :
test.jsp
<script>
var data = '{"id":"1","name":"nitin"}';
$.ajax({
url: "http://localhost:8084/Struts2Junit4/save",
data: data, //returns all cells' data
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function(res) {
console.log(res);
}
});
</script>
I get both the parameters.
I think I'm missing something in writing the test-case. Please help.
The JSONInterceptor looks for the content-type header that is why you need to use request.addHeader instead of request.setContentType.
request.setContent("{\"id\":\"1\",\"name\":\"nitin\"}".getBytes());
request.addHeader("Content-Type", "application/json");
I have an extjs form from which I am trying to post parameter using Ext.Ajax.request to the servlet. Call is working and servlet is being called but for some reason parameter's value isn't being send. I'll post my code, can anyone tell me what I am doing wrong. Thanks in advance.
This is the call from ExtJS form:
buttons: [{
text: 'Search',
handler: function(){
var fName = Ext.getCmp("fName").getValue();
Ext.Ajax.request({
url : 'LookUPCustomer',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
params : fName, // this value isn't being passed to servlet
success: function ( result, request ) {
var resultData1 = JSON.parse(result.responseText);
},
failure: function ( result, request ) {
resultData = JSON.parse(xmlhttp.responseText);
}
});
}];
and here is servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// value of fName is null, not being passed from the form
String fName = request.getParameter("fName");
// does some processing....
// print back to the form
response.setContentType("application/json");
out.println(jsArray);
}
The params parameter should be a JSON object with key, value pairs. Here's an example:
params: {
firstName: 'Jeff',
lastName: 'Tester'
}
or to plug in your variable
params: { fName: fName }
As you said, u are using extjs 4.0.7. it uses extraparams.
So you need to code like below
Before sending just validate whether fName contain required value.
Ext.Ajax.request({
url : <URL>,
method: 'POST',
extraParams :{ fName : fName },
success: function ( result, request ) {
var resultData1 = JSON.parse(result.responseText);
},
failure: function ( result, request ) {
resultData = JSON.parse(xmlhttp.responseText);
}
});
Thanks