Rest Web Service服务开发

1、创建Rest Web Service项目

wKiom1M-kdejXFOEAAJvU7eSJsI451.jpg

   配置servlet和libraries:

wKioL1M-kkHS09VlAAPRRVbLGok201.jpg

点击完成,生成的web.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <servlet>
    <display-name>JAX-RS REST Servlet</display-name>
    <servlet-name>JAX-RS REST Servlet</servlet-name>
    <servlet-class>
        com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>JAX-RS REST Servlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

   备注:可以添加REST Web Service capabilities,在项目上点击右键,选择MyEclipse>Add REST Web Service Capabilities。


2、创建普通Java类Customer.java

wKiom1M-lsyBKGbhAAIkAAouW60617.jpg

在类Customer名称前面添加@XmlRootElement,代码如下:

package com.xju.ws;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
    private int id;
    private String name;
    private String address;
    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 getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

2、创建CustomersResource类

wKioL1M-lPmTLVFhAABUkI51aik768.jpg

wKiom1M-lUbiilxFAAGfdJI5-H0071.jpg

wKiom1M-mu2CiMvWAAJOR_SOuSQ572.jpg

添加第一个方法:

wKiom1M-nC_xrb_cAAJVtFuD6SA982.jpg

添加第二个方法:

wKiom1M-nRuxoNxkAAKmt2Bcaz4561.jpg

添加第三个方法:

wKiom1M-nyDzxkpGAALw37ZTrT8248.jpg

结果:

wKioL1M-nzGxDB2wAAK-ySLmsGo260.jpg









本文出自 “IT技术学习与交流” 博客,谢绝转载!

你可能感兴趣的:(Web,REST,service)