(如果现有项目新增Rest支持,可以选择MyEclipse菜单下的Add REST Web Service Capabilities...)
全新建立项目:
这时可以发现web.xml里面有如下代码:
<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>
输入文件内容:
package com.myeclipseide.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; } }
选择New Web Service,
选择Singleton,要确保这个项目里这个类只能使用一个实例。
新增方法:
增加三个方法,点Finish,现在显示这样:
修改CustomerResource类:
package com.myeclipseide.ws; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; import javax.ejb.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; //import com.sun.jersey.spi.resource.Singleton; @Produces("application/xml") @Path("customers") @Singleton public class CustomersResource { private TreeMap<Integer, Customer> customerMap = new TreeMap<Integer, Customer>(); public CustomersResource() { // hardcode a single customer into the database for demonstration // purposes Customer customer = new Customer(); customer.setName("Harold Abernathy"); customer.setAddress("Sheffield, UK"); addCustomer(customer); } @GET public List<Customer> getCustomers() { List<Customer> customers = new ArrayList<Customer>(); customers.addAll(customerMap.values()); return customers; } @GET @Path("{id}") public Customer getCustomer(@PathParam("id") int cId) { return customerMap.get(cId); } @POST @Path("add") @Produces("text/plain") @Consumes("application/xml") public String addCustomer(Customer customer) { int id = customerMap.size(); customer.setId(id); customerMap.put(id, customer); return "Customer " + customer.getName() + " added with Id " + id; } }
可以通过右击Customer.java编辑器,选择MyEclipse-Add REST Method from the menu.
本文参考翻译自MyEclipse Help文档:REST Web Services Tutorial。
1.添加必要的类文件
2.在WEB-INF/web.xml里,
<servlet><init-param><param-name>com.sun.jersey.config.property.packages</params-name><param-value>
在value里添加加入的service.