Restful Web Service- Json Example - Spring MVC 4 + Maven

Lượt xem: 772

Bub

Bub

Administrator
Ban Quản Trị
3 Tháng chín 2015
454
75
28
HCMC
4online.net


You’ll build a service that will accept HTTP GET requests at:

Mã:
http://localhost:8080/restfulspringmvc/json?name=dat&age=23
and respond with a JSON like:
Mã:
[{"name":"dat1","age":11},{"name":"dat2","age":22}]
Getting Started:

I will not mention that how to create a SpringMVC project here.

You must add a dependency to pom.xml file.
Mã:
<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.4.1</version>
        </dependency>
Create Person class:
PHP:
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}
Controller Class:
PHP:
@Controller
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        return "home";
    }

    @RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody List<Person> personsReturn(@RequestParam("name") String name, @RequestParam("age") int age) {
        Person p1 = new Person("dat1", 11);
        Person p2 = new Person("dat2", 22);

        Person p3 = new Person("dat3", 33);
        Person p4 = new Person("dat4", 44);

        List<Person> lists = new ArrayList<Person>();

        if (name.equals("dat")) {
            lists.add(p1);
            lists.add(p2);
        } else {
            lists.add(p3);
            lists.add(p4);
        }
        return lists;
    }
}
now, we run project as server to enjoy.

I have a full example about restfull with json here: