泽西岛Java教程

Welcome to Java Jersey Tutorial. Recently I started working on a Restful web service project using the JAX-RS Jersey framework.

欢迎使用Java Jersey教程。 最近,我开始使用JAX-RS Jersey框架从事Restful Web服务项目。

什么是Java Jersey框架? (What is Java Jersey Framework?)

Java Jersey project tracks the JAX-RS API, which is used to create Restful web services in Java.

Java Jersey项目跟踪JAX-RS API,该API用于在Java中创建Restful Web服务。

1.谁应该使用本教程? (1. Who should use this tutorial?)

This tutorial is intended for Java programmers who are interested in developing and deploying Restful Web Services using JAX-RS API and JAXB.

本教程适用于对使用JAX-RS API和JAXB开发和部署Restful Web Services感兴趣的Java程序员。

2.先决条件 (2. Prerequisites)

The scope of this tutorial is to use Jersey API for creating Restful web services and invoking the web service using a Java client program and testing web service using the tool.

本教程的范围是使用Jersey API来创建Restful Web服务,并使用Java客户端程序调用Web服务,并使用该工具测试Web服务。

Basic understanding of Java, Web Services, XML, Maven, and any application server (JBoss/Tomcat) is required to understand the tutorial with ease.

要轻松理解本教程,需要对Java,Web服务,XML,Maven和任何应用程序服务器(JBoss / Tomcat)有基本的了解。

3.软件和工具 (3. Softwares and Tools)

  • JDK version 1.8.0_131

    JDK版本1.8.0_131
  • Apache Maven 3.5.3

    Apache Maven 3.5.3
  • Mac OS X 10.13.4

    Mac OS X 10.13.4
  • Tomcat 8.5.16

    Tomcat 8.5.16
  • Eclipse Java EE IDE Oxygen 4.7.3

    Eclipse Java EE IDE氧气4.7.3

创建Jersey Eclipse Maven项目 (Creating Jersey Eclipse Maven Project)

Create a “Dynamic Web Project” in Eclipse and then convert it to the maven project. This will provide us a maven based web application basic project.

在Eclipse中创建一个“动态Web项目”,然后将其转换为maven项目。 这将为我们提供一个基于Maven的Web应用程序基础项目。

I have given GroupId as com.journaldev.jersey and artifactID as my-jersey-project but you can specify anything you like. Once we complete the development of our project, the project structure will look like the below image.

我已将GroupId com.journaldev.jerseycom.journaldev.jersey并将artifactID com.journaldev.jerseymy-jersey-project但是您可以指定任何您喜欢的名称。 一旦完成项目的开发,项目结构将如下图所示。

Java Jersey Restful Web服务项目说明 (Java Jersey Restful Web Service Project Explanation)

1. pom.xml: Project configuration details, note the jersey dependencies provided, other details are common for any similar maven project.

1. pom.xml :项目配置详细信息,请注意提供的jersey依赖项,其他详细信息对于任何类似的maven项目都是通用的。

<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>com.journaldev.jersey</groupId>
	<artifactId>my-jersey-project</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.14</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-servlet</artifactId>
			<version>1.14</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-client</artifactId>
			<version>1.14</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>My-Jersey-Project</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.0.0</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

2. EmpRequest.java: Java Bean for the request object. The important thing to note here is the @XmlRootElement annotation to map the class to an XML element.

2. EmpRequest.java :请求对象的Java Bean。 这里要注意的重要事情是@XmlRootElement批注,用于将类映射到XML元素。

package com.journaldev.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "empRequest")
public class EmpRequest {
	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

3. EmpResponse.java: Java bean for the response object.

3. EmpResponse.java :响应对象的Java bean。

package com.journaldev.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "empResponse")
public class EmpResponse {
	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

}

4. ErrorResponse.java: Java Bean that will be sent as the response in case of an exception.

4. ErrorResponse.java :在发生异常的情况下将作为响应发送的Java Bean。

package com.journaldev.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "errorResponse")
public class ErrorResponse {

	private String errorCode;
	private int errorId;

	public String getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(String errorCode) {
		this.errorCode = errorCode;
	}

	public int getErrorId() {
		return errorId;
	}

	public void setErrorId(int errorId) {
		this.errorId = errorId;
	}

}

5. EmpNotFoundException.java: A normal exception class thrown in the web service.

5. EmpNotFoundException.java:Web服务中引发的普通异常类。

package com.journaldev.exception;

public class EmpNotFoundException extends Exception {

	private static final long serialVersionUID = 4351720088030656859L;
	private int errorId;

	public int getErrorId() {
		return errorId;
	}

	public EmpNotFoundException(String msg, int errorId) {
		super(msg);
		this.errorId = errorId;
	}

	public EmpNotFoundException(String msg, Throwable cause) {
		super(msg, cause);
	}
}

6. web.xml: Deployment descriptor for the web service. So any request with URI https://<HOST>:<PORT>/My-Jersey-Project/rest/* will be processed by Jersey ServletContainer servlet.

6. web.xml :Web服务的部署描述符。 因此,任何带有URI https://<HOST>:<PORT>/My-Jersey-Project/rest/*请求都将由Jersey ServletContainer servlet处理。

The init-param value passed for “com.sun.jersey.config.property.packages” defines the package jersey will look for the web service classes. This property must point to your resources classes. It also looks for the resource classes into the sub-packages.

为“ com.sun.jersey.config.property.packages”传递的init-param值定义了jersey将在其中查找Web服务类的软件包。 此属性必须指向您的资源类。 它还在子包中查找资源类。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xmlns="https://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>My Jersey Project</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>/rest/*</url-pattern>
	</servlet-mapping>
	<!-- Jersey Servlet configurations -->

</web-app>

7. EmpRouter.java: Resource class handling different kinds of request.

7. EmpRouter.java :处理不同类型请求的资源类。

  • @Path(“/emp”) – All the requests with URI https://<HOST>:<PORT>/My-Jersey-Project/rest/emp/ will be processed by this resource class.

    @Path(“ / emp”)–具有URI https://<HOST>:<PORT>/My-Jersey-Project/rest/emp/所有请求将由该资源类处理。
  • @Path(“/getEmp”) – All the requests with URI https://<HOST>:<PORT>/My-Jersey-Project/rest/emp/getEmp will be processed by this method.

    @Path(“ / getEmp”)–使用URI https://<HOST>:<PORT>/My-Jersey-Project/rest/emp/getEmp都将通过此方法处理。
  • @POST – This annotation defines that the HTTP method used should be POST. Some other possible values are @GET, @PUT, @DELETE

    @POST –此注释定义所使用的HTTP方法应为POST。 其他一些可能的值是@ GET,@ PUT,@ DELETE
  • @Consumes(MediaType.APPLICATION_XML) – The method accepts XML element

    @Consumes(MediaType.APPLICATION_XML)–该方法接受XML元素
  • @Produces(MediaType.APPLICATION_XML) – The method returns XML element

    @Produces(MediaType.APPLICATION_XML)–该方法返回XML元素
package com.journaldev.router;

import com.journaldev.exception.EmpNotFoundException;
import com.journaldev.model.*;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBElement;

@Path("/emp")
public class EmpRouter {

	@POST
	@Path("/getEmp")
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	public Response getEmp(JAXBElement<EmpRequest> empRequest)
			throws EmpNotFoundException {
		EmpResponse empResponse = new EmpResponse();
		if (empRequest.getValue().getId() == 1) {
			empResponse.setId(empRequest.getValue().getId());
			empResponse.setName(empRequest.getValue().getName());
		} else {
			throw new EmpNotFoundException("Wrong ID", empRequest.getValue()
					.getId());
		}
		return Response.ok(empResponse).build();
	}
}

8. EmpNotFoundExceptionMapper.java: Exception Mapper class that maps EmpNotFoundException to Response object. The class should have @Provider annotation. This class should be in the package provided for resource classes in web.xml. Implementation of toResponse() method generates the ErrorResponse object and set it as Entity in Response object with status as INTERNAL_SERVER_ERROR.

8. EmpNotFoundExceptionMapper.java :异常Mapper类,它将EmpNotFoundException映射到Response对象。 该类应具有@Provider批注。 此类应位于web.xml中为资源类提供的包中。 toResponse()方法的实现会生成ErrorResponse对象,并将其设置为Response对象中的Entity,状态为INTERNAL_SERVER_ERROR。

package com.journaldev.exceptionmapper;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import com.journaldev.exception.EmpNotFoundException;
import com.journaldev.model.ErrorResponse;

@Provider
public class EmpNotFoundExceptionMapper implements
		ExceptionMapper<EmpNotFoundException> {

	public EmpNotFoundExceptionMapper() {
	}
	
	public Response toResponse(
			EmpNotFoundException empNotFoundException) {
		ErrorResponse errorResponse = new ErrorResponse();
		errorResponse.setErrorId(empNotFoundException.getErrorId());
		errorResponse.setErrorCode(empNotFoundException.getMessage());
		return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
				errorResponse).type(
				MediaType.APPLICATION_XML).build();

	}

}

Our web service is ready, just build it to create the WAR file and deploy it to the application server.

我们的Web服务已准备就绪,只需构建它即可创建WAR文件并将其部署到应用程序服务器。

泽西岛客户示例 (Jersey Client Example)

We can use the Jersey Client to call our web service and get a response programmatically.

我们可以使用Jersey客户端来调用我们的Web服务并以编程方式获得响应。

EmpClient.java: This is a sample java program through which are invoking our web service. We are using Jersey Client API to invoke the service and based on response status we are parsing response entity to EmpResponse or ErrorResponse class.

EmpClient.java :这是一个示例Java程序,通过它可以调用我们的Web服务。 我们正在使用Jersey客户端API调用服务,并根据响应状态将响应实体解析为EmpResponse或ErrorResponse类。

package com.journaldev.client;

import javax.ws.rs.core.MediaType;

import com.journaldev.model.EmpRequest;
import com.journaldev.model.EmpResponse;
import com.journaldev.model.ErrorResponse;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class EmpClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String uri = "https://localhost:8080/My-Jersey-Project/rest/emp/getEmp";
		EmpRequest request = new EmpRequest();
		// set id as 1 for OK response
		request.setId(2);
		request.setName("PK");
		try {
			Client client = Client.create();
			WebResource r = client.resource(uri);
			ClientResponse response = r.type(MediaType.APPLICATION_XML).post(ClientResponse.class, request);
			System.out.println(response.getStatus());
			if (response.getStatus() == 200) {
				EmpResponse empResponse = response.getEntity(EmpResponse.class);
				System.out.println(empResponse.getId() + "::" + empResponse.getName());
			} else {
				ErrorResponse exc = response.getEntity(ErrorResponse.class);
				System.out.println(exc.getErrorCode());
				System.out.println(exc.getErrorId());
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

}

Success Response

成功回应

Error Response

错误回应

摘要 (Summary)

In this post, we learned how to create a REST web service using Jersey API. We also looked into the Jersey Client to invoke our REST APIs through java program.

在本文中,我们学习了如何使用Jersey API创建REST Web服务。 我们还研究了Jersey客户端,以通过java程序调用REST API。

GitHub Repository. GitHub存储库中检出完整的项目代码。

翻译自: https://www.journaldev.com/498/jersey-java-tutorial

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值