Ajax Request for Controller Spring

Asked

Viewed 1,615 times

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)

  • 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?

  • That way no, or you could switch from POST to GET and pass as URL parameter.

  • 1

    Thank you @Lucascosta

1 answer

1


The problem is that the parameters are like Requestparam, but the values are going in the body of the request.

So much so that if you give a post on Uri "http://localhost:8080/viewSummary? companyId=10&nsu=10" you will receive them in the controller.

If your interest is really sending in the body of the request, you can do so:

@RequestMapping(value = "/visualizarResumo", method = RequestMethod.POST, consumes = {
        MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody String visualizarResumo(@RequestBody(required = true) Map<String,Object> corpo) {
    System.out.println(corpo);
    return String.format("%7d %7d", corpo.get("empresaId"), corpo.get("nsu"));
}

But if your request does not change any status on the server, you can do a GET even. I don’t know your business rule, but I think you’d be more polite.

I would also say to pass to another layer the request, getting the controller take care of receiving the request, pass to another layer, take the return and return.

Any questions, just ask!

  • I understood where I was going wrong and I was able to solve the requisition problem. Thank you. You could explain to me what you meant by forwarding the request to another layer to pick up the return and return. It is no longer what I am doing by calling "Return resumeNFeService.buscaPorId(new Resumek(empresaId, nsu));", in case this going to a service layer.

  • Hi man. Your doubt is very interesting in this sense, because it is very conceptual and I notice that it is not something so trivial to catch. Think about it, the controller’s function should be just to receive and pass on the information, and maybe make the decision with what comes back. For example, if you spit an Exception, then you must return a Responseentity with Httpstatus 500. This is the controller’s obligation, and this is it. Making access to the bank is dao. Maybe put a layer of Façade in the middle resolve. Take a look at this Pattern(Façade), should guide you a little more. Qlq thing, just warn.

  • Thanks for the clarifications. I had already seen this Pattern, but I didn’t get to use it. I will study it again and apply in my case to see how it looks. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.