1
I am developing a system with back-end in Spring (Spring Boot) and front-end with HTML, CSS(Bootstrap) and Javascript(Jquery).
I’m having trouble putting together an ajax request.
Follow the Spring Controller code:
@RequestMapping(value = "/visualizarResumo", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody ResumoNFe visualizarResumo(@RequestParam Long empresaId, @RequestParam Long nsu) {
System.out.println(empresaId);
System.out.println(nsu);
return resumoNFeService.buscaPorId(new ResumoPK(empresaId, nsu));
}
And the requisition:
$('button[name=visualizarResumo]').click(function(e) {
var buttonVisualizarResumo = $(this);
var nsu = buttonVisualizarResumo.attr('data-nsu');
var empresaId = buttonVisualizarResumo.attr('data-empresa');
console.log(nsu);
console.log(empresaId);
$.ajax({
url: '/edocs/mde/visualizarResumo',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({empresaId:empresaId, nsu:nsu}),
dataType : 'json',
error: onErrorVisualizarResumo,
success: onSuccessVisualizarResumo
});
function onErrorVisualizarResumo() {
console.log(arguments);
}
function onSuccessVisualizarResumo() {
console.log("sucesso");
}
});
Looking at the Chrome tools, the Request Payload is mounted right with the companyId and nsu. However it is returned me a bad request (400)
Exception : "org.springframework.web.bind.Missingservletrequestparameterexception"
message : "Required Long Parameter 'empresaId' is not present"
Try changing parameter by body, this way:
visualizarResumo(@RequestBody String payload)
– BrTkCa
Right, now the request worked, but there would be no way it would arrive already converted into the two variables instead of coming the payload?
– rafaelssce
That way no, or you could switch from POST to GET and pass as URL parameter.
– BrTkCa
Thank you @Lucascosta
– rafaelssce