泽西(Jersey)Java教程

欢迎来到Java Jersey教程。最近,我开始使用JAX-RS Jersey框架来进行一个Restful web服务项目的工作。

Java Jersey Framework是什么?

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

这个教程适合谁使用?

本教程旨在帮助对使用JAX-RS API和JAXB开发和部署Restful Web服务感兴趣的Java程序员们。

2. 先决条件

这个教程的范围是使用Jersey API创建Restful Web服务,使用Java客户端程序调用Web服务,并使用工具测试Web服务。要轻松理解这个教程,需要基本了解Java、Web服务、XML、Maven和应用服务器(JBoss/Tomcat)。

3. 软件和工具 hé

  • JDK version 1.8.0_131
  • Apache Maven 3.5.3
  • Mac OS X 10.13.4
  • Tomcat 8.5.16
  • Eclipse Java EE IDE Oxygen 4.7.3

创建Jersey Eclipse Maven项目

jersey java tutorial eclipse project

Java Jersey Restful Web Service 项目解释

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.Olivia.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。重要的是要注意 @XmlRootElement 注解,将该类映射为一个XML元素。

package com.Olivia.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;
	}
}

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

package com.Olivia.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。

package com.Olivia.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:在网络服务中抛出的普通异常类。

package com.Olivia.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:Web服务的部署描述符。因此,任何以URI为https://:/My-Jersey-Project/rest/*的请求将由Jersey ServletContainer Servlet进行处理。传递给“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.Olivia</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:处理不同请求类型的资源类。

  • @Path(“/emp”) – All the requests with URI https://:/My-Jersey-Project/rest/emp/ will be processed by this resource class.
  • @Path(“/getEmp”) – All the requests with URI https://:/My-Jersey-Project/rest/emp/getEmp will be processed by this method.
  • @POST – This annotation defines that the HTTP method used should be POST. Some other possible values are @GET, @PUT, @DELETE
  • @Consumes(MediaType.APPLICATION_XML) – The method accepts XML element
  • @Produces(MediaType.APPLICATION_XML) – The method returns XML element
package com.Olivia.router;

import com.Olivia.exception.EmpNotFoundException;
import com.Olivia.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:异常映射器类,将EmpNotFoundException映射到响应对象。该类应该带有@Provider注解。这个类应该放在web.xml中为资源类提供的包中。toResponse()方法的实现生成ErrorResponse对象,并将其设置为Response对象的实体,状态为INTERNAL_SERVER_ERROR。

package com.Olivia.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.Olivia.exception.EmpNotFoundException;
import com.Olivia.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();

	}

}

我们的网络服务已经准备就绪,只需构建它以创建WAR文件并部署到应用服务器上。

泽西客户端示例

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

package com.Olivia.client;

import javax.ws.rs.core.MediaType;

import com.Olivia.model.EmpRequest;
import com.Olivia.model.EmpResponse;
import com.Olivia.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());
		}
	}

}
Jersey Client Exception Example

总结

在这篇文章中,我们学习了如何使用Jersey API创建一个REST Web服务。我们还研究了Jersey Client,通过Java程序调用我们的REST API。

你可以从我们的GitHub仓库上检出完整的项目代码。

发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds