1. 程式人生 > >使用IDEA+Maven+jersey構建RESTful Web Services入門案例

使用IDEA+Maven+jersey構建RESTful Web Services入門案例

1.首先在WEB專案

2.建立好之後點選專案右鍵,點Add Frameworks Support給專案新增Maven框架

3.建立好之後的專案結構如下圖所示

4.新增pom.xml依賴

<dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.17</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.17</version>
        </dependency>
</dependencies>

5.在java目錄下建立POJO類User.java

package cn.ysjh;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {

    private String name;
    private String password;
    private int id;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

6.建立Hello類測試不同型別的返回資料

package cn.ysjh;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class Hello {

    @GET
    @Path("test")
    @Produces(MediaType.APPLICATION_XML)
    public User test() {
        User user = new User();
        user.setName("zhangsan");
        user.setPassword("123456789");
        user.setId(12);
        return user;
    }

    @GET
    @Path("test1")
    @Produces(MediaType.APPLICATION_JSON)
    public User test1(){
        User user = new User();
        user.setName("zhangsan");
        user.setPassword("123456789");
        user.setId(13);
        return user;
    }

    @GET
    @Path("test2")
    @Produces(MediaType.TEXT_PLAIN)
    public String test2(){
        return "hello world";
    }
}

7.將jar包加入到WEB-INF目錄下

8.啟動Tomcat執行

 

執行結果:

localhost:8080/api/hello/test

localhost:8080/api/hello/test1

localhost:8080/api/hello/test2