RESTful Web Services
REST was presented in 2000 by Roy Fielding in his doctoral dissertation, one of the chief authors of the HTTP Specification version 1.0 and 1.1.
The most important concept in REST is resources, which are identified by using a global ID (usually a URI). The client application uses the HTTP method (Get/post/put/delete) to manipulate the resource or resource set. RESTful Web services are Web services that are implemented using HTTP and REST principles. In general, RESTful Web services should define the following: The base/root URI of the Web service, such as Http://hostname/{appcontext}/resources. Supports MIME-type response data, including Json/xml/atom, and so on. A collection of operations supported by the service (for example, POST, GET, PUT, or DELETE).
Table 1. HTTP Method Operation Mapping Table
Method |
Perform Actions |
Example: http://hostname/{appcontext}/resources/1234 |
GET |
View Resources |
View Resources with ID 1234 |
POST |
Create a resource |
Create a sub-resource below |
PUT |
Create or update a resource |
Create or update a resource with ID 1234 |
DELETE |
Delete a resource |
Delete a resource with ID 1234 |
Jersey
Jersey is Sun's production quality reference implementation for JSR 311:jax-rs:the Java APIs for RESTful Web Services. Jersey implements support for the annotations defined in JSR-311, making it easy for developers to build RESTful Web Servi Ces with Java and the Java JVM. Jersey also adds additional features not specified by the JSR. Development Environment JDK 1.7 Jersey 2.6 Spring 4.2.7.RELEASE Maven 3.3.9 Apache Tomcat 7.0.70 configuration 1, Project structure
2, Pom.xml
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jers
Ey.version>2.6</jersey.version> <jersey-spring.version>2.23.1</jersey-spring.version> <spring.version>4.2.7.RELEASE</spring.version> <servlet-api-version>3.1.0</ Servlet-api-version> <logback.version>1.1.1</logback.version> <jcloverslf4j.version>1
.7.6</jcloverslf4j.version> </properties> <dependencies> <dependency>
<groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-spring3</artifactId> <version>${jersey-spring.version}</version> <exclusions> <exc Lusion> <groupId>org.springframework</groupId> <ARTIFACTID>SP
Ring-core</artifactid> </exclusion> <exclusion> <groupid>org.springframework</groupi
D> <artifactId>spring-web</artifactId> </exclusion> <exclusion> <groupId>org.springframework</groupId> <artifa ctid>spring-beans</artifactid> </exclusion> </exclusions> </de
Pendency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>${jersey-spring.version}< ;/version> </dependency> <dependency> <groupid>org.glassfish.jersey.conta Iners</groupid> <artifactId>jersey-container-servlet-core</artifactId> <versi On>${jersey-spring.version}</version> </dependency> <dependency> <groupid>org.glassfish.je Rsey.media</groupid> <artifactId>jersey-media-json-jackson</artifactId> <vers ion>${jersey.version}</version> </dependency> <dependency> <groupid>
;org.glassfish.jersey.media</groupid> <artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version> </dependency> <dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactid>jersey-entity-filtering</artifact Id> <version>${jersey.version}</version> </dependency> <!--Spring4.2
Dependencies-<dependency> <groupId>org.springframework</groupId> <artifactid>sprinG-core</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring-c
Ontext</artifactid> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring-w eb</artifactid> <version>${spring.version}</version> </dependency> &L T;dependency> <groupId>org.springframework</groupId> <artifactid>spring-jdbc& lt;/artifactid> <version>${spring.version}</version> </dependency> <d Ependency> <groupId>org.springframework</groupId> <artifactid>spring-tx</a
Rtifactid> <version>${spring.version}</version> </dependency> <dependency> < Groupid>org.springframework</groupid> <artifactId>spring-test</artifactId> &L
T;version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactid>javax.serv Let-api</artifactid> <version>${servlet-api-version}</version> <scope>prov
Ided</scope> </dependency> <!--logback Dependencies---<dependency>
<groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId>
<version>${logback.version}</version> </dependency> <dependency> <groupid>org.Slf4j</groupid> <artifactId>jcl-over-slf4j</artifactId> <version>${jclover slf4j.version}</version> </dependency> <dependency> <groupid>junit<
;/groupid> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
3, Web. XML
<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "http://java.sun.com/dtd/w
Eb-app_2_3.dtd "> <web-app> <display-name>archetype Created Web application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <PARAM-VALUE>CLASSP ath:applicationcontext.xml</param-value> </context-param> <listener> <listener-class > Org.springframework.web.context.ContextLoaderListener </listener-class> </LISTENER&G
T
<servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class> Org.glassfish.jersey.servlet.ServletContainer </servlet-class> <init-param> <pa Ram-name>javax.ws.rs.application</param-name> <PARAM-VALUE>COM.RICKY.CODELAB.JERSEY.RESTJAXRSAP Plication</param-value> </init-param> <load-on-startup>1</load-on-startup> </SERVLET&G
T <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/*</
Url-pattern> </servlet-mapping> </web-app>
3.1, Applicationcontext.xml
<?xml version= "1.0" encoding= "UTF-8"?> <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.xsd/
http Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd " >
<context:component-scan base-package= "Com.ricky.codelab.jersey" ></context:component-scan>
</beans>
3.2. Jersey servlet configuration
Package Com.ricky.codelab.jersey;
Import Com.ricky.codelab.jersey.resource.UserResource;
Import Org.glassfish.jersey.jackson.JacksonFeature;
Import Org.glassfish.jersey.server.ResourceConfig;
Import Org.glassfish.jersey.server.spring.scope.RequestContextFilter; /** * ${description} * * @author Ricky Fung * @create 2016-07-20 14:15 * public class Restjaxrsapplication extends R
esourceconfig {/** * Register jax-rs application components. */Public Restjaxrsapplication () {//Register application Resources This.register (Userresource.class
);
Register Filters Register (requestcontextfilter.class);
Register (Loggingresponsefilter.class);
Register (Corsresponsefilter.class);
Register Exception mappers//register (Genericexceptionmapper.class);
Register (Appexceptionmapper.class);
Register (Notfoundexceptionmapper.class); Register Features Register (JACKSONFEAture.class);
Register (Multipartfeature.class);
}
}
REST API Design Implementation
Resources
Package Com.ricky.codelab.jersey.resource;
Import Com.ricky.codelab.jersey.domain.User;
Import Com.ricky.codelab.jersey.service.IUserService;
Import org.springframework.beans.factory.annotation.Autowired;
Import javax.ws.rs.*;
Import Javax.ws.rs.core.MediaType;
Import Javax.ws.rs.core.Response;
Import java.util.List;
/** * ${description} * * @author Ricky Fung * @create 2016-07-20 14:28 */@Path ("/user") public class Userresource {
@Autowired private Iuserservice UserService; @POST @Consumes ({Mediatype.application_json}) @Produces ({mediatype.text_html}) public Response CreateUser (
User user) {Long id = userservice.insert (user);
Return Response.Status (Response.Status.CREATED)//201. Entity ("A new user has been CREATED") . Header ("Location", "http://localhost:8888/user/" + String.valu
EOf (ID)). build (); } @POST @Consumes ({mediatype.application_form_urlencoded}) @Produces ({mediatype.text_html}) public Response createuserapplicationformurlencoded (
@FormParam ("name") String name, @FormParam ("age") Integer-age) {User user = new User ();
User.setname (name);
User.setage (age);
Long id = userservice.insert (user); return Response status (Response.Status.CREATED)//201. Entity ("A new User/resource have be En created at/user/"+ ID". Header ("Location", "Http://lo
calhost:8888/user/"+ string.valueof (ID)). build (); }//HTTP://LOCALHOST:8080/USER/1 @GET @Path ("/{id}") @Produces (Mediatype.application_json) public use
R Getuserbyid (@PathParam ("id") Long ID) {return Userservice.finduserbyid (ID); } @GET @Path ("/list") @Produces (mediatype.application_json) public list<user> geTuserlist () {return userservice.getuserlist (); } @GET @Produces (mediatype.application_json) public User getuserbyname (@QueryParam ("username") String Usernam
e) {return userservice.finduserbyname (username); @Consumes ({Mediatype.application_json}) @Produces ({mediatype.text_html}) pub @PUT @Path ("{ID}")
Lic Response Putuserbyid (@PathParam ("id") Long ID, user user) {User Userbyid = Userservice.finduserbyid (ID);
if (Userbyid = = null) {//resource not existent yet, and should be created under the specified URI
Long userId = Userservice.insert (user); Return Response