j2ee培訓:如何構建RESTful Web Service
- J2EE
- 關注:6.1K次
JavaEE的核心是EJB3.0, 其提供了更兼便捷的企業級的應用框架。下面yjbys小編為大家準備了關於如何構建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。
- 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-hk/itrz/j2ee/xv4105.html