Java Spring: send list from Ajax to Controller - java

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);
}

Related

Read return value of $.ajax POST Method gives just return value Object object

I want to use following ajax method to call a java function (I use Spring Boot and Hibernate) and read the return value afterwards. The function '/myFunction' is correctly called and the return value is a string and is correctly logged in the java function. But I don't get it, how I can use the return message from the java-method in the success-part afterwards. (notifyUser is a little function(title, message) that shows a notification to an user, this function works correctly) By now, notifyUser just post Error [object Object]
$.ajax({
type : 'POST',
contentType : 'application/json',
url : '/myFunction',
data : JSON.stringify({
fooM,
fooO,
fooS
}),
dataType : 'json',
cache : false,
timeout : 600000,
success : function(data) {
notifyUser('Info', data);
},
error : function(e) {
notifyUser('Error', e);
}
});
#RestController
#Secured({ "ROLE_USER", "ROLE_ADMIN" })
public class MyController {
#RequestMapping(value = "/myFunction", method = RequestMethod.POST)
public String myFunction(#RequestBody MyRequestClass request ) {
String return_string = "Check if return value works " + request.getFooM() + request.getFooO() +request.getFooS();
log.debug(return_string)
//Up to this step, everything works
return return_string;
}
}
What do I have to change, that I'm able to get the return value of the called function '/myFunction' in the success part and send the string to notifyUser?
Thank you for your answers.
Phil

Ajax request with type 'POST' not working, only with 'GET'

I'm trying to send and ajax post request to my springboot mvc controller, but with no success. I've looked a number of similar topics, tried the given solutions, but with no success at all.
If I change the request type to GET, it triggers the controller endpoint.
The endpoint function is not even being triggered in the controller. It is showing only the following error in browser console: jquery-3.4.1.js:9837 POST http://localhost:8080/rede-credenciada 500
I made the same request with postman and it gives the following error:
{
"timestamp": "2020-07-09T17:46:20.920+0000",
"status": 999,
"error": "None",
"message": "No message available"
}
Note: It only happens with POST request, if I change to GET, it works fine. The request is "listened" by the controller.
Here is my ajax request:
const json = {
idGrupoProcedimento: 0,
idTipoEspecialidade: $("#especialidade").val(),
uf: $("#estado").val(),
codCidade: $("#cidade").val()
}
const jsonString = JSON.stringify(json);
$.ajax({
url: "/rede-credenciada",
type: 'POST',
contentType: "application/json",
dataType: "application/json",
data: jsonString,
success: function(data){
console.log(data);
},
error: function(e) {
console.log(e.message);
}
});
Here, my endpoint:
#RequestMapping(value = "/rede-credenciada", method = RequestMethod.POST, consumes = "application/json")
#ResponseBody
public RedeCredenciadaResponse buscaRedeCredenciadaPorFiltro(#RequestBody RedeCredenciadaRequest request) {
... some logic
RedeCredenciadaResponse redeCredenciada = new RedeCredenciadaResponse();
redeCredenciada.setPessoasFisicas(pessoas);
redeCredenciada.setEmpresas(empresas);
return redeCredenciada;
}
And here is my wrapper class:
public class RedeCredenciadaRequest {
private int idGrupoProcedimento;
private int idTipoEspecialidade;
private String uf;
private String codCidade;
public int getIdGrupoProcedimento() {
return idGrupoProcedimento;
}
public void setIdGrupoProcedimento(int idGrupoProcedimento) {
this.idGrupoProcedimento = idGrupoProcedimento;
}
public int getIdTipoEspecialidade() {
return idTipoEspecialidade;
}
public void setIdTipoEspecialidade(int idTipoEspecialidade) {
this.idTipoEspecialidade = idTipoEspecialidade;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCodCidade() {
return codCidade;
}
public void setCodCidade(String cidade) {
this.codCidade = cidade;
}
The error:
In your ajax request you are using dataType:'application/json', According to jQuery’s Ajax-Related Methods Description
// The type of data we expect back
dataType : "json",
Value of dataType shoud be json, or xml, or html, etc.

How receive a list of JavaScript objects in a List<Object> in Spring MVC?

I was reading a lot but I don't know what is the error in my code. I hope you can help me. Regards.
Model: RenglonFacturaDTO(With his getters/setters)
public class RenglonFacturaDTO implements Comparable<RenglonFacturaDTO>{
private Integer idfact;
private Long idrenglon;
private Integer idremito;
private Float cant;
private String descripadic;
private Double precio;
private Double subtotal;
}
This is the list of objects that i send via ajax to controller
<script>
$(document).ready(function(){
var cliente = $('.id').data('id');
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var listado = [{}];
$('#generar').click(function(){
cliente = $('#idcliente').data('id');
$('.renglon').each(function(){
elem = $(this);
cant = elem.find('.cant').val();
precio = elem.find('.precio').val();
descripadic = elem.find('.descripadic').val();
idremito = elem.find('.idremito').text();
idrenglon = elem.data('idrenglon');
idfact = $('#factura').data('idfact');
subtotal = cant * precio;
listado.push({"cant": parseFloat(cant),"precio": precio ,"descripadic":descripadic,"subtotal":subtotal ,"idremito":idremito ,"idrenglon":idrenglon , "idfact":idfact});
});
$.ajax({
"type":"post",
"url":"agregarRenglonesFactura",
"dataType": 'json',
"cache": false,
"data": {"listado": listado},
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
}
});
});
});
</script>
Controller
#RequestMapping(value="/agregarRenglonesFactura", method= RequestMethod.POST)
public String redAgregarRenglonFactura(#ModelAttribute ArrayList<RenglonFacturaDTO> renglonesfacturadto) throws Exception{
Iterator<RenglonFacturaDTO> it = renglonesfacturadto.iterator();
while(it.hasNext()){
RenglonFacturaDTO renglonfacturadto = it.next();
System.out.println("***************AGREGAR RENGLON*******************IDRENGLONREMITO: " + renglonfacturadto.getIdrenglon() + " CANTIDAD: " + renglonfacturadto.getCant());
}
return ("TAMAÑO LISTA: " + renglonesfacturadto.size());
}
this is the error:
Request processing failed; nested exception is org.springframework.beans.InvalidPropertyException:
Invalid property 'listado[10][cant]' of bean class [ar.edu.grupoesfera.cursospring.modelo.ListadoRenglonesFacturaDTO]:
Property referenced in indexed property path 'listado[10][cant]' is neither an array nor a List nor a Map; returned value was [ar.edu.grupoesfera.cursospring.modelo.RenglonFacturaDTO#67e12cdf]] con causa raíz
This is the array that i send via post
listado[0][cant]15
listado[0][descripadic]
listado[0][idfact]12
listado[0][idremito]9
listado[0][idrenglon]36
listado[0][precio]135
listado[0][subtotal]2025
listado[1][cant]15
listado[1][descripadic]
listado[1][idfact]12
listado[1][idremito]9l
istado[1][idrenglon]36
listado[1][precio]135
listado[1][subtotal]2025
listado[2][cant]15
listado[2][descripadic]
listado[2][idfact]12
listado[2][idremito]9
listado[2][idrenglon]36
listado[2][precio]135
listado[2][subtotal]2025
With JQuery ajax requests, especially if you're sending a list, you want to use JSON.stringify().
"data": JSON.stringify({ 'listado': listado }),
As a side note, you're also passing a null value with your list because of the way it's instantiated. You could just write
var listado = [];
You should create a proper JSON before posting it to controller, something like below
[
{ "cant": 15,
...
}
]
And your controller RequestMapping should look like below:-
#RequestMapping(value="/agregarRenglonesFactura", method= RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public String
redAgregarRenglonFactura(#RequestBody ArrayList<RenglonFacturaDTO>
renglonesfacturadto) throws Exception{}

How to pass JSON object from ajax to controller in spring mvc?

I am using spring mvc. I need to pass a json object from my jsp page to controller.
My ajax code:
function createJSON() {
jsonObj = [];
item = {};
$(".values").each(function() {
var code = $(this).attr('id');
item[code] = $('#' + code).val();
});
var content=JSON.stringify(item)
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
url: "/pms/season/submit",
data: content,
dataType: "json",
success : function(data) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
My controller code:
#RequestMapping(value = "/submit", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json) {
System.out.println( "json ::::"+json );
}
But it's not working.
#RequestParam("json") means that you are intending to include a request parameter called json in the URI, i.e. /submit?json=...
I think you intend to get the request body, i.e. #RequestBody.
I would then suggest that, unless you really need the raw JSON string, you would have the #RequestBody translated to a Java object for you:
public void saveNewUsers(#RequestBody MyDto myDto) {
...
}
where MyDto would have getters/setters and fields matching the JSON class.
You can over omit the #RequestBody annotation if you annotate the controller with #RestController, instead of #Controller.
If you definitely want the raw JSON string, then take a look at this previous question: Return literal JSON strings in spring mvc #ResponseBody

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