Java的Restful Web Services教程

Welcome to Restful Web Services Tutorial in Java. REST is the acronym for REpresentational State Transfer. REST is an architectural style for developing applications that can be accessed over the network. REST architectural style was brought in light by Roy Fielding in his doctoral thesis in 2000.

欢迎使用Java的Restful Web服务教程。 REST代表性状态转移的缩写。 REST是一种体系结构样式,用于开发可通过网络访问的应用程序。 REST建筑风格是由Roy Fielding在2000年的博士论文中提出的。

宁静的Web服务 (Restful Web Services)

Restful Web Services is a stateless client-server architecture where web services are resources and can be identified by their URIs.

Restful Web Services是一种无状态的客户端-服务器体系结构,其中Web服务是资源,可以通过其URI进行标识。

REST Client applications can use HTTP GET/POST methods to invoke Restful web services. REST doesn’t specify any specific protocol to use, but in almost all cases it’s used over HTTP/HTTPS. When compared to SOAP web services, these are lightweight and doesn’t follow any standard. We can use XML, JSON, text or any other type of data for request and response.

REST客户端应用程序可以使用HTTP GET / POST方法来调用Restful Web服务。 REST没有指定要使用的任何特定协议,但是在几乎所有情况下,它都是通过HTTP / HTTPS使用的。 与SOAP Web服务相比,它们是轻量级的,不遵循任何标准。 我们可以使用XML,JSON,文本或任何其他类型的数据进行请求和响应。

Java RESTful Web服务API (Java RESTful Web Services API)

Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web services. JAX-RS uses annotations to simplify the development and deployment of web services. JAX-RS is part of JDK, so you don’t need to include anything to use it’s annotations.

RESTful Web服务的Java API(JAX-RS)是用于创建REST Web服务的Java API。 JAX-RS使用注释来简化Web服务的开发和部署。 JAX-RS是JDK的一部分,因此您无需包括任何内容即可使用其注释。

宁静的Web服务注释 (Restful Web Services Annotations)

Some of the important JAX-RS annotations are:

一些重要的JAX-RS批注是:

  • @Path: used to specify the relative path of class and methods. We can get the URI of a webservice by scanning the Path annotation value.

    @Path :用于指定类和方法的相对路径。 我们可以通过扫描路径注释值来获取Web服务的URI。
  • @GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP request type for a method.

    @GET@PUT@POST@DELETE@HEAD :用于指定的方法的HTTP请求类型。
  • @Produces, @Consumes: used to specify the request and response types.

    @Produces@Consumes :用于指定请求和响应类型。
  • @PathParam: used to bind the method parameter to path value by parsing it.

    @PathParam :用于通过解析将方法参数绑定到路径值。

宁静的Web服务和SOAP (Restful Web Services and SOAP)

  1. SOAP is a protocol whereas REST is an architectural style.

    SOAP是一种协议,而REST是一种体系结构样式。
  2. SOAP server and client applications are tightly coupled and bind with the WSDL contract whereas there is no contract in REST web services and client.

    SOAP服务器和客户机应用程序紧密耦合并与WSDL契约绑定,而REST Web服务和客户机中没有契约。
  3. Learning curve is easy for REST when compared to SOAP web services.

    与SOAP Web服务相比,REST易于学习。
  4. REST web services request and response types can be XML, JSON, text etc. whereas SOAP works with XML only.

    REST Web服务的请求和响应类型可以是XML,JSON,文本等,而SOAP仅适用于XML。
  5. JAX-RS is the Java API for REST web services whereas JAX-WS is the Java API for SOAP web services.

    JAX-RS是REST Web服务的Java API,而JAX-WS是SOAP Web服务的Java API。

REST API实施 (REST API Implementations)

There are two major implementations of JAX-RS API.

JAX-RS API有两种主要实现。

  1. Jersey: Jersey is the reference implementation provided by Sun. For using Jersey as our JAX-RS implementation, all we need to configure its servlet in web.xml and add required dependencies. Note that JAX-RS API is part of JDK not Jersey, so we have to add its dependency jars in our application.

    球衣球衣是Sun提供的参考实现。 为了使用Jersey作为我们的JAX-RS实现,我们需要在web.xml中配置其servlet并添加所需的依赖项。 请注意,JAX-RS API是JDK而不是Jersey的一部分,因此我们必须在应用程序中添加其依赖项jar。
  2. RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation.

    RESTEasyRESTEasy是提供JAX-RS实现的JBoss项目。

Java Restful Web服务教程 (Java Restful Web Services Tutorial)

Let’s see how easy to create Restful web service using Jersey and then RESTEasy. We will be exposing following methods over HTTP and use Chrome Postman extension to test these.

让我们看看使用Jersey和RESTEasy创建Restful Web服务有多么容易。 我们将通过HTTP公开以下方法,并使用Chrome Postman扩展程序进行测试。

URIHTTP MethodDescription
/person/{id}/getDummyGETReturns a dummy person object
/person/addPOSTAdds a person
/person/{id}/deleteGETDelete the person with ‘id’ in the URI
/person/getAllGETGet all persons
/person/{id}/getGETGet the person with ‘id’ in the URI
URI HTTP方法 描述
/ person / {id} / getDummy 得到 返回一个虚拟人对象
/人/添加 开机自检 加一个人
/人/ {id} /删除 得到 删除URI中带有“ id”的人
/人/ getAll 得到 让所有人
/ person / {id} / get 得到 在URI中获取带有“ id”的人

泽西岛宁静的Web服务 (Jersey Restful Web Services)

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.

创建一个动态Web项目,然后将其转换为Maven,以获取Web服务项目的框架。 下图显示了最终项目的项目结构。

Let’s look at the Jersey dependencies we have in pom.xml file.

让我们看一下pom.xml文件中的Jersey依赖项。

<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">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JAXRS-Example</groupId>
  <artifactId>JAXRS-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.19</version>
        </dependency>
  </dependencies>
  
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

We are not required to add jersey-client dependencies but if you are writing java program to invoke a REST web service using Jersey then it’s required.

我们不需要添加jersey-client依赖关系,但是如果您正在编写Java程序以使用Jersey调用REST Web服务,则是必需的。

Now let’s look at the deployment descriptor to learn how to configure Jersey to create our web application.

现在,让我们看一下部署描述符,以了解如何配置Jersey以创建我们的Web应用程序。

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>JAXRS-Example</display-name>

<!-- Jersey Servlet configurations -->
    <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.journaldev</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
  <!-- Jersey Servlet configurations -->

</web-app>

That’s all is required to plugin Jersey into our web application, in our java code we will be using JAX-RS annotations. Notice the value of init parameter com.sun.jersey.config.property.packages to provide package that will be scanned for web service resources and methods.

这就是将Jersey插入到我们的Web应用程序中所需要的全部,在我们的Java代码中,我们将使用JAX-RS批注。 请注意init参数com.sun.jersey.config.property.packages的值,以提供要扫描的Web服务资源和方法的软件包。

REST示例模型类 (REST Example Model Classes)

First of all we will create two model beans – Person for our application data and Response for sending response to client systems. Since we will be sending XML response, the beans should be annotated with @XmlRootElement, hence we have this class.

首先,我们将创建两个模型bean –用于我们的应用程序数据的Person和用于将响应发送到客户端系统的Response 。 由于我们将发送XML响应,因此应使用@XmlRootElement注释@XmlRootElement ,因此我们拥有此类。

package com.journaldev.jaxrs.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement (name="person")
public class Person {
	private String name;
	private int age;
	private int id;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	
	@Override
	public String toString(){
		return id+"::"+name+"::"+age;
	}

}
package com.journaldev.jaxrs.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Response {

	private boolean status;
	private String message;

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

REST Web服务教程服务 (REST Web Services Tutorial Services)

Based on our URI structure, below is the service interface and it’s implementation code.

根据我们的URI结构,以下是服务接口及其实现代码。

package com.journaldev.jaxrs.service;

import com.journaldev.jaxrs.model.Person;
import com.journaldev.jaxrs.model.Response;

public interface PersonService {

	public Response addPerson(Person p);
	
	public Response deletePerson(int id);
	
	public Person getPerson(int id);
	
	public Person[] getAllPersons();

}
package com.journaldev.jaxrs.service;


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.journaldev.jaxrs.model.Person;
import com.journaldev.jaxrs.model.Response;

@Path("/person")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public class PersonServiceImpl implements PersonService {

	private static Map<Integer,Person> persons = new HashMap<Integer,Person>();
	
	@Override
	@POST
    @Path("/add")
	public Response addPerson(Person p) {
		Response response = new Response();
		if(persons.get(p.getId()) != null){
			response.setStatus(false);
			response.setMessage("Person Already Exists");
			return response;
		}
		persons.put(p.getId(), p);
		response.setStatus(true);
		response.setMessage("Person created successfully");
		return response;
	}

	@Override
	@GET
    @Path("/{id}/delete")
	public Response deletePerson(@PathParam("id") int id) {
		Response response = new Response();
		if(persons.get(id) == null){
			response.setStatus(false);
			response.setMessage("Person Doesn't Exists");
			return response;
		}
		persons.remove(id);
		response.setStatus(true);
		response.setMessage("Person deleted successfully");
		return response;
	}

	@Override
	@GET
	@Path("/{id}/get")
	public Person getPerson(@PathParam("id") int id) {
		return persons.get(id);
	}
	
	@GET
	@Path("/{id}/getDummy")
	public Person getDummyPerson(@PathParam("id") int id) {
		Person p = new Person();
		p.setAge(99);
		p.setName("Dummy");
		p.setId(id);
		return p;
	}

	@Override
	@GET
	@Path("/getAll")
	public Person[] getAllPersons() {
		Set<Integer> ids = persons.keySet();
		Person[] p = new Person[ids.size()];
		int i=0;
		for(Integer id : ids){
			p[i] = persons.get(id);
			i++;
		}
		return p;
	}

}

Most of the code is self explanatory, spend some time to familiarize yourself with JAX-RS annotations @Path, @PathParam, @POST, @GET, @Consumes and @Produces.

大部分的代码是自我解释,花一些时间来熟悉JAX-RS注释@Path@PathParam@POST@GET@Consumes@Produces

宁静的Web服务测试 (Restful Web Services Test)

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.

而已。 我们的Web服务已准备就绪,只需将其导出为WAR文件并将其放在Tomcat webapps目录中或部署到您选择的任何其他容器中即可。

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.

以下是针对此Web服务使用Postman chrome扩展程序执行的一些测试。 请注意,我们必须在请求标头中提供Accept和Content-Type值作为“ application / xml”,如下图所示。

  • getDummy
    Restful web services java

    getDummy
  • add
    Java Restful web services tutorial


  • get
    Rest Web Services tutorial

    得到
  • getAll
    Jersey rest web services

    得到所有
  • delete
    Jersey REST API

    删除

That’s all for creating web services using Jersey JAX-RS implementation. As you can see that most of the code is using JAX-RS annotations and Jersey is plugged in through deployment descriptor and dependencies.

这就是使用Jersey JAX-RS实现创建Web服务的全部。 如您所见,大多数代码使用的是JAX-RS批注,并且Jersey是通过部署描述符和依赖项插入的。

RESTEasy RESTful Web服务示例 (RESTEasy RESTful Web Services Example)

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.

我们将使用Jersey项目中开发的所有业务逻辑,但是我没有对同一项目进行更改,而是创建了一个新项目。 创建一个动态Web项目并将其转换为Maven项目。 然后复制所有Java类-Person,Response,PersonService和PersonServiceImpl。 完成所有更改后,下面是最终项目。

Add below RESTEasy dependencies in pom.xml file.

在pom.xml文件中添加以下RESTEasy依赖项。

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jaxrs</artifactId>
	<version>3.0.13.Final</version>
</dependency>
<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jaxb-provider</artifactId>
	<version>3.0.13.Final</version>
</dependency>

Below is the web.xml file where we are configuring Resteasy servlet.

下面是我们要配置Resteasy servlet的web.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>JAXRS-Example-RestEasy</display-name>
     
    <listener>
      <listener-class>
         org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
      </listener-class>
   	</listener>
   
    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.journaldev.jaxrs.resteasy.app.MyApp</param-value>
    </init-param>
    </servlet>
  
    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
	
</web-app>

Notice the init-param where are providing MyApp class as value, here we are extending javax.ws.rs.core.Application class as shown below.

注意init-param在哪里提供MyApp类作为值,在这里我们扩展了javax.ws.rs.core.Application类,如下所示。

package com.journaldev.jaxrs.resteasy.app;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

import com.journaldev.jaxrs.service.PersonServiceImpl;

public class MyApp extends Application {
	
	private Set<Object> singletons = new HashSet<Object>();

	public MyApp() {
		singletons.add(new PersonServiceImpl());
	}

	@Override
	public Set<Object> getSingletons() {
		return singletons;
	}

}

RESTEasy Web服务测试 (RESTEasy Web Services Test)

That’s it. Our web service is ready with RESTEasy JAX-RS implementation. Below are some of the output from Postman chrome extension test.

而已。 RESTEasy JAX-RS实现已准备好我们的Web服务。 以下是Postman chrome扩展测试的一些输出。

  • getDummy
    rest services in java, rest client java, java rest api, REST Tutorial

    getDummy
  • add
    Restful web services java, Java Restful web services


  • get
    Restful Web Services

    得到

That’s all for Restful Web Services Tutorial, I hope you learned about JAX-RS annotations and understood the benefits of having standard API that helped us in reusing code and moving from Jersey to RESTEasy so easy.

这就是Restful Web Services Tutorial的全部内容,我希望您了解了JAX-RS批注,并了解了使用标准API的好处,该标准API可以帮助我们重用代码并使从Jersey轻松迁移到RESTEasy。

翻译自: https://www.journaldev.com/9170/restful-web-services-tutorial-java

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值