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

405
Visualizações
What is the correct way to send a string using AJAX with Spring and Thymeleaf? Status : 400

I am getting error ""Required UsernameSearch parameter 'username' is not present" when sending data using ajax with Spring and Thymeleaf. My script is as shown below

<script>
 $(document).ready(function() {
   $("#opusername").keyup(function() {
  var username = $('#opusername').text();

          $.ajax({
            type : "POST",
            contentType : "application/json",
            url : "/create/check-username-availability",
            data : {"username" : username},
            dataType : 'json',
            timeout : 100000,
            success : function(data) {
              console.log("SUCCESS: ", data);
            },
            error : function(e) {
              console.log("ERROR: ", e);
            },
            done : function(e) {
              console.log("DONE");
            }
          });
      });
  }); 

My controller has this method which should receive the string and return a value to indicate whether the username is available or not.

 @RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
 @ResponseBody
 public String checkUsernameAvailability(@RequestParam("username") UsernameSearch username) {
    logger.info("Checking username availability for username = " + username.getUsername());

    return "true";
}

This is the object I create which contains the username String. I have done this after following tutorials and answers here but nothing seems to work.

public class UsernameSearch {

String username;

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

}

This is the error when debugging

error:"Bad Request"
exception:"org.springframework.web.bind.MissingServletRequestParameterException"

message:"Required UsernameSearch parameter 'username' is not present" path:"/create/check-username-availability" status:400 timestamp:1489942516434

I also wanted to ask how to consume the result from the spring method. Is it possible to get a boolean value?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Change @RequestParam to @RequestBody. Request param != body of the request.

The 400 HTTP error means that the the request is malformed. In your case, the controller expects that the url will have a "username" parameter. Therefore you can either change the ajax call, to send the username as the request parameter, i.e. by attaching "?username=fooBar" to the url you're perfoming POST request and change the controller method signature to accept @RequestParam("username") String username, or change the annotation on the controller parameter to @RequestBody, which tells the controller that the data will be sent as an object in the body of the request.

about 4 years ago · Santiago Trujillo Relatório

0

function ajax:

var data = {
    username: $('#opusername').text()
};
$.ajax({
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    url: "/create/check-username-availability",
    data: JSON.stringify(data), // Note it is important
    success: function (result) {
        // do whatever you want with data
    }
});

and in your java method

@RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
@ResponseBody
public String checkUsernameAvailability(@RequestBody UsernameSearch username) {
    logger.info("Checking username availability for username = " + username.getUsername());

    return "true";
}
about 4 years ago · Santiago Trujillo Relatório

0

Don't send your data as string! Do the following:

data : {"username" : username},
about 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