http://www.codingpedia.org/ama/restful-web-services-example-in-java-with-jersey-spring-and-mybatis/
RESTful Web Services Example in Java with Jersey, Spring and MyBatis
Note: At the time of writing this post I was just starting with REST and Jersey so I suggest you have a look at Tutorial – REST API design and implementation in Java with Jersey and Spring instead. My gained REST knowledge will be from now on reflected in this post, which is already an “(r)evolution” regarding REST API design, REST best practices used and backend architecture/implementation supporting the REST API presented in the tutorial.
Looking to REST? In Java? There’s never time for that :), but if you are looking to use an “architectural style consisting of a coordinated set of constraints applied to components, connectors, and data elements, within a distributed hypermedia system” in Java, then you have come to the right place, because in this post I will present a simple RESTful API that maps REST calls to backend services offering CRUD functionality.
Note: I will not focus too much on Representational state transfer (REST) itself, because there are plenty of resources on the topic in the internet, some of which I listed under Resources at the end of the post.
1. The example
1.1. Why?
My intention is to move some of the parts from Podcastpedia.org, that are currently implemented in Spring MVC, to JavaScript-land and for that I’ll need to use more backend REST web services. Of course I could use Spring’s own REST implementation, as I currently do for the AJAX calls, but I wanted also to see how the “official” implementation looks like.
Note: You can visit my post Autocomplete search box with jQuery and Spring MVC to see how Spring handles REST requests.
1.2. What does it do?
So, the best way to get to know the technology is build a prototype with it. And that’s exactly what I did and what I will present in this post. I’ve build a simple application that “manages” podcasts via a REST API. It does CRUD operations on a single database table (Podcasts), triggered via the REST web services API. Though fairly simple, the example highlights the most common annotations you’ll need to build your own REST API.
1.3. Architecture and technologies
1.3.1. Jersey
The architecture is straightforward: with any REST client you can call the application’s API exposed via Jersey RESTful Web Services in JAVA. The Jersey RESTful Web Services framework is open source, production quality, framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 & JSR 339) Reference Implementation.
1.3.2. Spring
I like glueing stuff together with Spring, and this example is no exception. You’ll find out how Jersey 2 integrates with Spring.
1.3.3. MyBatis
For the persistence layer, I chose Mybatis because I like it the most and it integrates fairly easy with Spring (see my post Spring MyBatis integration example for more on that), but you are free to choose any framework and technology you’re familiar with (e.g. JPA/Hibernate, Hibernate, JDBC etc).
Note: If you want to see how the persistence layer is implemented for the same application with JPA2 and Hibernate 4 see the post Java Persistence Example with Spring, JPA2 and Hibernate.
1.3.4. Web Container
Everything gets packaged as a .war
file and can be deployed on any web container – I used Tomcat and Jetty but, it could also be Glassfih, Weblogic, JBoss or WebSphere.
1.3.5. MySQL
The sample data is stored in a MySQL table:
Note: The main focus in the post will be on the Jersey JAX-RS implementation, all the other technologies are viewed as enablers.
1.3.6. Technologies
- Jersey 2.4
- Spring 3.2
- Maven 3
- Tomcat 7
- Jetty 9
- MySql 5.6
1.3.7. Follow along
If you want to follow along, you find all you need on GitHub:
2. The coding
2.1. Configuration
2.1.1. Project dependencies
Among other things you need to have Jersey Spring extension in your
project’s classpath. You can easily add that with Maven by having the
following dependencies to the pom.xml
file of the project:
dependency groupIdglassfishjerseygroupId artifactIdjerseyspring3artifactId version2.4.1version exclusions exclusion groupIdspringframeworkgroupId artifactIdspringartifactId exclusion exclusion groupIdspringframeworkgroupId artifactIdspringartifactId exclusion exclusion groupIdspringframeworkgroupId artifactIdspringbeansartifactId exclusion exclusions dependency dependency groupIdglassfishjerseymediagroupId artifactIdjerseymediajacksonartifactId version2.4.1version dependency |
Note: The jersey-spring3.jar, uses its own version for Spring libraries, so to use the ones you want, you need to exclude these libraries manually.
Code alert: If you want to see what other dependencies are used (for Spring, Jetty, testing) in the project or how Jetty is configured so that you can start the project directly in Jetty, you can download the complete pom.xml file from GitHub – https://github.com/amacoder/demo-restWS-spring-jersey-tomcat-mybatis/blob/master/pom.xml
2.1.2. Web Application Deployment Descriptor – web.xml
<?version"1.0"encoding"UTF-8"?> version"3.0"xmlns"http://java.sun.com/xml/ns/javaee" xmlns"http://www.w3.org/2001/XMLSchema-instance" schemaLocation"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" displayRestful Applicationdisplay listener listenerclass springframeworkcontextContextLoaderListener listenerclass listener contextparam paramcontextConfigLocationparam paramvalueclasspathspringapplicationContextparamvalue contextparam servlet servletjerseyserlvetservlet servletclass glassfishjerseyservletServletContainer servletclass param paramjavaxApplicationparam paramvaluecodingpediaserviceMyApplicationparamvalue param startupstartup servlet servletmapping servletjerseyserlvetservlet patternpattern servletmapping resource descriptionDatabase resource applicationdescription restDemoDB javaxDataSource Container resource |
2.1.2.1. Jersey-servlet
Notice the Jersey servlet configuration [lines 18-33]. The javax.ws.rs.core.Application
class defines the components of the JAX-RS application. Because I extended the Application (ResourceConfig)
class to provide the list of relevant root resource classes (getResources()
) and singletons (getSingletons()
), i.e. the JAX-RS application model, I needed to register it in my web application web.xml
deployment descriptor using a Servlet or Servlet filter initialization parameter with a name of javax.ws.rs.Application.
Check out the documentation for other possibilities.
The implementation of org.codingpedia.demo.rest.service.MyApplication
looks like the following in the project:
packagecodingpediaservice import glassfishjerseyjacksonJacksonFeature import glassfishjerseyserverResourceConfig import glassfishjerseyserverspringscopeRequestContextFilter * Registers the components to be used by the JAX-RS application * @author ama publicclassMyDemoApplicationextendsResourceConfig * Register JAX-RS application components. publicMyDemoApplication registerRequestContextFilterclass registerPodcastRestServiceclass registerJacksonFeatureclass |
The class registers the following components
org.glassfish.jersey.server.spring.scope.RequestContextFilter
, which is a Spring filter that provides a bridge between JAX-RS and Spring request attributesorg.codingpedia.demo.rest.service.PodcastRestService
, which is the service component that exposes the REST API via annotations, will be presented later in detailorg.glassfish.jersey.jackson.JacksonFeature
, which is a feature that registers Jackson JSON providers – you need it for the application to understand JSON data
2.1.2.2. Spring application context configuration
The Spring application context configuration is located in the classpath under spring/applicationContext.xml
:
beans xmlns"http://www.springframework.org/schema/beans" xmlns"http://www.w3.org/2001/XMLSchema-instance" xmlnscontext"http://www.springframework.org/schema/context" xmlns"http://www.springframework.org/schema/tx" schemaLocation http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" contextcomponentpackage"org.codingpedia.demo.rest.*" Instruct Spring perform declarative transaction management automatically annotated classes annotationdriven transactionmanager"transactionManager" "transactionManager" class"org.springframework.jdbc.datasource.DataSourceTransactionManager" property"dataSource""dataSource" MyBATIS beans configuration "podcastDao"class"org.mybatis.spring.mapper.MapperFactoryBean" property"sqlSessionFactory""sqlSessionFactory" property"mapperInterface"value"org.codingpedia.demo.rest.dao.PodcastDao" "sqlSessionFactory"class"org.mybatis.spring.SqlSessionFactoryBean" property"dataSource""dataSource" property"configLocation"value"classpath:config/mybatisV3.xml" "podcastRestService"class"org.codingpedia.demo.rest.service.PodcastRestService" "dataSource"class"org.springframework.jndi.JndiObjectFactoryBean"scope"singleton" property"jndiName"value"java:comp/env/jdbc/restDemoDB" property"resourceRef"value"true" beans |
Nothing special here, it just defines the beans that are needed throughout the demo application. The most important one is the podcastRestService
which is actually the entry point class for our RESTful API, and will be thouroughly described in the next paragraphs.
2.2. The RESTful API
2.2.1. Resources
As mentioned earlier, the demo application manages podcasts, which represent the resources in our web API. Resources are the central concept in REST and are characterized by two main things:
- each is referenced with a global identifier (e.g. a URI in HTTP).
- has one or more representations, that they expose to the outer world and can be manipulated with (we’ll be working mostly with JSON representations in this example)
The podcast resources are represented in our application by the Podcast class:
packagecodingpediaentities importSerializable import importjavaxannotationXmlRootElement * Podcast entity * @author ama @XmlRootElement publicclassPodcastimplementsSerializable privatestaticfinalserialVersionUID8039686696076337053L /** id of the podcas */ private /** title of the podcast */ privateStringtitle /** link of the podcast on Podcastpedia.org */ privateStringlinkOnPodcastpedia /** url of the feed */ privateString /** description of the podcast */ privateStringdescription /** when an episode was last published on the feed*/ privateinsertionDate publicPodcast publicPodcastStringtitleStringlinkOnPodcastpediaString Stringdescription titletitle linkOnPodcastpedialinkOnPodcastpedia descriptiondescription publicStringgetTitle returntitle publicsetTitleStringtitle titletitle publicStringgetLinkOnPodcastpedia returnlinkOnPodcastpedia publicsetLinkOnPodcastpediaStringlinkOnPodcastpedia linkOnPodcastpedialinkOnPodcastpedia publicStringgetDescription returndescription publicsetDescriptionStringdescription descriptiondescription publicgetId return publicsetId publicStringgetFeed return publicsetFeedString publicgetInsertionDate returninsertionDate publicsetInsertionDateinsertionDate insertionDateinsertionDate |
The strucuture is pretty simple – there are an id
, which identifies a podcast, and several other fields that we’ll can see in the JSON representation:
"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"1388213547000 |
2.2.2. Methods
The API exposed by our example is described in the following table:
Resource | URI | Method |
CREATE |
||
Add a list podcasts | /podcasts/list | |
Add a new podcast | /podcasts/ | |
READ |
||
List of all podcasts | /podcasts/ | |
List a single podcast | /podcasts/{id} | |
UPDATE |
||
Updates a single podcasts or creates one if not existent | /podcasts/{id} | |
DELETE |
||
Delete all podcasts | /podcasts/ |
DELETE |
Delete a single podcast | /podcasts/{id} |
DELETE |
As already mentioned the PodcastRestService
class is the one handling all the rest requests:
packagecodingpediaservice Component "/podcasts" publicclassPodcastRestService privatestaticfinalString"http://localhost:8080/demo-rest-spring-jersey-tomcat-mybatis-0.0.1-SNAPSHOT" Autowired privatePodcastDao podcastDao |
Notice the @Path("/podcasts")
before the class definition. The @Path annotation’s value is a relative URI path. In the example above, the Java class will be hosted at the URI path /podcasts
. The PodcastDao
interface is used to communicate with the database.
Code alert: You can find the entire content of the class on GitHub – https://github.com/amacoder/demo-restWS-spring-jersey-tomcat-mybatis/blob/master/src/main/java/org/codingpedia/demo/rest/service/PodcastRestService.java. We’ll be going through the file step by step and explain the different methods corresponding to the different operations.
2.2.2.1. CREATE
For the creation of new resources(“podcasts”) I use the POST (HTTP) method.
Note: In JAX-RS (Jersey) you specifies the HTTP methods (GET, POST, PUT, DELETE) by placing the corresponding annotation in front of the method.
2.2.2.1.1. Create a single resource (“podcast”) from JSON input
* 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 @POST @ConsumesMediaTypeAPPLICATION_JSON @ProducesMediaTypeTEXT_HTML @Transactional publicResponse createPodcastPodcast podcast podcastDaocreatePodcastpodcast returnResponsestatusentitybuildNewPodcastResourceURLbuild |
Annotations
@POST
– indicates that the method responds to HTTP POST requests@Consumes({MediaType.APPLICATION_JSON})
– defines the media type, the method accepts, in this case"application/json"
@Produces({MediaType.TEXT_HTML})
– defines the media type) that the method can produce, in this case"text/html"
. The response will be a html document, with a status of 201, indicating to the caller that the request has been fulfilled and resulted in a new resource being created.@Transactional
– Spring annotation, specifies that the method execution, should take place inside a transaction
2.2.2.1.2. Create multiple resources (“podcasts”) from JSON input
* A list of resources (here podcasts) provided in json format will be added * to the database. * @param podcasts * @return @POST@Path"list" @ConsumesMediaTypeAPPLICATION_JSON @Transactional publicResponse createPodcasts<Podcast>podcasts Podcast podcastpodcasts podcastDaocreatePodcastpodcast returnResponsestatusbuild |
Annotations
@POST
– indicates that the method responds to HTTP POST requests@Path("/list")
– identifies the URI path that the class method will serve requests for. Paths are relative. The combined path here will be"/podcasts/list"
, because as we have seen we have@Path
annotation at the class level@Consumes({MediaType.APPLICATION_JSON})
– defines the media type, the method accepts, in this case"application/json"
@Transactional
– Spring annotation, specifies that the method execution, should take place inside a transaction
In this case the method returns a status of 204 (“No Content”), suggesting that the server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
2.2.2.1.3. Create a single resource (“podcast”) from form
* Adds a new resource (podcast) from "form" (at least title and feed elements are required * at the DB level) * @param title * @param linkOnPodcastpedia * @param feed * @param description * @return @POST @ConsumesMediaTypeAPPLICATION_FORM_URLENCODED @ProducesMediaTypeTEXT_HTML @Transactional publicResponse createPodcastFromForm @FormParam"title"Stringtitle @FormParam"linkOnPodcastpedia"StringlinkOnPodcastpedia @FormParam"feed"String @FormParam"description"Stringdescription Podcast podcastPodcasttitlelinkOnPodcastpediadescription podcastDaocreatePodcastpodcast returnResponsestatusentitybuildNewPodcastResourceURLbuild |
Annotations
@POST
– indicates that the method responds to HTTP POST requests@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
-
– defines the media type, the method accepts, in this case
"application/x-www-form-urlencoded"
- @FormParam – present before the input parameters of the method, this
annotation binds the value(s) of a form parameter contained within a
request entity body to a resource method parameter. Values are URL
decoded unless this is disabled using the
Encoded
annotation
- @FormParam – present before the input parameters of the method, this
annotation binds the value(s) of a form parameter contained within a
request entity body to a resource method parameter. Values are URL
decoded unless this is disabled using the
@Produces({MediaType.TEXT_HTML})
- defines the media type) that the method can produce, in this case "text/html". The response will be a html document, with a status of 201, indicating to the caller that the request has been fulfilled and resulted in a new resource being created.@Transactional
– Spring annotation, specifies that the method execution, should take place inside a transaction
2.2.2.2. READ
2.2.2.2.1. Read all resources
* Returns all resources (podcasts) from the database * @return @ProducesMediaTypeAPPLICATION_JSONMediaTypeAPPLICATION_XML public<Podcast>getPodcasts returnpodcastDaogetPodcasts |
Annotations
@GET
– indicates that the method responds to HTTP GET requests@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
– defines the media type) that the method can produce, in this case"application/json"
or"application/xml"
(you need the@XmlRootElement
in front of thePodcast
class to produce xml formatted response). The response will be a list of podcasts either in JSON or XML format.
2.2.2.2.2. Read one resource
"{id}" ProducesMediaTypeAPPLICATION_JSONMediaTypeAPPLICATION_XML publicResponse findByIdPathParam Podcast podcastByIdpodcastDaogetPodcastById podcastById returnResponsestatusentitypodcastByIdbuild returnResponsestatusentity"The podcast with the id "" does not exist"build |
Annotations
@GET
– indicates that the method responds to HTTP GET requests@Path("{id}")
– identifies the URI path that the class method will serve requests for. The “id” value is an embedded variable making an URI path template. It is used in combination with the@PathParam
variable.@PathParam("id")
– binds the value of a URI template parameter (“id”) to the resource method parameter. The value is URL decoded unless this is di sabled using the@Encoded
annotation. A default value can be specified using the@DefaultValue
annotation.
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
– defines the media type) that the method can produce, in this case"application/json"
or"application/xml"
(you need the@XmlRootElement
in front of the Podcast class to produce the response in xml format). The response will be a podcast either in JSON or XML format with the “200 OK” status, or a message saying the podcast does not exit with a “404 Not Found” status.
2.2.2.3. UPDATE
* Updates the attributes of the podcast received via JSON for the given @param id * If the podcast does not exist yet in the database (verified by <strong>id</strong>) then * the application will try to create a new podcast resource in the db * @param id * @param podcast * @return @Path"{id}" @ConsumesMediaTypeAPPLICATION_JSON @ProducesMediaTypeTEXT_HTML @Transactional publicResponse updatePodcastById@PathParamPodcast podcast podcastgetIdpodcastsetId Stringmessage status podcastWasUpdatedpodcast status message"Podcast has been updated" podcastCanBeCreatedpodcast podcastDaocreatePodcastpodcast status//Created message"The podcast you provided has been added to the database" status//Not acceptable message"The information you provided is not sufficient to perform either an UPDATE or " " an INSERTION of the new podcast resource <br/>" " If you want to UPDATE please make sure you provide an existent <strong>id</strong> <br/>" "
If you want to insert a new podcast please provide at least a
<strong>title</strong> and the
<strong>feed</strong> for the podcast resource" returnResponsestatusstatusentitymessagebuild |
Annotations
@PUT
– indicates that the method responds to HTTP PUT requests@Path("{id}")
– identifies the URI path that the class method will serve requests for. The “id” value is an embedded variable making an URI path template. It is used in combination with the@PathParam
variable.@PathParam("id")
– binds the value of a URI template parameter (“id”) to the resource method parameter. The value is URL decoded unless this is di sabled using the@Encoded
annotation. A default value can be specified using the@DefaultValue
annotation.
@Consumes({MediaType.APPLICATION_JSON})
– defines the media type, the method accepts, in this case"application/json"
@Produces({MediaType.TEXT_HTML})
– defines the media type) that the method can produce, in this case “text/html”. The response will be a html document containing different messages and stati depending on what action has been taken- 200 – OK, “podcast updated successfully “
- 201 – id given was not found in the db, so a new podcast resource has been created
- 406 – if id was not found and you haven’t provided enough information for the creation of a new resource, the request is “Not Acceptable”
2.2.2.4. DELETE
2.2.2.4.1. Delete all resources
@DELETE @ProducesMediaTypeTEXT_HTML publicResponse deletePodcasts podcastDaodeletePodcasts returnResponsestatusentity"All podcasts have been successfully removed"build |
Annotations
@DELETE
– indicates that the method responds to HTTP DELETE requests@Produces({MediaType.TEXT_HTML})
– defines the media type that the method can produce, in this case “text/html”. The response will be a html document, with a status of 200, indicating to the caller that the request has been fulfilled.@Transactional
– Spring annotation, specifies that the method execution, should take place inside a transaction
2.2.2.4.2. Delete one resource
@DELETE@Path"{id}" @ProducesMediaTypeTEXT_HTML @Transactional publicResponse deletePodcastById@PathParam podcastDaodeletePodcastById returnResponsestatusbuild returnResponsestatusentity"Podcast with the id "" is not present in the database"build |
Annotations
@DELETE
– indicates that the method responds to HTTP DELETE requests@Path("{id}")
– identifies the URI path that the class method will serve requests for. The “id” value is an embedded variable making an URI path template. It is used in combination with the@PathParam
variable.@PathParam("id")
– binds the value of a URI template parameter (“id”) to the resource method parameter. The value is URL decoded unless this is di sabled using the@Encoded
annotation. A default value can be specified using the@DefaultValue
annotation.
@Produces({MediaType.TEXT_HTML})
– defines the media type that the method can produce, in this case “text/html”. If the podcast is deleted, that is found in the database, a 204 “No Content” success status is returnred, otherwise an html document with the status of 404 “Not found” is returned@Transactional
– Spring annotation, specifies that the method execution, should take place inside a transaction
3. Testing
3.1. Integration tests
To test the application I will use the Jersey Client
and execute requests against a running Jetty server with the application deployed on it. For that I will use the Maven Failsafe Plugin.
3.1.1. Configuration
3.1.1.1 Jersey client dependency
To build a Jersey client the jersey-client
jar is required in the classpath. With Maven you can add it as a dependency to the pom.xml
file:
dependency groupIdglassfishjerseygroupId artifactIdjerseyclientartifactId version2.4.1version scopescope dependency |
3.1.1.2. Failsafe plugin
The Failsafe Plugin is used during the integration-test and verify
phases of the build lifecycle to execute the integration tests of the
application. The Failsafe Plugin will not fail the build during the
integration-test phase thus enabling the post-integration-test phase to
execute.
To use the Failsafe Plugin, you need to add the following configuration to your pom.xml
plugins plugin groupIdapachemavenpluginsgroupId artifactIdmavenfailsafepluginartifactId versionversion executions execution integration goals integration goals execution execution verify goals verify goals execution executions plugin plugins |
3.1.1.2. Jetty Maven Plugin
As mentioned, the integration tests will be executed against a
running jetty server, that will be started only for the execution of the
tests. For that the following execution has to be configured in the jetty-maven-plugin
configuration:
plugins plugin groupIdeclipsejettygroupId artifactIdjettymavenpluginartifactId versionjettyversionversion configuration jettyConfigprojectbasedirresourcesconfigjetty9jettyConfig stopKeystopKey stopPortstopPort stopWaitstopWait scanIntervalSecondsscanIntervalSeconds configuration executions execution startjetty phaseintegrationphase goals previous instance exploded goals configuration scanIntervalSecondsscanIntervalSeconds daemondaemon configuration execution execution jetty phaseintegrationphase goals goals execution executions plugin plugins |
Note: In the pre-integration-test
phase the Jetty server will be started, after stopping any running instance to free up the port, and in the post-integration-phase
it will be stopped. The scanIntervalSeconds
has to be set to 0, and daemon
to true.
Code alert: See the complete pom.xml file on GitHub – https://github.com/amacoder/demo-restWS-spring-jersey-tomcat-mybatis/blob/master/pom.xml
3.1.2. Build the integration tests
I am using JUnit as the testing framework. By default, the Failsafe Plugin will automatically include all test classes with the following wildcard patterns:
"**/IT*.java"
– includes all of its subdirectories and all java filenames that start with “IT”."**/*IT.java"
– includes all of its subdirectories and all java filenames that end with “IT”."**/*ITCase.java"
– includes all of its subdirectories and all java filenames that end with “ITCase”.
I have created a single test class – RestDemoServiceIT
– that will test the read (GET) methods, but the procedure should be the same for all the other:
publicclassRestDemoServiceIT @Test publictestGetPodcastthrowsJsonGenerationException JsonMappingExceptionIOException ClientConfig clientConfigClientConfig clientConfigregisterJacksonFeatureclass Client clientClientBuildernewClientclientConfig WebTarget webTargetclient target"http://localhost:8888/demo-rest-spring-jersey-tomcat-mybatis-0.0.1-SNAPSHOT/podcasts/2" Builder requestwebTargetrequestMediaTypeAPPLICATION_JSON Response responserequest AssertassertTrueresponsegetStatus Podcast podcastresponsereadEntityPodcastclass ObjectMapper mapperObjectMapper System print"Received podcast from database *************************** " mapperwriterWithDefaultPrettyPrinter writeValueAsStringpodcast |
Note:
- I had to register the JacksonFeature for the client too so that I can marshall the podcast response in JSON format – response.readEntity(Podcast.class)
- I am testing against a running Jetty on port 8888 – I will show you in the next section how to start Jetty on a desired port
- I am expecting a 200 status for my request
- With the help
org.codehaus.jackson.map.ObjectMapper
I am displaying the JSON response nicely formatted
3.1.3. Running the integration tests
The Failsafe Plugin can be invoked by calling the verify
phase of the build lifecycle.
verify |
To start jetty on port 8888 you need to set the jetty.port
property to 8888. In Eclipse I use the following configuration:
3.2. Live tests
In the following video I will will show how to test the API application from Chrome with the help of DEV HTTP Client, which I highly recommend:
4. Summary
Well, that’s it. You’ve learned how to create a REST API with the help of Jersey 2, how it integrates with Spring with the new jersey-spring3 dependency and how to test the API with the Jersey Client and from Chrome with the help of Dev HTTP Client.
If you’ve found some usefulnes in this post, I’d be very grateful if you helped it spread by leaving a comment or sharing it on Twitter, Google+ or Facebook. Thank you! Don’t forget also to check out Podcastpedia.org – you’ll find for sure interesting podcasts and episodes. We are grateful for your support.
5. Resources
5.1. Source Code
5.2. Web resources