Tell me, please, how to correctly respond from java @RestController to XMLHttpRequest from javascript.

@ResponseBody @RequestMapping(value = "/authorization", method = RequestMethod.POST) public String authorization( @RequestParam String login, @RequestParam String password) { System.out.println(login + " " + password); return "HelloWorld!"; } 

Javascript

 formData.append("login", $("#login").val()); formData.append("password", $("#password").val()); formData.append("delete", document.getElementById("deleteCheck").checked); var xhr = new XMLHttpRequest(); xhr.open("POST", "authorization",false); xhr.send(formData); alert(xhr.responseText); 

In the controller, I see the login and password, but I don’t see it in the answer.

  • I did this: @RequestMapping (value = "/ authorization", method = RequestMethod.POST) public ToSend authorization (@RequestParam String login, @RequestParam String password) {ToSend toSend = new ToSend (); toSend.getCustomers (). add (new Customer (login, password)); toSend.getCustomers (). add (new Customer ("Customer2", "123456")); toSend.setMessage ("Authorization OK!"); System.out.println (toSend); return toSend; In response, HttpStatus 500. - Nikolay Egorov

2 answers 2

If you want to return JSON, you need to add the @ResponseBody annotation to the controller method.

  • This @RestController forgot to write. Doesn't work ... - Nikolay Egorov
  • If you use the @RestController annotation, @ResponseBody do not need to write @ResponseBody , it automatically makes all methods annotated. - raviga

Perhaps this is because you are sending a string with the text "Hello World?". You need to create an object, something like a DTO, into which you complain about the values ​​returned in the response and return to return it. Example:

 return new Response(username, password); 

But it is better to make some kind of responsive wrapper that will return status, status messages and the object itself.

In addition, you need to connect HttpJacksonMapper and three depenpendy com.fasterxml.jackson.core .

And the 500th error says that you somewhere transfer not the correct type of values.

And why not make the input parameter a model with the username and password fields and accept it as @RequestBody AuthModel request ? And if the input parameters will be 10? It is also easier.

  • What about the dependency more precisely possible?) I tried Json - 500 error does not work. And HelloWorld and everything else just to simplify did. - Nikolay Egorov
  • @ Nikolay Egorov you can see here https://github.com/dkhodan/REST---JWT-Security---Swagger-UI , at the same time look at the configuration and dependency. - raviga
  • Added ... Error 500 - Nikolay Egorov
  • can you fill up your code somewhere along with the configurations? perhaps on git or bitbucket, so you can put it locally. perhaps problems somewhere in configs. - raviga