1. JAX-RS = Java API For Restful Web Services
JAX-RS是JAVA EE6 引入的一个新规范。 是一个Java 编程语言的应用程序接口,支持按照表述性状态转移(REST)架构风格创建Web
服务。
JAX-RS使用了Java标注来简化Web服务的客户端和服务端的开发和部署。
除了JAX-RS方式发布Restful风格的Webservice
SpringMVC也可以发布Restful风格的Webservice
JAX-RS提供了一些标注将一个资源类,一个POJO Java类,封装为Web资源。
包括:
@Path,标注资源类或者方法的相对路径
@GET,@PUT,@POST,@DELETE,标注方法是HTTP请求的类型。
@Produces,标注返回的MIME媒体类型
@Consumes,标注可接受请求的MIME媒体类型
@PathParam,@QueryParam,@HeaderParam,@CookieParam,@MatrixParam,@FormParam,分别标注方法的参数来
自于HTTP请求的不同位置,例如:
@PathParam来自于URL的路径,
@QueryParam来自于URL的查询参数,
@HeaderParam来自于HTTP请求的头信息,
@CookieParam来自于HTTP请求的Cookie。
基于JAX-RS实现的框架有Jersey,RESTEasy等。
这两个框架创建的应用可以很方便地部署到Servlet 容器中
怎么用:
1 建工程添jar包(Cxf的jar包)
2 建Customer.java的entity并添加注解@XmlRootElement
3 建CustomerService接口并添加Restful风格相关的注释
4 编写CustomerServiceImpl实现类
5 编写MainServer类,启动Restful的Webservice
启动后注意目前用rest而不是soap了,所以没有WSDL的描述了
6 浏览器地址栏里面按照Restful风格的路径进行访问+测试
Entity类:
@XmlRootElement
public class Customer {
public Customer (){
}
private String id ;
private String name;
private Integer age;
public Customer(String id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
Service类:
@Path("/crm")
public class CustomerService {
@GET
@Path("/customer/{id}")
@Produces("application/json")
public Customer getCustomerById(@PathParam("id") String id){
System.out.println("get id:"+id);
Customer res_customer=new Customer(id,"z3",18);
return res_customer;
}
}
服务启动类:
public class MainServer {
public static void main(String[] args) {
JAXRSServerFactoryBean jAXRSServerFactoryBean = new JAXRSServerFactoryBean();
jAXRSServerFactoryBean.setAddress("http://localhost:8888/restws");
jAXRSServerFactoryBean.setResourceClasses(CustomerServiceImpl.class);
jAXRSServerFactoryBean.create().start();
}
}
客户端开发步骤:
使用 HttpClient需要以下6个步骤:
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例
3. 调用第一步中创建好的实例的execute方法来执行第二步中创建好的链接类实例
4. 读response获取HttpEntity
5. 对得到后的内容进行处理
6. 释放连接。无论执行方法是否成功,都必须释放连接
客户端类:
private static String getCustomer(String id) throws ClientProtocolException, IOException{
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpGet httpget = new HttpGet("http://localhost:8888/restws/crm/customer/1122");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String result = EntityUtils.toString(entity, "UTF-8");
System.out.println(result);
}else{
String result = EntityUtils.toString(entity, "UTF-8");
System.err.println(result);
}
EntityUtils.consume(entity);
httpclient.close();
}