Ajax Request for Controller Spring

1

I'm developing a system with Spring (Spring Boot) and front-end backend with HTML, CSS (BootStrap) and JavaScript (JQuery).

I'm having trouble building an ajax request.

Follow the Controller Spring 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, Request Payload is set up right with the company Id and nsu. However a bad request (400) is returned to me

exception : "org.springframework.web.bind.MissingServletRequestParameterException"

message : "Required Long parameter 'companyId' is not present"

    
asked by anonymous 07.12.2016 / 12:40

1 answer

1

The problem is that the parameters are like RequestParam, but the values are going into the request body.

So much that if you give a post in the uri " link " you will receive them in the controller. / p>

If your interest is to actually send in the request body, 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 even do a GET. I do not know your business rule, but I think it would make you more educated.

I would also say to pass to another layer the requisition, being the controller to take care of receiving the request, pass to another layer, pick up the return and return.

Any questions, just ask!

    
07.12.2016 / 14:11