當前位置:才華齋>IT認證>J2EE>

j2ee培訓:如何構建RESTful Web Service

J2EE 閱讀(7.83K)

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。