0

I am trying to hit my SpringBoot controller with a JSON and for that I am using AJAX. I want my controlelr to receive the AJAX call, extract the JSON, works with the values and return a JSON response back to the script which I will then utilize in some way.

I am not able to figure out how to code my controller so as to handle the AJAX and also if the request should be POST or GET ?

Here is my script code:

<script>
    database.on('child_added', function (snapshot) {
        var data = {};
        data["FirstName"] = snapshot.val().FirstName;
        data["LastName"] = snapshot.val().LastName;
        data["Number"] = snapshot.val().Number;

        $.ajax({
          type: "GET",
          contentType: "application/json",
          url:"my-localhost/application/print",
          data: JSON.stringify(data),
          dataType: 'json',
          cache: false,
          success: function(){
            console.log("Successfully sent payload")
          },
          error: function(e){
            console.log("Error": , e)
          }
        });
</script>

Here is my controller for now. I dont know how and what to change in it and how to send the response back to the script:

@RestController
@RequestMapping("/application")
public class AppController
{
    @GetMapping("/print")
    public void print()
    {
        System.out.println("Hello World");
    }
}
Vai
  • 343
  • 3
  • 17

2 Answers2

0

I am not able to figure out how to code my controller so as to handle the AJAX and also if the request should be POST or GET ?

Your service method is annotated as @GetMapping("/print") so it should be GET request. I suggest reading a bit more on various HTTP methods and then decide which one serves you best.

Here is my controller for now. I dont know how and what to change in it and how to send the response back to the script.

You should be returning the object which encapsulates the data you want to send back to the consumer.

Smile
  • 3,832
  • 3
  • 25
  • 39
0

Simply it has three steps

  1. Create DTO object (property name must be according to your JSON object names)
  2. User @RequestBody in your method
  3. Use @ReponseBody and simply return the object.

Example: Consider it you want to send some user information, do some business and return that user to the javascript (UI).

  • Create DTO class for user
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class UserDto {

    private Long id;
    private String name;
    private String family;
    private String password;
    private String username;
    private String nationalId;
    private String email;
    //Getters and Setters
    }
  • Put @RequestBody and User class as the input of the controller method.

  • Simply return user object.

 @RestController
 @RequestMapping("/application")
 public class AppController {

    //Changed to @PostMapping
    @PostMapping("/print")
    public User print(@RequestBody User user) {

        //Do whatever you want to user
        System.out.println("Hello World" + user.getUsername());
        return user;

    }
 }

Some notes

  • @RequestBody, works as a converter to convert sent JSON to a java class (Convert user JSON to User.class)

  • @ResponseBody, is inverse of @RequestBody, it converts java classes to JSON (Convert User.class into user JSON)

  • As you're sending data to the server it's good for you to use POST instead of GET. GET OF POST

  • DTO object property names (family, id,...) must be the same as your JSON property names. Otherwise, you must use @JsonProperty. Further information about JsonProperty

  • When you're using @RestController you don't need to use @ResponseBody because it's in body of @RestContoller

  • How can I fetch the JSON in my controller from the AJAX call ? – Vai Jan 09 '20 at 11:49
  • 1
    You must get your data back from your success callback method. like this: success:function(data){ console.log(data); } – Mehrdad HosseinNejad Yami Jan 09 '20 at 11:52
  • I mean, how can I use the JSON from AJAX in my spring controller ? – Vai Jan 09 '20 at 11:55
  • 1
    When you use @RequestController, your JSON form data is in java class form now. after that, you can work with that class. For example, in the aforementioned example, I use username of converted user and printed it. I mean after conversion you can do whatever you want on your converted class and after that, you can return it back to your javascript. – Mehrdad HosseinNejad Yami Jan 09 '20 at 12:00