jersey + tomcat 實現restful風格,jerseyrestful

來源:互聯網
上載者:User

jersey + tomcat 實現restful風格,jerseyrestful

 

本文參考 http://www.cnblogs.com/bluesfeng/archive/2010/10/28/1863816.html

 

環境:

idea 15.0.2

jersey 1.3

tomcat 7.0

maven 3.3.3

1.idea 基於maven 構建webapp 略過

2.項目構建完成之後pom.xml 檔案加入項目所需包:

<dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.7</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>com.sun.jersey</groupId>            <artifactId>jersey-core</artifactId>            <version>1.3</version>        </dependency>        <dependency>            <groupId>com.sun.jersey</groupId>            <artifactId>jersey-server</artifactId>            <version>1.3</version>        </dependency>        <dependency>            <groupId>com.sun.jersey</groupId>            <artifactId>jersey-client</artifactId>            <version>1.3</version>        </dependency>        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.14</version>        </dependency>        <dependency>            <groupId>javax.ws.rs</groupId>            <artifactId>jsr311-api</artifactId>            <version>1.1.1</version>        </dependency>        <dependency>            <groupId>asm</groupId>            <artifactId>asm</artifactId>            <version>3.2</version>        </dependency>

3.建立pojo類 Student:

@XmlRootElementpublic class Student {    private int id;    private String name;    private String dept;    public int getId() {        return id;    }    public Student() {    }    public Student(int id, String name, String dept) {        super();        this.id = id;        this.name = name;        this.dept = dept;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getDept() {        return dept;    }    public void setDept(String dept) {        this.dept = dept;    }}

同時建立資源類:

@Path("/students")public class RestWsDemo {    private static Logger logger = Logger.getLogger(RestWsDemo.class);    private static int index = 1;    private static Map<Integer,Student> studentList = new HashMap<Integer, Student>();    public RestWsDemo() {        if(studentList.size()==0) {            studentList.put(index, new Student(index++, "Frank",  "CS"));            studentList.put(index, new Student(index++, "Jersey", "Math"));        }    }    @GET    @Path("{studentid}")    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})    public Student getMetadata(@PathParam("studentid") int studentid) {        if(studentList.containsKey(studentid))            return studentList.get(studentid);        else            return new Student(0, "Nil", "Nil");    }    @GET    @Path("list")    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})    public List<Student> getAllStudents() {        List<Student> students = new ArrayList<Student>();        students.addAll(studentList.values());        return students;    }    @POST    @Path("add")    @Produces("text/plain")    public String addStudent(@FormParam("name") String name,                             @FormParam("dept") String dept) {        studentList.put(index, new Student(index++, name, dept));        return String.valueOf(index-1);    }    @DELETE    @Path("delete/{studentid}")    @Produces("text/plain")    public String removeStudent(@PathParam("studentid") int studentid) {        logger.info("Receieving quest for deleting student: " + studentid);        Student removed = studentList.remove(studentid);        if(removed==null) return "failed!";        else   return "true";    }    @PUT    @Path("put")    @Produces("text/plain")    public String putStudent(@QueryParam("studentid") int studentid,                             @QueryParam("name") String name,                             @QueryParam("dept") String dept    ) {        logger.info("Receieving quest for putting student: " + studentid);        if(!studentList.containsKey(studentid))            return "failed!";        else            studentList.put(studentid, new Student(studentid, name, dept));        return String.valueOf(studentid);    }}

建立完之後項目結構

 

4.再web.xml 配置如下:

<servlet>        <servlet-name>jerseyws</servlet-name>        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>        <init-param>            <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>            <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value>        </init-param>        <init-param>            <param-name>com.sun.jersey.config.property.packages</param-name>            <param-value>cz.service</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>jerseyws</servlet-name>        <url-pattern>/rest/*</url-pattern>    </servlet-mapping>

其中 com.sun.jersey.config.property.packages 的屬性值是你資源所在的包的路徑

5.maven install 略過

6.啟動tomcat 訪問路徑 http://localhost:8081/rest/students/list 就看以看到如下結果:

7.其他資源擷取方式自行領悟、測試

 

第一篇處女博文,覺得不好請將就下看這,如果該博文侵犯 原作者著作權請儘快聯絡我

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.