Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

419
Visualizações
Ajax post request in Spring MVC

I am currently trying to call an ajax request from a JavaScript onchange handler to call a Spring MVC controller. I believe the way I am currently calling the URL in my view is wrong since I get an 404 error on the browser when the event is triggered and call for url. Can anyone shine some light if I have everything setup correctly?

Here is my code:

@Controller
public class DataTableController 
{     
    @RequestMapping(value = "/table", method = RequestMethod.GET)
    public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException 
    {
        List<String> gpnList = new ArrayList<GPN>();
        gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3"); 
        model.addAttribute("gpnList", mapper.writeValueAsString(gpnList)); 
        return "index"; //name of my view
    }
    
    @RequestMapping(value = "/getsector", method = RequestMethod.POST)
    public @ResponseBody String getSector(@RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
    {
        List<String> sectors = new ArrayList<String>();
        sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(sectors);
    }
}

Jquery Code:

$(document).ready(function()
{
    document.getElementById("markets").onchange =  function()
    { 
        var market = $("select[id='markets'").find('option:selected').text();
        var filters = { "market" : market }
        filters = JSON.stringify(filters);

        $.ajax({
            url: "/getsector",
            type: "POST",
            dataType : 'json',
            contentType : "application/json",
            data: JSON.stringify(filters),
            success: function(response) 
            {
                console.log("sucess!");
            },
            error: function(e){
                console.log("ERROR: ", e);
            }
        });
    }
}); 

The main thing I want to achieve is being able to call my controllers via ajax calls. Any other tips on Spring Controller Mapping and conventions will be appreciated.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If your a requesting information you should use GET requests, not POST.

You are mixing @RequestParam with a json payload. If you want to receive your filter as a request param it has to go at the url, not as a json payload, using something like:

$(document).ready(function()
{
    document.getElementById("markets").onchange =  function()
    { 
        var market = $("select[id='markets'").find('option:selected').text();

        $.ajax({
            url: "/getsector?market="+market,
            type: "GET",
            success: function(response) 
            {
                console.log("sucess!");
            },
            error: function(e){
                console.log("ERROR: ", e);
            }
        });
    }
}); 

@RequestMapping(value = "/getsector", method = RequestMethod.GET)
public @ResponseBody String getSector(@RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
  .... your logic.
}

On the other hand, if you really want to use POST requests with a json payload, you need to use @RequestBody at the controller and bind the json object to a bean with the same properties.

@RequestMapping(value = "/getsector", method = RequestMethod.POST)
public @ResponseBody String getSector(@RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException
{
    List<String> sectors = new ArrayList<String>();
    sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
    return sectors;
}


public class Market
{
  String market;

  //getter and setter...
}

Bear in mind your javascript is wrong as well, you are using JSON.stringify twice.

If you use @ResponseBody and spring is configured fine it will make the serialisation for you when returning the response, so you do not have to do it manually.

This code has not been tested, it is just for you to get an idea.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda