jersey_教程–带有Jersey和Spring的Java REST API设计和实现
jersey
想要在Java中使用REST? 然后您來對地方了,因為在博客文章中,我將向您介紹如何“美麗”地設計REST API,以及如何使用Jersey框架在Java中實現(xiàn)它。 在本教程中開發(fā)的RESTful API將為存儲在MySql數(shù)據(jù)庫中的播客資源演示完整的Create,_read,_update_and_delete(CRUD)功能。
1.例子
為什么?
在開始之前,讓我告訴你為什么寫這篇文章–好吧,我的意圖是將來為Podcastpedia.org提供REST API。 當然,可以像我目前對AJAX調(diào)用那樣使用Spring自己的REST實現(xiàn),但是我還想看看“正式”實現(xiàn)的樣子。 因此,了解該技術的最佳方法是使用該技術構建原型。 這就是我所做的,也是我在這里介紹的,我可以說我對澤西島非常滿意。 繼續(xù)閱讀以了解原因!!!
注意:您可以使用jQuery和Spring MVC訪問我的帖子自動完成搜索框,以了解Spring如何處理REST請求。
它有什么作用?
本教程中管理的資源是播客。 REST API將允許創(chuàng)建,檢索,更新和刪除此類資源。
建筑與技術
該演示應用程序基于“德米特法則(LoD)或最少知識原理” [16]使用了多層體系結構:
- 第一層是通過Jersey實施的REST支持,具有外觀的作用并將邏輯委托給業(yè)務層
- 業(yè)務層是邏輯發(fā)生的地方
- 數(shù)據(jù)訪問層是與持久性存儲(在本例中為MySql數(shù)據(jù)庫)進行通信的地方
關于使用的技術/框架的幾句話:
1.3.1。 澤西島(門面)
Jersey RESTful Web服務框架是開源,生產(chǎn)質(zhì)量的,用于以Java開發(fā)RESTful Web服務的框架,該框架提供對JAX-RS API的支持,并充當JAX-RS (JSR 311和JSR 339)參考實現(xiàn)。
1.3.2。 Spring(業(yè)務層)
我喜歡將東西與Spring粘在一起,這個示例也不例外。 在我看來,沒有更好的方法來制作具有不同功能的POJO。 您將在本教程中找到將Jersey 2與Spring集成所需的功能。
1.3.3。 JPA 2 / Hibernate(持久層)
對于持久層,我仍然使用DAO模式,盡管要實現(xiàn)它,我使用的是JPA 2,正如某些人所說,它應該使DAO變得多余(我不喜歡EntityManager / JPA專用代碼)。 JPA 2的AS支持框架我正在使用Hibernate。
有關Java中的持久性主題的有趣討論,請參見我的Spring,JPA2和Hibernate的Java持久性示例。
1.3.4。 網(wǎng)絡容器
一切都與Maven打包為.war文件,并且可以部署在任何Web容器上–我使用Tomcat和Jetty ,但是也可以是Glassfih,Weblogic,JBoss或WebSphere。
1.3.5。 MySQL
示例數(shù)據(jù)存儲在MySQL表中:
1.3.6。 技術版本
注意:帖子中的主要焦點將是REST api設計及其通過Jersey JAX-RS實現(xiàn)的實現(xiàn),所有其他技術/層均被視為促成因素。
源代碼
此處提供的項目的源代碼可在GitHub上獲得,其中包含有關如何安裝和運行項目的完整說明:
- Codingpedia / Demo-rest-jersey-spring
2.配置
在開始介紹REST API的設計和實現(xiàn)之前,我們需要做一些配置,以便所有這些奇妙的技術可以一起發(fā)揮作用
項目依賴
Jersey Spring擴展名必須存在于項目的類路徑中。 如果使用的是Maven,請將其添加到項目的pom.xml文件中:
pom.xml中的Jersey-spring依賴項
<dependency><groupId>org.glassfish.jersey.ext</groupId><artifactId>jersey-spring3</artifactId><version>${jersey.version}</version><exclusions><exclusion><groupId>org.springframework</groupId><artifactId>spring-core</artifactId></exclusion> <exclusion><groupId>org.springframework</groupId><artifactId>spring-web</artifactId></exclusion><exclusion><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId></exclusion></exclusions> </dependency> <dependency><groupId>org.glassfish.jersey.media</groupId><artifactId>jersey-media-json-jackson</artifactId><version>2.4.1</version> </dependency>注意: jersey-spring3.jar為Spring庫使用其自己的版本,因此要使用所需的庫(在本例中為Spring 4.0.3,請釋放),您需要手動排除這些庫。
代碼警報:如果您想查看項目中還需要哪些其他依賴項(例如Spring,Hibernate,Jetty maven插件,測試等),則可以查看GitHub上完整的pom.xml文件。
web.xml
Web應用程序部署描述符
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><display-name>Demo - Restful Web Application</display-name><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/applicationContext.xml</param-value></context-param><servlet><servlet-name>jersey-serlvet</servlet-name><servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class><init-param><param-name>javax.ws.rs.Application</param-name><param-value>org.codingpedia.demo.rest.RestDemoJaxRsApplication</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>jersey-serlvet</servlet-name><url-pattern>/*</url-pattern></servlet-mapping><resource-ref><description>Database resource rest demo web application </description><res-ref-name>jdbc/restDemoDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth></resource-ref> </web-app>澤西servlet
注意Jersey Servlet配置[行18-33]。 javax.ws.rs.core.Application類定義JAX-RS應用程序的組件(根資源和提供程序類)。 我使用了ResourceConfig,它是Jersey自己對Application類的實現(xiàn),并且提供了高級功能來簡化JAX-RS組件的注冊。 請查閱文檔中的JAX-RS應用程序模型,以了解更多可能性。
我對ResourceConfig類的實現(xiàn)org.codingpedia.demo.rest.RestDemoJaxRsApplication ,注冊了應用程序資源,過濾器,異常映射器和功能:
org.codingpedia.demo.rest.service.MyDemoApplication
package org.codingpedia.demo.rest.service;//imports omitted for brevity /*** Registers the components to be used by the JAX-RS application* * @author ama* */ public class RestDemoJaxRsApplication extends ResourceConfig {/*** Register JAX-RS application components.*/public RestDemoJaxRsApplication() {// register application resourcesregister(PodcastResource.class);register(PodcastLegacyResource.class);// register filtersregister(RequestContextFilter.class);register(LoggingResponseFilter.class);register(CORSResponseFilter.class);// register exception mappersregister(GenericExceptionMapper.class);register(AppExceptionMapper.class);register(NotFoundExceptionMapper.class);// register featuresregister(JacksonFeature.class);register(MultiPartFeature.class);} }請注意:
- org.glassfish.jersey.server.spring.scope.RequestContextFilter ,這是一個Spring過濾器,它提供了JAX-RS和Spring請求屬性之間的橋梁
- org.codingpedia.demo.rest.resource.PodcastsResource ,這是一個“外觀”組件,它通過注釋公開了REST API,并將在稍后的文章中進行詳盡介紹。
- org.glassfish.jersey.jackson.JacksonFeature ,這是注冊Jackson JSON提供程序的功能-應用程序需要它才能理解JSON數(shù)據(jù)
2.1.2.2。 Spring應用程序上下文配置
Spring應用程序上下文配置位于spring/applicationContext.xml下的類路徑中:
Spring應用程序上下文配置
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="org.codingpedia.demo.rest.*" /><!-- ************ JPA configuration *********** --><tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="entityManagerFactory" /></bean><bean id="transactionManagerLegacy" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="entityManagerFactoryLegacy" /></bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="persistenceXmlLocation" value="classpath:config/persistence-demo.xml" /><property name="persistenceUnitName" value="demoRestPersistence" /> <property name="dataSource" ref="restDemoDS" /><property name="packagesToScan" value="org.codingpedia.demo.*" /><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><property name="showSql" value="true" /><property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" /></bean></property></bean> <bean id="entityManagerFactoryLegacy" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="persistenceXmlLocation" value="classpath:config/persistence-demo.xml" /><property name="persistenceUnitName" value="demoRestPersistenceLegacy" /><property name="dataSource" ref="restDemoLegacyDS" /><property name="packagesToScan" value="org.codingpedia.demo.*" /><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><property name="showSql" value="true" /><property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" /></bean></property></bean> <bean id="podcastDao" class="org.codingpedia.demo.rest.dao.PodcastDaoJPA2Impl"/> <bean id="podcastService" class="org.codingpedia.demo.rest.service.PodcastServiceDbAccessImpl" /> <bean id="podcastsResource" class="org.codingpedia.demo.rest.resource.PodcastsResource" /><bean id="podcastLegacyResource" class="org.codingpedia.demo.rest.resource.PodcastLegacyResource" /><bean id="restDemoDS" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton"><property name="jndiName" value="java:comp/env/jdbc/restDemoDB" /><property name="resourceRef" value="true" /> </bean><bean id="restDemoLegacyDS" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton"><property name="jndiName" value="java:comp/env/jdbc/restDemoLegacyDB" /><property name="resourceRef" value="true" /> </bean> </beans>這里沒什么特別的,它只是定義了整個演示應用程序所需的bean(例如podcastsResource ,這是我們REST API的入口點類)。
3. REST API(設計和實現(xiàn))
資源資源
3.1.1。 設計
如前所述,演示應用程序管理播客,這些播客代表了我們REST API中的資源。 資源是REST中的核心概念,其主要特征有兩個:
- 每個引用都有一個全局標識符(例如HTTP中的URI )。
- 具有一個或多個表示形式,它們公開給外部世界并可以使用(在此示例中,我們將主要使用JSON表示形式)
在REST中,資源通常用名詞(播客,客戶,用戶,帳戶等)而不是動詞(getPodcast,deleteUser等)表示。
本教程中使用的端點是:
- /podcasts – (請注意復數(shù)) URI標識了表示播客集合的資源
- /podcasts/{id} –通過播客ID標識播客資源的URI
3.1.2。 實作
為了簡單起見,播客將僅具有以下屬性:
- id –唯一標識播客
- feed -播客的URL飼料
- title –播客標題
- linkOnPodcastpedia –您可以在Podcastpedia.org上找到播客
- description -播客的簡短描述
我本可以只使用一個Java類來表示代碼中的播客資源,但是在那種情況下,該類及其屬性/方法可能會因JPA和XML / JAXB / JSON注釋而變得混亂不堪。 我想避免這種情況,而是使用了兩個具有幾乎相同屬性的表示形式:
- PodcastEntity.java –在DB和業(yè)務層中使用的JPA注釋類
- Podcast.java –在正面和業(yè)務層中使用的帶有JAXB / JSON注釋的類
注意:我仍在嘗試使自己相信這是更好的方法,因此,如果對此有任何建議,請發(fā)表評論。
Podcast.java類的外觀類似于以下內(nèi)容:
Podcast.java
package org.codingpedia.demo.rest.resource;//imports omitted for brevity/*** Podcast resource placeholder for json/xml representation * * @author ama**/ @SuppressWarnings("restriction") @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Podcast implements Serializable {private static final long serialVersionUID = -8039686696076337053L;/** id of the podcast */@XmlElement(name = "id")?? ?private Long id;/** title of the podcast */@XmlElement(name = "title")?? ?private String title;/** link of the podcast on Podcastpedia.org */@XmlElement(name = "linkOnPodcastpedia")?? ?private String linkOnPodcastpedia;/** url of the feed */@XmlElement(name = "feed")?? ?private String feed;/** description of the podcast */@XmlElement(name = "description")private String description; /** insertion date in the database */@XmlElement(name = "insertionDate")@XmlJavaTypeAdapter(DateISO8601Adapter.class)?? ?@PodcastDetailedViewprivate Date insertionDate;public Podcast(PodcastEntity podcastEntity){try {BeanUtils.copyProperties(this, podcastEntity);} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public Podcast(String title, String linkOnPodcastpedia, String feed,String description) {this.title = title;this.linkOnPodcastpedia = linkOnPodcastpedia;this.feed = feed;this.description = description;}public Podcast(){}//getters and setters now shown for brevity }并轉(zhuǎn)換為以下JSON表示形式,它實際上是當今與REST一起使用的事實上的媒體類型:
{"id":1,"title":"Quarks & Co - zum Mitnehmen-modified","linkOnPodcastpedia":"http://www.podcastpedia.org/podcasts/1/Quarks-Co-zum-Mitnehmen","feed":"http://podcast.wdr.de/quarks.xml","description":"Quarks & Co: Das Wissenschaftsmagazin","insertionDate":"2014-05-30T10:26:12.00+0200" }即使JSON越來越成為REST API中的首選表示形式,您也不應忽略XML表示形式,因為大多數(shù)系統(tǒng)仍使用XML格式與其他方進行通信。
好消息是,在澤西島,您可以一槍殺死兩只兔子–使用JAXB bean(如上所述),您將能夠使用相同的Java模型來生成JSON和XML表示形式。 另一個優(yōu)勢是使用這種模型的簡單性以及Java SE Platform中API的可用性。
注意:本教程中定義的大多數(shù)方法都將產(chǎn)生和使用application / xml媒體類型,其中application / json是首選方式。
方法
在向您介紹API之前,讓我告訴您
- 創(chuàng)建= POST
- 讀取=獲取
- 更新= PUT
- 刪除=刪除
并且不是嚴格的1:1映射。 為什么? 因為您還可以將PUT用于創(chuàng)建,將POST用于更新。 在接下來的段落中將對此進行解釋和演示。
注意:對于“讀取和刪除”非常清楚,它們確實使用GET和DELETE HTTP操作一對一映射。 無論如何,REST是一種體系結構樣式,不是一種規(guī)范,您應該使體系結構適應您的需求,但是如果您想公開自己的API并希望有人使用它,則應該遵循一些“最佳實踐”。
如前所述, PodcastRestResource類是處理所有其余請求的類:
package org.codingpedia.demo.rest.resource; //imports ...................... @Component @Path("/podcasts") public class PodcastResource {@Autowiredprivate PodcastService podcastService;..................... }注意類定義之前的@Path("/podcasts") –與播客資源相關的所有內(nèi)容都將在此路徑下發(fā)生。 @Path批注的值是相對URI路徑。 在上面的示例中,Java類將托管在URI路徑/podcasts 。 PodcastService接口將業(yè)務邏輯公開給REST外觀層。
代碼警報:您可以在GitHub – PodcastResource.java上找到該類的全部內(nèi)容。 我們將逐步介紹該文件,并說明與不同操作相對應的不同方法。
3.2.1。 創(chuàng)建播客
3.2.1.1。 設計
盡管資源創(chuàng)建的“最著名”方法是使用POST,但是如前所述,要創(chuàng)建新資源,我可以同時使用POST和PUT方法,而我做到了:
| 描述 | URI | HTTP方法 | HTTP狀態(tài)響應 |
| 添加新的播客 | /播客/ | 開機自檢 | 創(chuàng)建了201 |
| 添加新的播客(必須發(fā)送所有值) | / podcasts / {id} | 放 | 創(chuàng)建了201 |
使用POST(不是冪等)之間的最大區(qū)別
“ POST方法用于請求源服務器接受請求中包含的實體作為請求行中Request-URI所標識資源的新下屬[…]如果在源服務器上創(chuàng)建了資源,響應應為201(已創(chuàng)建),并包含描述請求狀態(tài)并引用新資源的實體以及位置標頭” [1]
和PUT(冪等)
“ PUT方法請求將封閉的實體存儲在提供的Request-URI […]下,如果Request-URI沒有指向現(xiàn)有資源,并且請求用戶代理能夠?qū)⒃揢RI定義為新資源,原始服務器可以使用該URI創(chuàng)建資源。 如果創(chuàng)建了新資源,則原始服務器務必通過201(已創(chuàng)建)響應通知用戶代理。” [1]
是對于PUT,您應該事先知道將在其中創(chuàng)建資源的位置,并發(fā)送該條目的所有可能值。
3.2.1.2。 實作
3.2.1.2.1。 使用POST創(chuàng)建單個資源
從JSON創(chuàng)建單個播客資源
/*** Adds a new resource (podcast) from the given json format (at least title* and feed elements are required at the DB level)* * @param podcast* @return* @throws AppException*/ @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.TEXT_HTML }) public Response createPodcast(Podcast podcast) throws AppException {Long createPodcastId = podcastService.createPodcast(podcast);return Response.status(Response.Status.CREATED)// 201.entity("A new podcast has been created").header("Location","http://localhost:8888/demo-rest-jersey-spring/podcasts/"+ String.valueOf(createPodcastId)).build(); }注解
- @POST –表示該方法響應HTTP POST請求
- @Consumes({MediaType.APPLICATION_JSON}) –定義該方法接受的媒體類型,在這種情況下為"application/json"
- @Produces({MediaType.TEXT_HTML}) –定義方法可以產(chǎn)生的媒體類型,在這種情況下為"text/html" 。
響應
- 成功:文本/ html文檔,HTTP狀態(tài)為201 Created ,并且Location標頭指定在何處創(chuàng)建資源
- 錯誤時:
- 400 Bad request如果沒有提供足夠的數(shù)據(jù)
3.2.1.2.2。 使用PUT創(chuàng)建單個資源(“播客”)
這將在下面的“更新播客”部分中進行處理。
3.2.1.2.3。 獎勵–從表單創(chuàng)建單個資源(“播客”)
從表單創(chuàng)建單個播客資源
/*** Adds a new podcast (resource) from "form" (at least title and feed* elements are required at the DB level)* * @param title* @param linkOnPodcastpedia* @param feed* @param description* @return* @throws AppException*/ @POST @Consumes({ MediaType.APPLICATION_FORM_URLENCODED }) @Produces({ MediaType.TEXT_HTML }) @Transactional public Response createPodcastFromApplicationFormURLencoded(@FormParam("title") String title,@FormParam("linkOnPodcastpedia") String linkOnPodcastpedia,@FormParam("feed") String feed,@FormParam("description") String description) throws AppException {Podcast podcast = new Podcast(title, linkOnPodcastpedia, feed,description);Long createPodcastid = podcastService.createPodcast(podcast);return Response.status(Response.Status.CREATED)// 201.entity("A new podcast/resource has been created at /demo-rest-jersey-spring/podcasts/"+ createPodcastid).header("Location","http://localhost:8888/demo-rest-jersey-spring/podcasts/"+ String.valueOf(createPodcastid)).build(); }注解
- @POST –表示該方法響應HTTP POST請求
- @Consumes({MediaType.APPLICATION_FORM_URLENCODED}) –定義該方法接受的媒體類型,在這種情況下為"application/x-www-form-urlencoded"
- @FormParam –出現(xiàn)在方法的輸入?yún)?shù)之前,此批注將請求實體主體中包含的表單參數(shù)的值綁定到資源方法參數(shù)。 除非使用“ Encoded注釋”將其禁用,否則將對值進行URL解碼
- @Produces({MediaType.TEXT_HTML}) –定義該方法可以產(chǎn)生的媒體類型,在這種情況下為“ text / html”。 響應將是狀態(tài)為201的html文檔,它向調(diào)用方指示請求已得到滿足并導致創(chuàng)建了新資源。
響應
- 成功:文本/ html文檔,HTTP狀態(tài)為201 Created ,并且Location標頭指定在何處創(chuàng)建資源
- 錯誤時:
- 400 Bad request如果沒有提供足夠的數(shù)據(jù)
3.2.2。 閱讀播客
3.2.2.1。 設計
該API支持兩種讀取操作:
- 返回播客的集合
- 返回由ID標識的播客
| 描述 | URI | HTTP方法 | HTTP狀態(tài)響應 |
| 返回所有播客 | / podcasts /?orderByInsertionDate = {ASC | DESC}&numberDaysToLookBack = {val} | 得到 | 200 OK |
| 添加新的播客(必須發(fā)送所有值) | / podcasts / {id} | 得到 | 200 OK |
請注意收集資源的查詢參數(shù)– orderByInsertionDate和numberDaysToLookBack。 將過濾器添加為URI中的查詢參數(shù)而不是路徑的一部分是很有意義的。
3.2.2.2。 實作
3.2.2.2.1。 閱讀所有播客(“ /”)
閱讀所有資源
/*** Returns all resources (podcasts) from the database* * @return* @throws IOException* @throws JsonMappingException* @throws JsonGenerationException* @throws AppException*/ @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public List<Podcast> getPodcasts(@QueryParam("orderByInsertionDate") String orderByInsertionDate,@QueryParam("numberDaysToLookBack") Integer numberDaysToLookBack)throws JsonGenerationException, JsonMappingException, IOException,AppException {List<Podcast> podcasts = podcastService.getPodcasts(orderByInsertionDate, numberDaysToLookBack);return podcasts; }注解
- @GET –表示該方法響應HTTP GET請求
- @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) –定義該方法可以產(chǎn)生的媒體類型),在這種情況下為"application/json"或"application/xml" (您需要在@XmlRootElement前面Podcast類)。 響應將是JSON或XML格式的播客列表。
響應
- 數(shù)據(jù)庫中的播客列表和HTTP狀態(tài)200 OK
3.2.2.2.1。 閱讀一個播客
通過ID讀取一種資源
@GET @Path("{id}") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response getPodcastById(@PathParam("id") Long id)throws JsonGenerationException, JsonMappingException, IOException,AppException {Podcast podcastById = podcastService.getPodcastById(id);return Response.status(200).entity(podcastById).header("Access-Control-Allow-Headers", "X-extra-header").allow("OPTIONS").build(); }注解
- @GET –表示該方法響應HTTP GET請求
- @Path("{id}") –標識類方法將為其請求服務的URI路徑。 “ id”值是構成URI路徑模板的嵌入式變量。 它與@PathParam變量結合使用。
- @PathParam("id") –將URI模板參數(shù)(“ id”)的值綁定到資源方法參數(shù)。
- @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) –定義方法可以產(chǎn)生的媒體類型,在這種情況下為"application/json"或"application/xml" (您需要在Podcast前面的@XmlRootElement課)。
響應
- 成功:請求的播客的HTTP狀態(tài)為200 OK 。 格式為xml或JSON,具體取決于客戶端發(fā)送的Accept-header值(可能押于application / xml或application / json)
- 錯誤: 404 Not found如果數(shù)據(jù)庫中不存在具有給定ID的播客,則找不到
3.2.3。 更新播客
3.2.3.1。 設計
| 描述 | URI | HTTP方法 | HTTP狀態(tài)響應 |
| 更新播客(完整) | / podcasts / {id} | 放 | 200 OK |
| 更新播客(部分) | / podcasts / {id} | 開機自檢 | 200 OK |
在REST領域,您將進行兩種更新:
要進行完整的更新,很明顯可以使用PUT方法,并且符合RFC 2616中該方法的規(guī)范。
現(xiàn)在,對于部分更新,有很多關于使用什么的建議/辯論:
讓我告訴我為什么我認為第一種選擇(使用PUT)是行不通的。 好吧,根據(jù)規(guī)格
“如果請求URI引用了已經(jīng)存在的資源,則應將封閉的實體視為駐留在源服務器上的實體的修改版本。” [1]
如果我只想更新ID為2的播客的title屬性
PUT命令進行部分更新
PUT http://localhost:8888/demo-rest-jersey-spring/podcasts/2 HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/json Content-Length: 155 Host: localhost:8888 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5){"title":"New Title" }然后,根據(jù)規(guī)范,“存儲”在該位置的資源應僅具有ID和標題,顯然我的意圖不是。
通過POST的第二個選項……好吧,我們可以“濫用”此選項,這恰恰是我在實現(xiàn)中所做的,但是它似乎與我不符,因為POST的規(guī)范指出:
“發(fā)布的實體從屬于該URI,就像文件從屬于包含它的目錄,新聞文章從屬于發(fā)布它的新聞組或記錄從屬于數(shù)據(jù)庫一樣。” [1 ]
在我看來,這似乎不是部分更新案例……
第三種選擇是使用PATCH,我想這是該方法成功的主要原因:
“幾個擴展超文本傳輸??協(xié)議(HTTP)的應用程序需要功能來進行部分資源修改。 現(xiàn)有的HTTP PUT方法僅允許完全替換文檔。該提案添加了新的HTTP方法PATCH,以修改現(xiàn)有的HTTP資源。” [2]
我很確定將來會使用它進行部分更新,但是由于它尚不是規(guī)范的一部分,并且尚未在Jersey中實現(xiàn),因此我選擇在演示中使用POST的第二個選項。 如果您真的想用PATCH在Java中實現(xiàn)部分更新,請查看這篇文章– JAX-RS 2.0中的透明PATCH支持
3.2.3.1。 實作
3.2.3.1.1。 完整更新
創(chuàng)建或完全更新資源實現(xiàn)方法
@PUT @Path("{id}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.TEXT_HTML }) public Response putPodcastById(@PathParam("id") Long id, Podcast podcast)throws AppException {Podcast podcastById = podcastService.verifyPodcastExistenceById(id);if (podcastById == null) {// resource not existent yet, and should be created under the// specified URILong createPodcastId = podcastService.createPodcast(podcast);return Response.status(Response.Status.CREATED)// 201.entity("A new podcast has been created AT THE LOCATION you specified").header("Location","http://localhost:8888/demo-rest-jersey-spring/podcasts/"+ String.valueOf(createPodcastId)).build();} else {// resource is existent and a full update should occurpodcastService.updateFullyPodcast(podcast);return Response.status(Response.Status.OK)// 200.entity("The podcast you specified has been fully updated created AT THE LOCATION you specified").header("Location","http://localhost:8888/demo-rest-jersey-spring/podcasts/"+ String.valueOf(id)).build();} }注解
- @PUT –表示該方法響應HTTP PUT請求
- @Path("{id}") –標識類方法將為其請求服務的URI路徑。 “ id”值是構成URI路徑模板的嵌入式變量。 它與@PathParam變量結合使用。
- @PathParam("id") –將URI模板參數(shù)(“ id”)的值綁定到資源方法參數(shù)。
- @Consumes({MediaType.APPLICATION_JSON}) –定義該方法接受的媒體類型,在這種情況下為"application/json"
- @Produces({MediaType.TEXT_HTML}) –定義方法可以產(chǎn)生的媒體類型,在這種情況下為“ text / html”。
將是一個html文檔,其中包含不同的消息和狀態(tài),具體取決于采取了哪些措施
回應
- 在創(chuàng)造時
- 成功時: 201 Created并且在Location標頭中指定了創(chuàng)建資源的指定位置
- 錯誤: 400 Bad request如果未提供插入所需的最低屬性
- 完整更新
- 成功: 200 OK
3.2.3.1.2。 部分更新
部分更新
//PARTIAL update @POST @Path("{id}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.TEXT_HTML }) public Response partialUpdatePodcast(@PathParam("id") Long id, Podcast podcast) throws AppException {podcast.setId(id);podcastService.updatePartiallyPodcast(podcast);return Response.status(Response.Status.OK)// 200.entity("The podcast you specified has been successfully updated").build(); }注解
- @POST –表示該方法響應HTTP POST請求
- @Path("{id}") –標識類方法將為其請求服務的URI路徑。 “ id”值是構成URI路徑模板的嵌入式變量。 它與@PathParam變量結合使用。
- @PathParam("id") –將URI模板參數(shù)(“ id”)的值綁定到資源方法參數(shù)。
- @Consumes({MediaType.APPLICATION_JSON}) –定義該方法接受的媒體類型,在這種情況下為"application/json"
- @Produces({MediaType.TEXT_HTML}) –定義方法可以產(chǎn)生的媒體類型,在這種情況下為"text/html" 。
響應
- 成功: 200 OK
- 錯誤: 404 Not Found ,如果在提供的位置沒有資源可用
3.2.4。 刪除播客
3.2.4.1。 設計
| 描述 | URI | HTTP方法 | HTTP狀態(tài)響應 |
| 刪除所有播客 | /播客/ | 刪除 | 204沒有內(nèi)容 |
| 刪除指定位置的播客 | / podcasts / {id} | 刪除 | 204沒有內(nèi)容 |
3.2.4.2。 實作
3.2.4.2.1。 刪除所有資源
刪除所有資源
@DELETE @Produces({ MediaType.TEXT_HTML }) public Response deletePodcasts() {podcastService.deletePodcasts();return Response.status(Response.Status.NO_CONTENT)// 204.entity("All podcasts have been successfully removed").build(); }注解
- @DELETE –表示該方法響應HTTP DELETE請求
- @Produces({MediaType.TEXT_HTML}) –定義該方法可以產(chǎn)生的媒體類型,在這種情況下為“ text / html”。
響應
- 響應將是一個html文檔,狀態(tài)為204 No content,向調(diào)用方指示請求已完成。
3.2.4.2.2。 刪除一項資源
刪除一項資源
@DELETE @Path("{id}") @Produces({ MediaType.TEXT_HTML }) public Response deletePodcastById(@PathParam("id") Long id) {podcastService.deletePodcastById(id);return Response.status(Response.Status.NO_CONTENT)// 204.entity("Podcast successfully removed from database").build(); }注解
- @DELETE –表示該方法響應HTTP DELETE請求
- @Path("{id}") –標識類方法將為其請求服務的URI路徑。 “ id”值是構成URI路徑模板的嵌入式變量。 它與@PathParam變量結合使用。
- @PathParam("id") –將URI模板參數(shù)(“ id”)的值綁定到資源方法參數(shù)。
- @Produces({MediaType.TEXT_HTML}) –定義該方法可以產(chǎn)生的媒體類型,在這種情況下為“ text / html”。
響應
- 成功時:如果刪除播客,則返回204 No Content成功狀態(tài)
- 錯誤:播客不再可用,并且返回404 Not found狀態(tài)
4.記錄
當日志記錄級別設置為DEBUG時,將記錄每個請求的路徑和響應的實體。 在Jetty過濾器的幫助下,它像包裝器一樣具有AOP樣式的功能。
有關此問題的更多詳細信息,請參閱我的文章“ 如何使用SLF4J和Logback登錄Spring” 。
5.異常處理
如果出現(xiàn)錯誤,我決定采用統(tǒng)一的錯誤消息結構進行響應。 這是一個錯誤響應的示例:
示例–錯誤消息響應
{"status": 400,"code": 400,"message": "Provided data not sufficient for insertion","link": "http://www.codingpedia.org/ama/tutorial-rest-api-design-and-implementation-with-jersey-and-spring","developerMessage": "Please verify that the feed is properly generated/set" }注意:請繼續(xù)關注,因為以下文章將提供有關使用Jersey的REST中的錯誤處理的更多詳細信息。
6.在服務器端添加CORS支持
我擴展了為該教程開發(fā)的API的功能,以支持服務器端的跨源資源共享(CORS) 。
有關此問題的更多詳細信息,請參閱我的文章“ 如何使用Jersey使用Java在服務器端添加CORS支持” 。
7.測試
Java集成測試
為了測試該應用程序,我將使用Jersey Client并針對正在運行的Jetty服務器和部署了該應用程序的服務器執(zhí)行請求。 為此,我將使用Maven故障安全插件。
7.1.1。 組態(tài)
7.1.1.1 Jersey客戶端依賴性
要構建Jersey客戶端,必須在類路徑中提供jersey-client jar。 使用Maven,您可以將其作為依賴項添加到pom.xml文件中:
Jersey Client Maven依賴項
<dependency><groupId>org.glassfish.jersey.core</groupId><artifactId>jersey-client</artifactId><version>${jersey.version}</version><scope>test</scope> </dependency>7.1.1.2。 故障安全插件
Failsafe插件用于構建生命周期的集成測試和驗證階段,以執(zhí)行應用程序的集成測試。 Failsafe插件在集成測試階段不會使構建失敗,因此可以執(zhí)行集成測試后階段。要使用故障安全插件,您需要將以下配置添加到pom.xml
Maven故障安全插件配置
<plugins>[...]<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-failsafe-plugin</artifactId><version>2.16</version><executions><execution><id>integration-test</id><goals><goal>integration-test</goal></goals></execution><execution><id>verify</id><goals><goal>verify</goal></goals></execution></executions></plugin>[...] </plugins>7.1.1.2。 Jetty Maven插件
集成測試將針對正在運行的碼頭服務器執(zhí)行,該服務器僅在執(zhí)行測試時啟動。 為此,您必須在jetty-maven-plugin配置以下執(zhí)行:
用于集成測試的Jetty Maven插件配置
<plugins><plugin><groupId>org.eclipse.jetty</groupId><artifactId>jetty-maven-plugin</artifactId><version>${jetty.version}</version><configuration><jettyConfig>${project.basedir}/src/main/resources/config/jetty9.xml</jettyConfig><stopKey>STOP</stopKey><stopPort>9999</stopPort><stopWait>5</stopWait><scanIntervalSeconds>5</scanIntervalSeconds>[...]</configuration><executions><execution><id>start-jetty</id><phase>pre-integration-test</phase><goals><!-- stop any previous instance to free up the port --><goal>stop</goal> <goal>run-exploded</goal></goals><configuration><scanIntervalSeconds>0</scanIntervalSeconds><daemon>true</daemon></configuration></execution><execution><id>stop-jetty</id><phase>post-integration-test</phase><goals><goal>stop</goal></goals></execution></executions></plugin>[...] </plugins>注意:在pre-integration-test階段,在停止任何正在運行的實例以釋放端口之后,將啟動Jetty服務器,在post-integration-phase ,它將停止。 必須將scanIntervalSeconds設置為0,并將daemon為true。
代碼警報:在GitHub上找到完整的pom.xml文件
7.1.2。 建立整合測試
我正在使用JUnit作為測試框架。 默認情況下,故障安全插件將自動包含具有以下通配符模式的所有測試類:
- "**/IT*.java" –包括其所有子目錄以及以“ IT”開頭的所有Java文件名。
- "**/*IT.java" –包括其所有子目錄以及所有以“ IT”結尾的java文件名。
- "**/*ITCase.java" –包括其所有子目錄以及所有以“ ITCase”結尾的java文件名。
我已經(jīng)創(chuàng)建了一個測試類RestDemoServiceIT ,它將測試讀取(GET)方法,但其他所有過程均應相同:
public class RestDemoServiceIT {[....]@Testpublic void testGetPodcast() throws JsonGenerationException,JsonMappingException, IOException {ClientConfig clientConfig = new ClientConfig();clientConfig.register(JacksonFeature.class);Client client = ClientBuilder.newClient(clientConfig);WebTarget webTarget = client.target("http://localhost:8888/demo-rest-jersey-spring/podcasts/2");Builder request = webTarget.request(MediaType.APPLICATION_JSON);Response response = request.get();Assert.assertTrue(response.getStatus() == 200);Podcast podcast = response.readEntity(Podcast.class);ObjectMapper mapper = new ObjectMapper();System.out.print("Received podcast from database *************************** "+ mapper.writerWithDefaultPrettyPrinter().writeValueAsString(podcast));} }注意:
- 我也必須為客戶端注冊JacksonFeature,以便可以編組JSON格式的播客響應– response.readEntity(Podcast.class)
- 我正在針對端口8888上正在運行的Jetty進行測試–下一節(jié)將向您展示如何在所需的端口上啟動Jetty
- 我希望我的要求為200
- 借助org.codehaus.jackson.map.ObjectMapper幫助,我以相當格式顯示了JSON響應
7.1.3。 運行集成測試
可以通過調(diào)用構建生命周期的verify階段來調(diào)用故障安全插件。
Maven命令調(diào)用集成測試
mvn verify要在端口8888上啟動碼頭,您需要將jetty.port屬性設置為8888。在Eclipse中,我使用以下配置:
從Eclipse運行集成測試
與SoapUI的集成測試
最近,在大量使用SoapUI測試基于SOAP的Web服務之后,我重新發(fā)現(xiàn)了SoapUI 。 使用最新版本(在撰寫本文時,最新版本是5.0.0),它提供了很好的功能來測試基于REST的Web服務,并且以后的版本應該對此進行改進。 因此,除非您開發(fā)自己的框架/基礎結構來測試REST服務,否則為什么不嘗試使用SoapUI。 我做到了,到目前為止,我對結果感到滿意,因此我決定制作一個視頻教程,現(xiàn)在您可以在我們的頻道的YouTube上找到該視頻教程:
8.版本控制
有三種主要可能性
因為我是開發(fā)人員,而不是RESTafarian ,所以我會選擇URL選項。 在本例中,我在實現(xiàn)方面要做的就是將PodcastResource類上的@Path的值批注從修改為
路徑中的版本控制
@Component @Path("/v1/podcasts") public class PodcastResource {...}當然,在生產(chǎn)應用程序上,您不希望每個資源類都以版本號為前綴,而是希望以某種方式通過AOP過濾器對版本進行處理。 也許這樣的事情會出現(xiàn)在下面的帖子中……
以下是一些對事情有更好理解的人們的寶貴資源:
- [視頻] REST + JSON API設計–開發(fā)人員最佳實踐
- 您的API版本錯誤,這就是為什么我決定通過@troyhunt用3種不同的錯誤方式進行操作
- REST服務版本控制
- API版本控制的最佳做法? –關于Stackoverflow的有趣討論
9.總結
好,就是這樣。 如果您走了這么遠,我必須向您表示祝賀,但是我希望您可以從本教程中了解有關REST的知識,例如設計REST API,用Java實現(xiàn)REST API,測試REST API等。 如果您愿意,我將不勝感激,如果您通過發(fā)表評論或在Twitter,Google +或Facebook上分享評論來幫助其傳播。 謝謝! 不要忘記也查看Podcastpedia.org ,您肯定會找到有趣的Podcast和情節(jié)。 感謝您的支持。
如果您喜歡這篇文章,我們將非常感謝您為我們的工作做出的一點貢獻! 立即向Paypal捐款。
10.資源
源代碼
- GitHub – Codingpedia / demo-rest-jersey-spring (有關如何安裝和運行項目的說明)
網(wǎng)絡資源
Codingpedia相關資源
- 帶有Spring,JPA2和Hibernate的Java持久性示例
- http://www.codingpedia.org/ama/spring-mybatis-integration-example/
- http://www.codingpedia.org/ama/tomcat-jdbc-connection-pool-configuration-for-production-and-development/
- http://www.codingpedia.org/ama/error-when-executing-jettyrun-with-jetty-maven-plugin-version-9-java-lang-unsupportedclassversionerror-unsupported-major-minor-version-51-0/
- http://www.codingpedia.org/ama/autocomplete-search-box-with-jquery-and-spring-mvc/
翻譯自: https://www.javacodegeeks.com/2014/08/tutorial-rest-api-design-and-implementation-in-java-with-jersey-and-spring.html
jersey
總結
以上是生活随笔為你收集整理的jersey_教程–带有Jersey和Spring的Java REST API设计和实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: chrome开发者工具各种骚技巧
- 下一篇: 几个高逼格 Linux 命令!