欢迎来到Java中的Restful Web Services Tutorial。 REST是代表性国家转移的缩写。REST是开发可通过网络访问的应用程序的 **架构风格。
多余的网站服务
REST 客户端应用程序可以使用 HTTP GET/POST 方法来调用 Restful Web 服务 REST 不会指定任何特定的协议来使用,但在几乎所有情况下,它被用于 HTTP/HTTPS 上。
Java RESTful Web 服务 API
Java API for RESTful Web Services (JAX-RS) 是用于创建 REST Web 服务的 Java API. JAX-RS 使用注释来简化 Web 服务的开发和部署。
安静的网站服务注释
JAX-RS的一些重要注释是:
@Path
:用来指定类和方法的相对路径. 我们可以通过扫描 Path 注释值来获取 Web 服务的 URI@GET
,@PUT
,@POST
,@DELETE
和@HEAD
:用来指定方法的 HTTP 请求类型@Produces
,@Consumes
:用来指定请求和响应类型@PathParam
:用来通过分析将方法参数与路径值结合。
安静的 Web 服务和 SOAP
SOAP 是协议,而 REST 是架构风格 2. SOAP 服务器和客户端应用程序紧密相连,并与 WSDL 合约相结合,而 REST 网页服务和客户端没有合同 3. 学习曲线与 SOAP 网页服务相比,REST 很容易学习 4. REST 网页服务请求和响应类型可以是 XML、JSON、文本等,而 SOAP 只使用 XML 5. JAX-RS 是 REST 网页服务的 Java API,而 JAX-WS 是 SOAP 网页服务的 Java API
REST API 应用程序
JAX-RS API 有两种主要的实现。
- Jersey: Jersey是由太阳提供的参考实现。为了使用Jersey作为我们的JAX-RS实现,我们只需要在web.xml中配置它的服务器并添加所需的依赖性。 请注意,JAX-RS API是JDK的一部分,而不是Jersey,所以我们必须在我们的应用程序中添加它的依赖性
- RESTEasy: RESTEasy是提供JAX-RS实现的JBoss项目
Java Restful Web Services 应用程序
让我们看看使用 Jersey 然后 RESTEasy 创建 Restful Web 服务是多么容易,我们将通过 HTTP 揭示以下方法,并使用 Chrome Postman 扩展来测试这些方法。
──」
URI | HTTP Method | Description |
---|---|---|
/person/{id}/getDummy | GET | Returns a dummy person object |
/person/add | POST | Adds a person |
/person/{id}/delete | GET | Delete the person with 'id' in the URI |
/person/getAll | GET | Get all persons |
/person/{id}/get | GET | Get the person with 'id' in the URI |
Jersey Restful 网站服务
Create a dynamic web project and then convert it to Maven to get the skeleton of your web services project. Below image shows the project structure of the final project. Let's look at the Jersey dependencies we have in pom.xml file.
1<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
2 <modelVersion>4.0.0</modelVersion>
3 <groupId>JAXRS-Example</groupId>
4 <artifactId>JAXRS-Example</artifactId>
5 <version>0.0.1-SNAPSHOT</version>
6 <packaging>war</packaging>
7
8 <dependencies>
9 <dependency>
10 <groupId>com.sun.jersey</groupId>
11 <artifactId>jersey-server</artifactId>
12 <version>1.19</version>
13 </dependency>
14 <dependency>
15 <groupId>com.sun.jersey</groupId>
16 <artifactId>jersey-servlet</artifactId>
17 <version>1.19</version>
18 </dependency>
19 <dependency>
20 <groupId>com.sun.jersey</groupId>
21 <artifactId>jersey-client</artifactId>
22 <version>1.19</version>
23 </dependency>
24 </dependencies>
25
26 <build>
27 <sourceDirectory>src</sourceDirectory>
28 <plugins>
29 <plugin>
30 <artifactId>maven-war-plugin</artifactId>
31 <version>2.6</version>
32 <configuration>
33 <warSourceDirectory>WebContent</warSourceDirectory>
34 <failOnMissingWebXml>false</failOnMissingWebXml>
35 </configuration>
36 </plugin>
37 <plugin>
38 <artifactId>maven-compiler-plugin</artifactId>
39 <version>3.3</version>
40 <configuration>
41 <source>1.7</source>
42 <target>1.7</target>
43 </configuration>
44 </plugin>
45 </plugins>
46 </build>
47</project>
我们不需要添加 jersey-client 依赖性,但如果您正在编写 Java 程序以使用 Jersey 召唤 REST 网页服务,那么它是必需的。
1<?xml version="1.0" encoding="UTF-8"?>
2<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
3 <display-name>JAXRS-Example</display-name>
4
5<!-- Jersey Servlet configurations -->
6 <servlet>
7 <servlet-name>Jersey REST Service</servlet-name>
8 <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
9 <init-param>
10 <param-name>com.sun.jersey.config.property.packages</param-name>
11 <param-value>com.journaldev</param-value>
12 </init-param>
13 <load-on-startup>1</load-on-startup>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>Jersey REST Service</servlet-name>
17 <url-pattern>/*</url-pattern>
18 </servlet-mapping>
19 <!-- Jersey Servlet configurations -->
20
21</web-app>
所有这些都需要插入 Jersey 到我们的 Web 应用程序中,在我们的 java 代码中,我们将使用 JAX-RS 注释。 注意 init 参数 com.sun.jersey.config.property.packages
的值,以提供将被扫描到 Web 服务资源和方法的包。
模型类别 模型类别
首先,我们将创建两个模型豆 - 我们的应用数据的人
和响应
发送回复到客户端系统. 因为我们将发送XML响应,豆应该被注释为@XmlRootElement
,因此我们有这个类。
1package com.journaldev.jaxrs.model;
2
3import javax.xml.bind.annotation.XmlRootElement;
4
5@XmlRootElement (name="person")
6public class Person {
7 private String name;
8 private int age;
9 private int id;
10
11 public String getName() {
12 return name;
13 }
14
15 public void setName(String name) {
16 this.name = name;
17 }
18
19 public int getAge() {
20 return age;
21 }
22
23 public void setAge(int age) {
24 this.age = age;
25 }
26
27 public int getId() {
28 return id;
29 }
30
31 public void setId(int id) {
32 this.id = id;
33 }
34
35 @Override
36 public String toString(){
37 return id+"::"+name+"::"+age;
38 }
39
40}
1package com.journaldev.jaxrs.model;
2
3import javax.xml.bind.annotation.XmlRootElement;
4
5@XmlRootElement
6public class Response {
7
8 private boolean status;
9 private String message;
10
11 public boolean isStatus() {
12 return status;
13 }
14
15 public void setStatus(boolean status) {
16 this.status = status;
17 }
18
19 public String getMessage() {
20 return message;
21 }
22
23 public void setMessage(String message) {
24 this.message = message;
25 }
26}
REST Web Services 辅导服务
根据我们的 URI 结构,以下是服务界面和实施代码。
1package com.journaldev.jaxrs.service;
2
3import com.journaldev.jaxrs.model.Person;
4import com.journaldev.jaxrs.model.Response;
5
6public interface PersonService {
7
8 public Response addPerson(Person p);
9
10 public Response deletePerson(int id);
11
12 public Person getPerson(int id);
13
14 public Person[] getAllPersons();
15
16}
1package com.journaldev.jaxrs.service;
2
3import java.util.HashMap;
4import java.util.Map;
5import java.util.Set;
6
7import javax.ws.rs.Consumes;
8import javax.ws.rs.GET;
9import javax.ws.rs.POST;
10import javax.ws.rs.Path;
11import javax.ws.rs.PathParam;
12import javax.ws.rs.Produces;
13import javax.ws.rs.core.MediaType;
14
15import com.journaldev.jaxrs.model.Person;
16import com.journaldev.jaxrs.model.Response;
17
18@Path("/person")
19@Consumes(MediaType.APPLICATION_XML)
20@Produces(MediaType.APPLICATION_XML)
21public class PersonServiceImpl implements PersonService {
22
23 private static Map<Integer,Person> persons = new HashMap<Integer,Person>();
24
25 @Override
26 @POST
27 @Path("/add")
28 public Response addPerson(Person p) {
29 Response response = new Response();
30 if(persons.get(p.getId()) != null){
31 response.setStatus(false);
32 response.setMessage("Person Already Exists");
33 return response;
34 }
35 persons.put(p.getId(), p);
36 response.setStatus(true);
37 response.setMessage("Person created successfully");
38 return response;
39 }
40
41 @Override
42 @GET
43 @Path("/{id}/delete")
44 public Response deletePerson(@PathParam("id") int id) {
45 Response response = new Response();
46 if(persons.get(id) == null){
47 response.setStatus(false);
48 response.setMessage("Person Doesn't Exists");
49 return response;
50 }
51 persons.remove(id);
52 response.setStatus(true);
53 response.setMessage("Person deleted successfully");
54 return response;
55 }
56
57 @Override
58 @GET
59 @Path("/{id}/get")
60 public Person getPerson(@PathParam("id") int id) {
61 return persons.get(id);
62 }
63
64 @GET
65 @Path("/{id}/getDummy")
66 public Person getDummyPerson(@PathParam("id") int id) {
67 Person p = new Person();
68 p.setAge(99);
69 p.setName("Dummy");
70 p.setId(id);
71 return p;
72 }
73
74 @Override
75 @GET
76 @Path("/getAll")
77 public Person[] getAllPersons() {
78 Set<Integer> ids = persons.keySet();
79 Person[] p = new Person[ids.size()];
80 int i=0;
81 for(Integer id : ids){
82 p[i] = persons.get(id);
83 i++;
84 }
85 return p;
86 }
87
88}
大多数代码都是自我解释的,花一些时间来熟悉JAX-RS的注释@Path
,@PathParam
,@POST
,@GET
,@Consumes
和@Produces
。
Restful Web 服务测试
That's it. Our web service is ready, just export it as WAR file and put it inside Tomcat webapps directory or deploy into any other container of your choice. Below are some of the tests performed using Postman chrome extension for this web service. Note that we have to provide Accept and Content-Type values as "application/xml" in request header as shown in below image.
所有这些都是用 Jersey JAX-RS 实现来创建 Web 服务,正如你所看到的那样,大多数代码都使用 JAX-RS 注释,并且 Jersey 通过部署描述器和依赖程序插入。
RESTEasy RESTful Web 服务示例
We will use all the business logic developed in Jersey project, but rather than making changes to the same project, I have created a new project. Create a dynamic web project and convert it to Maven project. Then copy all the java classes - Person, Response, PersonService and PersonServiceImpl. Below is the final project after we are done with all the changes. Add below RESTEasy dependencies in pom.xml file.
1<dependency>
2 <groupId>org.jboss.resteasy</groupId>
3 <artifactId>resteasy-jaxrs</artifactId>
4 <version>3.0.13.Final</version>
5</dependency>
6<dependency>
7 <groupId>org.jboss.resteasy</groupId>
8 <artifactId>resteasy-jaxb-provider</artifactId>
9 <version>3.0.13.Final</version>
10</dependency>
下面是 web.xml 文件,我们正在配置 Resteasy servlet。
1<?xml version="1.0" encoding="UTF-8"?>
2<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
3 <display-name>JAXRS-Example-RestEasy</display-name>
4
5 <listener>
6 <listener-class>
7 org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
8 </listener-class>
9 </listener>
10
11 <servlet>
12 <servlet-name>resteasy-servlet</servlet-name>
13 <servlet-class>
14 org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
15 </servlet-class>
16 <init-param>
17 <param-name>javax.ws.rs.Application</param-name>
18 <param-value>com.journaldev.jaxrs.resteasy.app.MyApp</param-value>
19 </init-param>
20 </servlet>
21
22 <servlet-mapping>
23 <servlet-name>resteasy-servlet</servlet-name>
24 <url-pattern>/*</url-pattern>
25 </servlet-mapping>
26
27</web-app>
请注意 init-param 提供MyApp
类为值,在这里我们将javax.ws.rs.core.Application
类扩展到下面。
1package com.journaldev.jaxrs.resteasy.app;
2
3import java.util.HashSet;
4import java.util.Set;
5
6import javax.ws.rs.core.Application;
7
8import com.journaldev.jaxrs.service.PersonServiceImpl;
9
10public class MyApp extends Application {
11
12 private Set<Object> singletons = new HashSet<Object>();
13
14 public MyApp() {
15 singletons.add(new PersonServiceImpl());
16 }
17
18 @Override
19 public Set<Object> getSingletons() {
20 return singletons;
21 }
22
23}
RESTEasy Web 服务测试
我们的网页服务已经完成了 RESTEasy JAX-RS 实现. 下面是 Postman chrome 扩展测试的一些结果。
这就是 Restful Web Services 教程的全部,我希望您了解了 JAX-RS 注释,并了解了具有标准 API 的好处,这有助于我们重新使用代码并从 Jersey 移动到 RESTEasy 如此轻松。