1、概述
JAX-RS是Java提供用於開發RESTful Web服務基於註解(annotation)的API。JAX-RS旨在定義一個統一的規範,使得Java程序員可使用一套固定的接口來開發REST應用,避免了依賴第三方框架。同時JAX-RS使用POJO編程模型和基於註解的配置並集成JAXB,能夠有效縮短REST應用的開發週期。JAX-RS只定義RESTful API,具體實現由第三方提供,如Jersey、Apache CXF等。java
JAX-RS包含近五十多個接口、註解和抽象類:程序員
javax.ws.rs包含用於建立RESTful服務資源的高層次(High-level)接口和註解。web
javax.ws.rs.core包含用於建立RESTful服務資源的低層次(Low-level)接口和註解。spring
javax.ws.rs.ext包含用於擴展JAX-RS API支持類型的APIs。apache
JAX-RS經常使用註解:編程
@Path:標註資源類或方法的相對路徑。json
@GET、@PUT、@POST、@DELETE:標註方法的HTTP請求類型。瀏覽器
@Produces:標註返回的MIME媒體類型。tomcat
@Consumes:標註可接受請求的MIME媒體類型。restful
@PathParam、@QueryParam、@HeaderParam、@CookieParam、@MatrixParam、@FormParam:標註方法的參數來自於HTTP請求的位置。@PathParam來自於URL的路徑,@QueryParam來自於URL的查詢參數,@HeaderParam來自於HTTP請求的頭信息,@CookieParam來自於HTTP請求的Cookie。
2、依賴JAR文件Maven座標
- <properties>
- <cxf.version>3.0.7</cxf.version>
- <junit.version>4.11</junit.version>
- </properties>
- <!-- CXF須要導入的jar包 -->
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-frontend-jaxws</artifactId>
- <version>${cxf.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-transports-http</artifactId>
- <version>${cxf.version}</version>
- </dependency>
- <!-- CXF實現RestFul接口須要用到的包 -->
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-frontend-jaxrs</artifactId>
- <version>${cxf.version}</version>
- </dependency>
- <!-- 客戶端調用restFul服務須要導入的包 -->
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-rs-client</artifactId>
- <version>${cxf.version}</version>
- </dependency>
-
- <!-- 部署至tomcat低下不會,jetty環境須要加入該包 -->
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-transports-http-jetty</artifactId>
- <version>${cxf.version}</version>
- </dependency>
3、發佈RestFul接口
3.1實體對象
- @XmlRootElement(name="UserInfo")
- public class Users{
- private String userId;
- private String userName;
- private String userPwd;
- private Integer sex;
- private Float sal;
- private Date birthday;
-
- get、set方法省略!
-
- public String toJson() {
- Gson gson = new Gson();
- return gson.toJson(this);
- }
- }
3.二、定義發佈接口
- import javax.ws.rs.DELETE;
- import javax.ws.rs.GET;
- import javax.ws.rs.POST;
- import javax.ws.rs.PUT;
- import javax.ws.rs.Path;
- import javax.ws.rs.PathParam;
- import javax.ws.rs.Produces;
- import javax.ws.rs.QueryParam;
- import javax.ws.rs.core.MediaType;
-
- @Path("/restFul")
- public interface UserService {
-
- @GET
- @Path("/get")
- @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
- public Users get(@QueryParam("id") String id);
-
-
-
- @PUT
- @Path("/put/{id}")
- @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
- public Users put(@PathParam("id")String id,Users u);
-
-
-
- @POST
- @Path("/post/{id}")
- @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
- public Users post(@PathParam("id") String id,Users u);
-
-
-
- @DELETE
- @Path("/delete/{id}")
- @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
- public Users delete(@PathParam("id") String id);
-
- }
3.三、接口實現類
- import java.util.Date;
- import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
- import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
-
- public class UserServiceRestFul implements UserService {
-
- @Override
- public Users get(String id) {
- System.out.println("GET方法,id=" + id);
- Users user = new Users();
- user.setUserId("get");
- user.setUserName("ickes");
- user.setUserPwd("ices123");
- user.setSex(1);
- user.setSal(32F);
- user.setBirthday(new Date());
- return user;
- }
-
- @Override
- public Users put(String id, Users u) {
- System.out.println("PUT方法,id=" + id + ",users=" + u.toJson());
- Users user = new Users();
- user.setUserId("put");
- user.setUserName("ickes");
- user.setUserPwd("ices123");
- user.setSex(1);
- user.setSal(32F);
- user.setBirthday(new Date());
- return user;
- }
-
- @Override
- public Users post(String id, Users u) {
- System.out.println("POST方法,id=" + id + ",users=" + u.toJson());
- Users user = new Users();
- user.setUserId("post");
- user.setUserName("ickes");
- user.setUserPwd("ices123");
- user.setSex(1);
- user.setSal(32F);
- user.setBirthday(new Date());
- return user;
- }
-
- @Override
- public Users delete(String id) {
- System.out.println("DELETE方法,id=" + id);
- Users user = new Users();
- user.setUserId("delete");
- user.setUserName("ickes");
- user.setUserPwd("ices123");
- user.setSex(1);
- user.setSal(32F);
- user.setBirthday(new Date());
- return user;
- }
- }
4、發佈RestFul接口
4.一、使用CXF的API接口進行發佈
使用CXF的API接口進行發佈的缺點很明顯,就是必須指定一個端口進行發佈,這個端口不能被佔用,佔用就會拋出異常。
- public static void main(String[] args) {
- JAXRSServerFactoryBean jrf = new JAXRSServerFactoryBean();
- jrf.setResourceClasses(UserServiceRestFul.class);
- jrf.setResourceProvider(UserServiceRestFul.class,
- new SingletonResourceProvider(new UserServiceRestFul()));
- jrf.setAddress("http://localhost:8080/rest/");
- jrf.create();
- }
4.二、在spring容器中進行發佈
跟使用CXF發佈JAX-WS接口同樣,首先必須在web.xml中配置CXFWebServlet,代碼以下:
- <!-- Cxf中使用 CXFServlet,發佈跟當前項目端口相同的服務 -->
- <servlet>
- <servlet-name>cxfServlet</servlet-name>
- <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>cxfServlet</servlet-name>
- <url-pattern>/cxf/*</url-pattern>
- </servlet-mapping>
而後在類路徑下面新建applicationContext-cxf.xml,代碼以下:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http:
- http:
- http:
-
- <jaxrs:server id="restUserService" address="/restFul">
- <jaxrs:serviceBeans>
- <ref bean="userServiceRestFul" />
- </jaxrs:serviceBeans>
- <jaxrs:extensionMappings>
- <entry key="json" value="application/json" />
- <entry key="xml" value="application/xml" />
- </jaxrs:extensionMappings>
- </jaxrs:server>
- <bean id="userServiceRestFul" class="com.gosun.jws.cxf.restful.UserServiceRestFul"></bean>
- </beans>
發佈後在瀏覽器中輸入http://localhost:8080/jws/cxf,出現以下見面說明發布成功.
5、客戶端調用
5.一、使用WebClient進行調用(不推薦)
使用org.apache.cxf.jaxrs.client.WebClient調用的代碼以下:
- import javax.ws.rs.core.MediaType;
- import org.apache.cxf.jaxrs.client.WebClient;
- import org.junit.Before;
- import org.junit.Test;
-
-
- public class WebClientTest {
-
- WebClient client = null;
-
- @Before
- public void init() {
- client = WebClient.create("http://localhost:8080/rest/");
- }
-
-
- @Test
- public void getTest() {
-
- client = WebClient
- .create("http://localhost:8080/rest/restFul/get?id=ickes");
- Users u = client.accept(MediaType.APPLICATION_XML).get(Users.class);
- System.out.println(u.toJson());
- }
-
-
- @Test
- public void putTest() {
- Users u = new Users();
- u.setUserId("1");
- u.setUserName("aa");
- u.setUserPwd("bbb");
- client.path("restFul/put/{id}", "ickes")
- .accept(MediaType.APPLICATION_XML).put(u);
- }
-
-
- @Test
- public void postTest() {
- Users u = new Users();
- u.setUserId("1");
- u.setUserName("aa");
- u.setUserPwd("bbb");
- client.accept(MediaType.APPLICATION_XML)
- .path("/restFul/post/{id}", "post").post(u);
- }
-
-
- @Test
- public void deleteTest() {
- client.accept(MediaType.APPLICATION_XML)
- .path("/restFul/delete/{id}", "post").delete();
- }
- }
5.二、使用CXF的客戶端工廠類JAXRSClientFactory進行調用(推薦)
這種方式相對比WebClient要更簡單,直接使用接口中的方法便可,代碼以下:
- import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
- import org.junit.Before;
- import org.junit.Test;
-
- public class JAXRSClientFactoryTest {
- UserService us = null;
-
- @Before
- public void init() {
- us = JAXRSClientFactory.create("http://localhost:8080/jws/cxf/restFul",UserService.class);
- System.out.println(us);
- }
-
-
- @Test
- public void getTest() {
- System.out.println(us.get("a").toJson());
- }
-
-
- @Test
- public void putTest() {
- Users u = new Users();
- u.setUserId("1");
- u.setUserName("aa");
- u.setUserPwd("bbb");
- System.out.println(us.post("a001",u));
- }
-
-
- @Test
- public void postTest() {
- Users u = new Users();
- u.setUserId("1");
- u.setUserName("aa");
- u.setUserPwd("bbb");
- us.post("POST", u);
- }
-
-
- @Test
- public void deleteTest() {
- us.delete("DELETE");
- }
-
- }
若是想在Spring配置文件中配置org.apache.cxf.jaxrs.client.JAXRSClientFactory,代碼以下:
- <bean id="userService" class="org.apache.cxf.jaxrs.client.JAXRSClientFactory" factory-method="create">
- <constructor-arg type="java.lang.String" value="http://localhost:8080/rest/" />
- <constructor-arg type="java.lang.Class" value="com.gosun.jws.cxf.restful.UserService" />
- </bean>