Send empty array from ajax to jersey web server - java

I try to send array of integers from ajax to jersey web service.
javascript
var myFoods = [];
// adding items via push
$.ajax({
url: "ws/food/" + idParam + "/recomendation",
type: "POST",
data: {'foods[]': myFoods,
async: false,
});
web service
#POST
#Path("/{id}/recomendation")
public void updateRecomendations(
#PathParam("id")
Long id,
#FormParam("foods[]")
List<Long> recomendedFoodIds
) {
...
}
With non empty arrays this code work good but if myFoods is empty i have error
"HTTP Status 500 - java.lang.IllegalStateException: The #FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded"
How to fix it?

I solved the problem with this:
#POST
#Path("/{id}/recomendation")
public void updateRecomendations(
Form form,
#PathParam("id")
Long id
) {
List<Long> foods = getFoodIdsFromForm(form);
...
}
private List<Long> getFoodIdsFromForm(Form form) {
Map parametrsMap = form.asMap();
final List<Long> foodIds = new ArrayList<Long>();
if (parametrsMap.get("foods[]") != null) {
List<String> idsString = (List<String>)parametrsMap.get("foods[]");
for (String id : idsString) {
foodIds.add(Long.parseLong(id));
}
}
return foodIds;
}

Related

Java Spring: send list from Ajax to Controller

I'm trying to send an array of
this Json data
data using this Ajax in a JSP:
$.ajax({
url: 'agregarSeleccion',
type: 'POST',
dataType:'json',
data: JSON.stringify(lista),
success:function(dataP){
//Successs
error: function (jqXhr) {
swal("Error","","error");
}
});
To this controller in Java (Spring framework):
private List<Seleccion> seleccionados = new ArrayList<Seleccion>();
#RequestMapping("/agregarSeleccion")
#ResponseBody
public List<Seleccion> agregar(Seleccion obj) {
seleccionados.add(obj);
return seleccionados;
}
The "Seleccion" object it's an entity that has some of the attributes of the JSON that I sent from Ajax, the "seleccionados" is a list that saves the array received, but when I send it, the obj param always return a null object and Ajax sends the error function, I think the problem is that I'm sending an array to an Object, but I can't figure how to solve it
Seleccion object model:
public class Seleccion {
private int idProducto;
private String nombre;
private double precio;
private int cantidad;
private double totalParcial;
//Getters and setters
}
Try using ResponseEntity and update you controller like the below snippet;
Test Data
[
{
idProducto : 1,
nombre : 'Test1',
precio : 1.5,
cantidad : 1,
totalParcial : 2.5
}
]
Your Ajax (I changed datatype back to json);
$.ajax({
url: 'agregarSeleccion',
type: 'POST',
contentType: "application/json",
data: JSON.stringify(lista),
success:function(dataP){
console.log(dataP);
},
error: function (jqXhr) {
swal("Error","","error");
}
});
Your Controller (Notice a variable is declared outside method as well , added allAll method to add list , Changed return type at the end)
List<Seleccion> seleccionados;
#RequestMapping("/agregarSeleccion")
public ResponseEntity<?> agregar(#Valid #RequestBody List<Seleccion> obj) {
seleccionados = new ArrayList<Seleccion>();
System.out.println("result"+ obj.toString());
seleccionados.addAll(obj);
return new ResponseEntity<>(seleccionados, HttpStatus.OK);
}

Pass model and a string using ajax to Spring MVC

Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.

Pass List<String> to Jquery in Play Framework

I am using Play 2.2.6 and need to get List<String> or String[] from controller to my jQuery Ajax call.
My controller looks like:
public static Result list(){
List<String> cname = new ArrayList<String>();
String[] arr= new String[]{"abc","abc2"};
return ok(index.render(arr));
}
Code for Index method:
public static Result index(){
String[] arr= new String[]{"abc","abc2"};
return ok(index.render(arr));
}
and my jQuery function looks like:
<script>
$(function() {
ajaxCall();
});
var ajaxCall = function() {
var ajaxCallBack = {
success : onSuccess,
error : onError
}
jsRoutes.controllers.Application.list().ajax(ajaxCallBack);
};
var onSuccess = function(data) {
console.log(data)
}
var onError = function(error) {
alert(error);
}
</script>
This script is in index.scala.html file and routes are:
GET / controllers.Application.index()
POST / controllers.Application.list()
GET /javascriptRoutes controllers.JavascriptRoute.javascriptRoutes
Ajax response works perfect for String type e.g. if I say
return ok("This is string");
Then I can see it in Ajax response but can't figure out why array or list throws below error:
Internal server error, for (GET) [/] ->
cannot find symbol [symbol: method ok(java.lang.String[])] [location: class controllers.Application]
Just to mention I defined this method as POST in routes.
Any suggestions?
The problem is that you are responding with a rendered index template and the exception is being thrown when trying to render that template. What you want to do is respond with the JSON data.
public static Result list(){
String[] arr= new String[]{"abc","abc2"};
return ok(Json.toJson(arr));
}
tested it locally in my browser with the following code
$.ajax({
method: "POST",
url: "/",
dataType: "script",
success : function(data) {
console.log(JSON.parse(data));
}
});
EDIT:
So you could do something like this:
List<ObjectNode> objectNodes = new ArrayList<>();
ObjectNode objectNode = Json.newObject();
objectNode.put("Latitude", "13.679389");
objectNode.put("Longitude", "-13.679389");
objectNodes.add(objectNode);
// create loop to add more nodes
return ok(Json.toJson(objectNodes));`
And in your ajax response you will now have a list of nodes with Longitude and Latitude values

java spring boot HTTP POST request not working

For my application I am writing a POST request to send array of parameters from a checkbox list. Its working for get request but not working for post request. What is the error in my code.
My code on the client side for sending ajax request to the server.
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "POST",
url : '/rest/channelstats/my/rest/controller',
data : {
// monitoring : monitoring,
// nonMonitoring: nonMonitoring,
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
}
});
})
My java code on the server side.
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
}
}
Its working for HTTP GET requests but not working for POST requests.How should I solve this problem?
According to your jquery post request, you should use DAO(Data Access Object) to parse the request data. So you should add class Request
public class Request {
private int monitoringLength;
private int nonMonitoringLength;
//getters and setters
}
And change controller to
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestBody Request request){
System.out.println("MonitoringLength =>"+request.getMonitoringLength());
System.out.println("NonMonitoringLength=>"+request.getNonMonitoringLength());
}

How do I pass an array of integer into spring controller?

script Array of int and I wish to pass into Spring Controller. but I keep getting
400 bad request.
if my js array is
array = [1,2,3,4]
array -> 400 bad request
JSON.Stringify(array) -> I will get [1,2,3,4]
$.ajax({//jquery ajax
data:{"images": array},
dataType:'json',
type:"post",
url:"hellomotto"
....
})
when I loop the string List.. the first element will be '[1'
#RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(#RequestParam("images") List<String> images){
sysout(images); -> I will get [1,2,3,4]
}
public void
May I know how can I do this properly? I have tried different combination
The following is a working example:
Javascript:
$('#btn_confirm').click(function (e) {
e.preventDefault(); // do not submit the form
// prepare the array
var data = table.rows('.selected').data();
var ids = [];
for(var i = 0; i < data.length; i++) {
ids.push(Number(data[i][0]));
}
$.ajax({
type: "POST",
url: "?confirm",
data: JSON.stringify(ids),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
Controller:
#RequestMapping(params = "confirm", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody int confirm(#RequestBody Long[] ids) {
// code to handle request
return ids.length;
}
#RequestParam is used to bind request parameters, so if you do something like
#RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(#RequestParam("image") String image){
...
}
and you do post to /hellomotto?image=test, the image variable in hellomotto method will contain "test"
What you want to do is to parse Request body , so you should you should use #RequestBody annotation :
http://docs.spring.io/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody
it is using jackson labrary (so you will have to include it as your dependency) to parse json object into java object.
I think you wantAjax call,through ajax, you are sending List of Integers
so in spring your controller will be
#RequestMapping(value = "/hellomotto", method = Request.POST)
#ResponseBody
public void hellomotto(#RequestParam("images") List<Integer> images){
sysout(images); -> I will get [1,2,3,4]
}
*#ResponseBody is missing in Your Code

Categories

Resources