j2ee培训:如何构建RESTful Web Service

JavaEE的核心是EJB3.0, 其提供了更兼便捷的企业级的应用框架。下面yjbys小编为大家准备了关于如何构建RESTful Web Service的.文章,欢迎阅读

j2ee培训:如何构建RESTful Web Service

  1. 首先是实体类,注意其中的@XmlRootElement注解

package s;

import ;

import ootElement;

@XmlRootElement(name="Customer")

public class Customer {

private String id;

private String name;

private Date birthday;

public String getId() {

return id;

}

public void setId(String id) {

= id;

}

public String getName() {

return name;

}

public void setName(String name) {

= name;

}

public Date getBirthday() {

return birthday;

}

public void setBirthday(Date birthday) {

hday = birthday;

}

@Override

public String toString() {

return ectionToString(this);

}

}

  2. RESTful Web Service接口类,可以通过修改@Produces注解来声明暴露接口返回的json还是xml数据格式

package s;

import ;

import ;

import Param;

import uces;

import yParam;

@Path(value = "/customer")

@Produces("*/*")

//@Produces("application/xml")

//@Produces("application/json")

public interface CustomerService {

@GET

@Path(value = "/{id}/info")

Customer findCustomerById(@PathParam("id")String id);

@GET

@Path(value = "/search")

Customer findCustomerByName(@QueryParam("name")String name);

}

  3. RESTful Web Service接口实现类

package s;

import ndar;

public class CustomerServiceImpl implements CustomerService {

public Customer findCustomerById(String id) {

Customer customer = new Customer();

d(id);

ame(id);

irthday(nstance()ime());

return customer;

}

public Customer findCustomerByName(String name) {

Customer customer = new Customer();

d(name);

ame(name);

irthday(nstance()ime());

return customer;

}

}

  4. Server端代码

package s;

import ingInInterceptor;

import ingOutInterceptor;

import SServerFactoryBean;

public class MyServer {

public static void main(String[] args) throws Exception {

JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();

nInterceptors()(new LoggingInInterceptor());

utInterceptors()(new LoggingOutInterceptor());

esourceClasses(s);

ddress("http://localhost:9000/ws/jaxrs");

te();

}

}

  5. Client端代码

package s;

import Client;

import Status;

import ethod;

public class MyClient {

public static void main(String[] args) throws Exception {

go("http://localhost:9000/ws/jaxrs/customer/1/info");

go("http://localhost:9000/ws/jaxrs/customer/search?name=abc");

}

private static void go(String url) throws Exception {

HttpClient client = new HttpClient();

GetMethod method = new GetMethod(url);

int statusCode = uteMethod(method);

if (statusCode != _OK) {

tln("Method failed: " + tatusLine());

}

byte[] responseBody = esponseBody();

tln(new String(responseBody));

}

}

  6.测试

首先运行MyServer类,然后运行MyClient类来验证Web Service。