Spring MVC - JSON response with @ResponseBody annotation (Spring + JSON)


Models::

package com.developer.FileUpload.models;

/**
 * Created by Pukar on 8/25/2017.
 */
public class Student {
    private int id;
    private String firstName;
    private String lastName;

    public Student() {
    }

    public Student(int id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Controller::

@GetMapping("/list")
    public @ResponseBody
    List<Student> getAll() {
        List<Student> studentList = new ArrayList<Student>();
        studentList.add(new Student(1, "Ram", "Pukar"));
        return studentList;
    }

 views::

<button>Show List</button>
<script type="text/javascript">
$(document).ready(function(){
$('button').on('click',function(){
            $.ajax({
                type: "GET",
                url: "/list",
                success: function(res){
                    debugger;
}
            });
})
});
</script>

Demo::

Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment