HowToDoInJava-其它教程-1-三-

龙哥盟 / 2024-11-20 / 原文

HowToDoInJava 其它教程 1(三)

原文:HowToDoInJava

协议:CC BY-NC-SA 4.0

RESTEasy ExceptionMapper – 异常处理示例

原文: https://howtodoinjava.com/resteasy/resteasy-exceptionmapper-example/

学习使用 resteasy ExceptionMapper接口实现创建和处理自定义异常。 ExceptionMapper是供应器的契约,该供应器将 Java 异常映射到Response对象。

必须使用@Provider注解ExceptionMapper接口的实现才能正常工作。

1. Resteasy ExceptionMapper - 自定义异常处理器

ExceptionMapper的示例实现供应器类如下所示:

package com.howtodoinjava.exception;

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

@Provider
public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException> 
{
	@Override
	public Response toResponse(MyApplicationException exception) 
	{
		return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();	
	}
}

自定义异常类MyApplicationException.java的编写方式为:

package com.howtodoinjava.exception;

import java.io.Serializable;

public class MyApplicationException extends Exception implements Serializable
{
	private static final long serialVersionUID = 1L;

	public MyApplicationException()	{
		super();
	}
	public MyApplicationException(String msg)	{
		super(msg);
	}
	public MyApplicationException(String msg, Exception e)	{
		super(msg, e);
	}
}

2. Resteasy REST API

为了测试ExceptionMapper实现,我编写了以下 resteasy REST API。

package com.howtodoinjava.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.spi.validation.ValidateRequest;

import com.howtodoinjava.exception.MyApplicationException;

@Path("/rest")
public class UserService 
{
	@Path("/users/{id}")
	@GET
	@ValidateRequest
	public Response getUserBId	( @PathParam("id") String id ) throws MyApplicationException
	{
		//validate mandatory field
		if(id == null)
		{
			throw new MyApplicationException("id is not present in request !!");
		}
		//Validate proper format
		try
		{
			Integer.parseInt(id);
		}
		catch(NumberFormatException e)
		{
			throw new MyApplicationException("id is not a number !!");
		}
		//Process the request
		return Response.ok().entity("User with ID " + id + " found !!").build();
	}
}

3. RESTEasy ExceptionMapper 演示

上面的 API 接受Integer格式的用户'id'参数。 如果我们以无法解析为Integer的其他格式传递 id,则会抛出MyApplicationException。 我们的异常映射器应该能够处理这个问题。

3.1 有效请求

在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/1

Valid request to REST API

REST API 的有效请求

3.2 无效的请求 - 引发异常

在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/abc

Invalid request to REST API

REST API 的无效请求

要下载这个使用ExceptionMapper接口的 Resteasy 客户端异常处理示例的源代码,请遵循以下给定的链接。

源码下载

学习愉快!

RESTEasy 客户端 API

使用java.net包的 RESTful 客户端

原文: https://howtodoinjava.com/resteasy/restful-webservices-client-using-java-net-package/

到目前为止,在此博客中,我们已经学习了有关构建服务器端组件 RESTful Web 服务的知识。 在本文中,我们将学习构建一个 RESTful 客户端,以使用先前文章中编写的 Web 服务。

我将重新使用为 RESTEasy + JAXB xml 示例编写的代码库。 我将构建一个不使用任何第三方工具的纯 Java API 客户端。

1)构建 RESTful Web 服务 API

请遵循 RESTEasy + JAXB xml 示例中给出的步骤。

作为参考,服务和模型类为:

UserManagementModule.java

package com.howtodoinjava.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import com.howtodoinjava.model.User;

@Path("/user-management")
public class UserManagementModule
{
	@GET
	@Path("/users/{id}")
	@Produces("application/xml")
	public Response getUserById(@PathParam("id") Integer id)
	{
		User user = new User();
		user.setId(id);
		user.setFirstName("Lokesh");
		user.setLastName("Gupta");
		return Response.status(200).entity(user).build();
	}
}

User.java

package com.howtodoinjava.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @XmlAttribute(name = "id")
    private int id;

    @XmlElement(name = "firstName")
    private String firstName;

    @XmlElement(name = "lastName")
    private String lastName;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

2)创建 RESTFul Web 服务的用户客户端

我们的 Java 客户端基于java.net包 API。 我在这里做两个步骤:

  1. 以字符串格式捕获输出
  2. 从 xml 响应解组模型对象

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.howtodoinjava.model.User;

public class PureJavaClient 
{
	public static void main(String[] args) 
	{
		try 
		{
			URL url = new URL("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/xml");

			if (conn.getResponseCode() != 200) 
			{
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
			String apiOutput = br.readLine();
			System.out.println(apiOutput);
			conn.disconnect();

			JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));

			System.out.println(user.getId());
			System.out.println(user.getFirstName());
			System.out.println(user.getLastName());

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}

Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user id="10"><firstName>Lokesh</firstName><lastName>Gupta</lastName></user>
10
Lokesh
Gupta

单击以下链接下载此示例的源代码。

祝您学习愉快!

使用 RESTful API 的 RESTEasy 客户端

原文: https://howtodoinjava.com/resteasy/resteasy-client-for-consuming-rest-apis/

到目前为止,在此博客中,我们已经学习了有关构建服务器端组件 RESTful Web 服务的知识。 在本文中,我们将学习构建一个 RESTful 客户端,以使用先前文章中编写的 Web 服务。

我将重新使用为 RESTEasy + JAXB xml 示例编写的代码库。

我将要访问的 API 已定义。

@GET
@Path("/users/{id}")
public User getUserById (@PathParam("id") Integer id) 
{
	User user = new User();
	user.setId(id);
	user.setFirstName("demo");
	user.setLastName("user");
	return user;
}

@POST
@Path("/users")
public User addUser() 
{
   //Some code
}

要使用 JAX-RS RESTEasy 的客户端功能构建 RESTful 客户端,请遵循给定的说明。

1)验证以下 RESTEasy 依赖项

<!-- core library -->
<dependency>
	<groupId>org.jboss.resteasy</groupId>
	 <artifactId>resteasy-jaxrs</artifactId>
	<version>2.3.1.GA</version>
</dependency>
<dependency>
	<groupId>net.sf.scannotation</groupId>
	<artifactId>scannotation</artifactId>
	<version>1.0.2</version>
</dependency>
<!-- JAXB provider -->
<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jaxb-provider</artifactId>
	<version>2.3.1.GA</version>
</dependency>	

2)编写客户端代码以访问 GET API,如下所示

public static void sampleResteasyClientGETRequest() throws Exception 
{
	//Define the API URI where API will be accessed
	ClientRequest request = new ClientRequest("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");

	//Set the accept header to tell the accepted response format
	request.accept("application/xml");

	//RESTEasy client automatically converts the response to desired objects.
	//This is how it is done.
	//Populate the response in user object
	ClientResponse<User> response = request.get(User.class);

	//First validate the api status code
	int apiResponseCode = response.getResponseStatus().getStatusCode();
	if(response.getResponseStatus().getStatusCode() != 200)
	{
		throw new RuntimeException("Failed with HTTP error code : " + apiResponseCode);
	}

	//Get the user object from entity
	User user = response.getEntity();

	//verify the user object
	System.out.println(user.getId());
	System.out.println(user.getFirstName());
	System.out.println(user.getLastName());
}

3)编写客户端代码以访问 POST API,如下所示

public static void sampleResteasyClientPostRequest() throws Exception 
{
	User user = new User();
	user.setId(100);
	user.setFirstName("Lokesh");
	user.setLastName("Gupta");

	StringWriter writer = new StringWriter();
	JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	jaxbMarshaller.marshal(user, writer);

	//Define the API URI where API will be accessed
	ClientRequest request = new ClientRequest("http://localhost:8080/RESTfulDemoApplication/user-management/users");

	//Set the accept header to tell the accepted response format
	request.body("application/xml", writer.getBuffer().toString());

	//Send the request
	ClientResponse response = request.post();

	//First validate the api status code
	int apiResponseCode = response.getResponseStatus().getStatusCode();
	if(response.getResponseStatus().getStatusCode() != 201)
	{
		throw new RuntimeException("Failed with HTTP error code : " + apiResponseCode);
	}
}

祝您学习愉快!

Apache HttpClient GET 和 POST 示例

原文: https://howtodoinjava.com/resteasy/jax-rs-restful-client-using-apache-httpclient/

我们已经学习了有关构建 RESTful Web 服务的知识。 现在学习构建 JAX-RS REST 客户端以便使用 HttpClient RESTful 客户端来使用 Web 服务。

我将重用为 jaxrs xml 示例编写的代码。

我将访问的 HTTP GET 和 POST REST API 已定义。

@GET
@Path("/users/{id}")
public User getUserById (@PathParam("id") Integer id) 
{
	User user = new User();
	user.setId(id);
	user.setFirstName("demo");
	user.setLastName("user");
	return user;
}

@POST
@Path("/users")
public User addUser() 
{
   //Some code
}

要使用 Apache httpclient 构建 RESTful 客户端,请遵循以下说明。

1. Apache HttpClient Maven 依赖项

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.1.1</version>
</dependency>

2. Apache HttpClient GET API 示例

Java 程序,用于如何使用 http get 请求发送 json 数据。

public static void demoGetRESTAPI() throws Exception 
{
	DefaultHttpClient httpClient = new DefaultHttpClient();
	try
	{
		//Define a HttpGet request; You can choose between HttpPost, HttpDelete or HttpPut also.
		//Choice depends on type of method you will be invoking.
		HttpGet getRequest = new HttpGet("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");

		//Set the API media type in http accept header
		getRequest.addHeader("accept", "application/xml");

		//Send the request; It will immediately return the response in HttpResponse object
		HttpResponse response = httpClient.execute(getRequest);

		//verify the valid error code first
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 200) 
		{
			throw new RuntimeException("Failed with HTTP error code : " + statusCode);
		}

		//Now pull back the response object
		HttpEntity httpEntity = response.getEntity();
		String apiOutput = EntityUtils.toString(httpEntity);

		//Lets see what we got from API
		System.out.println(apiOutput); //<user id="10"><firstName>demo</firstName><lastName>user</lastName></user>

		//In realtime programming, you will need to convert this http response to some java object to re-use it.
		//Lets see how to jaxb unmarshal the api response content
		JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));

		//Verify the populated object
		System.out.println(user.getId());
		System.out.println(user.getFirstName());
		System.out.println(user.getLastName());
	}
	finally
	{
		//Important: Close the connect
		httpClient.getConnectionManager().shutdown();
	}
}

3. 带有 json 正文的 Apache HttpClient POST API 示例

Java 程序,用于如何使用 http post 请求将 json 数据发送到服务器。

public static void demoPostRESTAPI() throws Exception 
{
	DefaultHttpClient httpClient = new DefaultHttpClient();

	User user = new User();
	user.setId(100);
	user.setFirstName("Lokesh");
	user.setLastName("Gupta");

	StringWriter writer = new StringWriter();
	JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	jaxbMarshaller.marshal(user, writer);

	try
	{
		//Define a postRequest request
		HttpPost postRequest = new HttpPost("http://localhost:8080/RESTfulDemoApplication/user-management/users");

		//Set the API media type in http content-type header
		postRequest.addHeader("content-type", "application/xml");

		//Set the request post body
		StringEntity userEntity = new StringEntity(writer.getBuffer().toString());
		postRequest.setEntity(userEntity);

		//Send the request; It will immediately return the response in HttpResponse object if any
		HttpResponse response = httpClient.execute(postRequest);

		//verify the valid error code first
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 201) 
		{
			throw new RuntimeException("Failed with HTTP error code : " + statusCode);
		}
	}
	finally
	{
		//Important: Close the connect
		httpClient.getConnectionManager().shutdown();
	}
}

源码下载

将您对 http GET
和 POST 请求的 httpclient 示例的评论发给我。

学习愉快!

RESTEasy Javascript/Ajax 客户端演示

原文: https://howtodoinjava.com/resteasy/resteasy-javascriptajax-client-demo/

如果正在开发 Web 应用,则 RESTEasy 为构建 Ajax 驱动的客户端提供了非常出色的支持。 RESTEasy 可以生成一个 JavaScript API,该 API 使用 AJAX 调用来调用 JAX-RS 操作。 生成用于访问 REST API 的 JavaScript 代码与 Java 代码非常相似,您会感觉自己正在用 Java 语言调用 REST API。

这种方法的优点(或缺点?)是您的类名和方法名可以通过 javascript 代码直接访问。 即使您不需要编写自动嵌入在您的网页中的 Ajax 处理代码。

注意:在 JS 代码中使用类和方法名称可能会成为一个非常严重的安全漏洞。 因此,请明智地使用它。

在本教程中,我构建了一个普通的 HTML 表单,该表单是用于将用户添加到系统中的用户。 我将使用 RESTEasy Ajax 客户端来访问 REST API,以添加用户并获取响应。

步骤 1)添加对 RESTEasy JSAPI 的运行时支持

<dependency>
	<groupId>org.jboss.resteasy</groupId>
	<artifactId>resteasy-jsapi</artifactId>
	<version>2.3.1.GA</version>
</dependency>

如果不使用 maven 构建工具,则可以将 jar 文件添加到 lib 文件夹中。

步骤 2)添加 JSAPI Servlet 映射

web.xml文件中的 Servlet 声明下方添加。 必须将 JavaScript API Servlet 配置为启用 JavaScript API。

<servlet>
	<servlet-name>RESTEasy-JSAPI</servlet-name>
	<servlet-class>org.jboss.resteasy.jsapi.JSAPIServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>RESTEasy-JSAPI</servlet-name>
	<url-pattern>/js/*</url-pattern>
</servlet-mapping>

步骤 3)编写需要从 javascript/ajax 中调用的 REST API

我正在编写一个最小的 REST API,以使示例不复杂。

@Path("/rest")
public class UserService 
{
	@Path("/users")
	@POST
	public Response addUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName)
	{
		//vaildate first name
		if(firstName == null || firstName.isEmpty())
		{
			return Response.ok().entity("First name is mandatory dude").build();
		}
		//vaildate last name
		if(lastName == null || lastName.isEmpty())
		{
			return Response.ok().entity("Don't you have any last name? I will keep secret").build();
		}
		//Add user and return the response
		return Response.ok().entity("User "" + firstName + "" added through JAX-RS JavaScript API").build();
	}
}

步骤 4)在视图层上构建 Ajax 客户端

我正在使用默认的index.jsp文件编写客户端代码。

示例 1:

<html>
	<head>
		<!-- This will include the whole javascript file including ajax handling  -->
		<script lang="javascript" src="./js"></script>

		<!-- Write the javascript code for accessing REST APIs -->
		<script lang="javascript">
			function addUserForm()
			{
				//Collect input from html page
				var firstNameTxt = document.getElementById("firstName").value;
				var lastNameTxt = document.getElementById("lastName").value;

				//Call the REST APIs with directly method names
				var message = UserService.addUser({firstName:firstNameTxt,lastName:lastNameTxt});

				//Use the REST API response
				document.getElementById("error").innerHTML = "<h2><span style='color:red'>" + message + " !!</span></h2>";
			}
		</script>
	</head>
	<body>
		<h1>RESTEasy Ajax client demo</h1>
		<div id="error"></div>
		<form method="post">
			<p>First Name : <input type="text" name="firstName" id="firstName"/></p>
			<p>LastName : <input type="text" name="lastName" id="lastName"/></p>
			<input type="button" value="Add User" onclick="addUserForm()" />
		</form>
		Demo by : <b>https://www.howtodoinjava.com</b>
	</body>
</html>

示例 2:

如果发现使用类名和方法名是不可管理的,因为它们可能在另一天得到更改。 不用担心,REST 隐式对象正在为您解救。 演示 REST 调用如下:

//Example Two using REST object
function addUserForm()
{
	//Collect input from html page
	var firstNameTxt = document.getElementById("firstName").value;
	var lastNameTxt = document.getElementById("lastName").value;

	var req = new REST.Request();
	req.setURI(REST.apiURL + "/rest/users");
	req.setMethod("POST");
	req.setEntity({firstName:firstNameTxt,lastName:lastNameTxt});
	req.execute(function(status, request, entity){
		document.getElementById("error").innerHTML = "<h2><span style='color:red'>" + entity + " !!</span></h2>";
	});
} 

测试应用

要测试该应用,请将其部署在任何 Web 服务器中。

1)输入网址http://localhost:8080/RESTfulValidation/

resteasy-ajax-demo

示例欢迎界面

2)仅填写名字,然后按添加按钮

Validation error for last name field

姓氏字段的验证错误

3)填写两个字段,然后按添加按钮

User added successfully

用户添加成功

要下载上面演示的源代码,请遵循以下给定的下载链接。

祝您学习愉快!

JAX-RS 2.0 RESTEasy 3.0.2.Final 客户端 API 示例

原文: https://howtodoinjava.com/resteasy/jax-rs-2-0-resteasy-3-0-2-final-client-api-example/

JAX-RS 2.0 在以前的版本中带来了很多改进。 主要改进之一是客户端 API,它在 JAX-RS 1.0 中完全丢失。 尽管编写可移植的 JAX-RS 服务很容易,但是每个 JAX-RS 实现都定义了自己的专有 API。 JAX-RS 2.0 用流畅的,低级的请求构建 API 填补了这一空白。 这是一个简单的示例:

	Client client = ClientFactory.newClient(); 
	WebTarget target = client.target("http://localhost:8080/howtodoinjava"); 
	Form form = new Form().param("customer", "Bill").param("product", "book"); 
	Response response = target.request().post(Entity.form(form)); 
	Order order = response.readEntity(Order.class); 

上面的代码特定于 JAX-RS 2.0,并使用 JAX-RS 类。 如果您正在使用最新的 RESTEasy (版本 3)内部版本,则可以使用其客户端 API 提供的 RESTEasy 抽象的这些较低级别的 JAX-RS 2.0 API。

JAX-RS RESTEasy API

让我们以示例网络服务 API 为例,我们将在客户端代码中对其进行访问:

	@GET
	@Path("/users")
	@Produces("application/vnd.com.demo.user-management.users+xml;charset=UTF-8;version=1")
	public Users getAllUsers() {
		User user1 = new User();
		user1.setId(1);
		user1.setFirstName("demo");
		user1.setLastName("user");
		user1.setUri("/user-management/users/1");

		User user2 = new User();
		user2.setId(2);
		user2.setFirstName("Mark");
		user2.setLastName("Dwain");
		user2.setUri("/user-management/users/2");

		Users users = new Users();
		users.setUsers(new ArrayList<User>());
		users.getUsers().add(user1);
		users.getUsers().add(user2);

		return users;
	}

	@POST
	@Path("/users")
	@Consumes("application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1")
	public Response createUser(User user,
			@DefaultValue("false") @QueryParam("allow-admin") boolean allowAdmin)
			throws URISyntaxException {
		System.out.println(user.getFirstName());
		System.out.println(user.getLastName());
		return Response.status(201)
				.contentLocation(new URI("/user-management/users/123")).build();
	}

客户端代码

现在,使用新客户端代码访问这些 API:

package test.jaxrs2;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.demo.rest.model.User;
import com.demo.rest.model.Users;

public class Demo_JAXRS_2_Example 
{
	public static void main(String[] args) 
	{
		getExample_one();
		getExample_two();
		postExample();
	}

	private static void getExample_one() 
	{
		ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target("http://localhost:8080/RESTEasyApplication/user-management/users");
        Response response = target.request().get();
        //Read output in string format
        String value = response.readEntity(String.class);
        System.out.println(value);
        response.close();  
	}

	private static void getExample_two()
	{
		ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target("http://localhost:8080/RESTEasyApplication/user-management/users");
        Response response = target.request().get();
        //Read the entity
        Users users = response.readEntity(Users.class);
        for(User user : users.getUsers()){
        	System.out.println(user.getId());
        	System.out.println(user.getLastName());
        }
        response.close();  
	}

	private static void postExample() 
	{
		User user = new User();
		user.setFirstName("john");
		user.setLastName("Maclane");

		ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target("http://localhost:8080/RESTEasyApplication/user-management/users");
        Response response = target.request().post(Entity.entity(user, "application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1"));
        //Read output in string format
        System.out.println(response.getStatus());
        response.close();  
	}

}

Output in console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<users>
<user id="1" uri="/user-management/users/1"><firstName>demo</firstName><lastName>user</lastName></user>
<user id="2" uri="/user-management/users/2"><firstName>demo</firstName><lastName>user</lastName></user>
</users>
1
user
2
Dwain
201

Maven 配置

我已经使用下面的 Maven 配置来运行这些示例。

  <repositories>
	<repository>
	  <id>jboss</id>
	  <url>http://repository.jboss.org/maven2</url>
	</repository>
  </repositories>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
     <!-- core library -->
	 <dependency>
	    <groupId>org.jboss.resteasy</groupId>
	     <artifactId>resteasy-jaxrs</artifactId>
	    <version>3.0.2.Final</version>
	 </dependency>
	<!-- JAXB support -->
	<dependency>
	  <groupId>org.jboss.resteasy</groupId>
	    <artifactId>resteasy-jaxb-provider</artifactId>
	  <version>3.0.2.Final</version>
	</dependency>
	<dependency>
	    <groupId>org.jboss.resteasy</groupId>
	    <artifactId>jaxrs-api</artifactId>
	    <version>3.0.2.Final</version>
	</dependency>
	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		<artifactId>resteasy-client</artifactId>
		<version>3.0.2.Final</version>
	</dependency>
	<dependency>
	    <groupId>net.sf.scannotation</groupId>
	    <artifactId>scannotation</artifactId>
	    <version>1.0.3</version>
	</dependency>
  </dependencies>

要下载以上示例的源代码,请点击以下链接。

[下载源码](https://docs.google.com/file/d/0B7yo2HclmjI4NS1IQUZLUjI1Q0U/edit?usp=sharing "jax-rs 2.0 resteasy client code swource code")

学习愉快!

Maven – 本地,远程和中央仓库

原文: https://howtodoinjava.com/maven/local-remote-central-repositories/

Maven 仓库是物理目录,其中包含打包的 JAR 文件以及有关这些 jar 文件的额外元数据。 此元数据采用 POM 文件的形式,这些文件具有 jar 文件项目信息,包括此 JAR 文件还具有哪些其他外部依赖项。 这些其他外部依赖项会暂时下载到您的项目中,并成为该项目的有效 pom 的一部分。

Table of Contents

Local repository
Central repository
Remote repository

本地仓库

Maven 本地仓库位于开发人员的计算机中。 每当您运行需要这些依赖项的 maven 目标时,maven 都会从远程服务器下载依赖项并将它们存储在开发人员的计算机中。

默认情况下,Maven 在用户主目录(即C:/Users/superdev/.m2目录)内创建本地仓库。 您可以使用localRepository标签在setting.xml文件中更改本地仓库的位置。

<settings>
    <localRepository>
        C:\M2
    </localRepository>
</settings>

将依赖项存储到本地计算机有两个主要好处。 首先,多个项目可以访问相同的工件,从而减少了存储需求。 其次,由于依赖项仅下载一次,因此也减少了网络使用率。

中央仓库

Maven 中央仓库位于 http://repo.maven.apache.org/maven2/。 每当您运行构建作业时,Maven 都会首先尝试从本地仓库中找到依赖项。 如果不存在,默认情况下,maven 将触发从该中央仓库位置进行下载。

Maven Central Repository

Maven 中央仓库

要覆盖此默认位置,可以更改settings.xml文件以使用一个或多个镜像。

如果您在任何防火墙后面,则无需进行任何特殊配置即可访问中央仓库,但网络代理设置除外。

远程仓库

除了中央仓库之外,您可能还需要将工件部署在其他远程位置。 例如,在您的公司办公室中,可能仅存在特定于组织的项目或模块。 在这种情况下,组织可以创建远程仓库并部署这些私有工件。 仅在组织内部可以访问此远程仓库。

这些 maven 远程仓库的工作方式与 maven 的中央仓库完全相同。 每当需要这些仓库中的工件时,都会先将其下载到开发人员的本地仓库中,然后再使用。

您可以在 POM 文件中配置远程仓库,也可以在远程仓库本身中配置超级 POM 文件。

<repositories>
   <repository>
       <id>org.source.repo</id>
       <url>http://maven.orgName.com/maven2/</url>
   </repository>
</repositories>

将我的问题放在评论部分。

学习愉快!

参考:仓库简介

RESTEasy 最佳实践

RESTEasy - 与ResteasyProviderFactory共享上下文数据

原文: https://howtodoinjava.com/resteasy/share-context-data-with-jax-rs-resteasyproviderfactory/

很多时候,我们不得不将数据从应用传递到多层。 使用拦截器的应用就是一个例子。 假设我们的应用中有两个拦截器,一个用于登录检查,另一个用于将审计信息放入数据库。 我们要使用 User 对象从第一个拦截器进入第二个拦截器。

在基于 RESTEasy 的应用中,可以使用ResteasyProviderFactory实例轻松实现上述功能。 通过使用以下定义在web.xml文件中添加过滤器,可以启用ResteasyProviderFactory

<listener>
  <listener-class>
	 org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
  </listener-class>
</listener>

现在,您可以在 RESTEasy 上下文范围内的任何类中轻松获取ResteasyProviderFactory的实例。 因此,要在拦截器之间共享数据,您将需要执行两个步骤:

1)在上下文映射中设置数据

使用pushContext()方法设置此上下文数据。 此方法将数据添加到定义为以下内容的线程本地栈中:

protected static ThreadLocalStack<Map<Class<?>, Object>> contextualData 
						= new ThreadLocalStack<Map<Class<?>, Object>>();

您需要按以下方式推送数据:

User user = new User();
//Set some user attributes

//Get registered ResteasyProviderFactory instance
ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();

//Add user into context data map
factory.pushContext(User.class, user);

2)从上下文映射中获取数据

第一步取回数据集非常简单。 使用popContextData()方法。 该上下文数据本质上是线程局部的,因此在代码的另一个位置进行检索时,您不必担心会得到错误的数据。

 ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
 factory.popContextData(User.class);

这样,您可以使用ResteasyProviderFactory在应用的多个层之间共享数据。

学习愉快!

RESTEasy ExceptionMapper – 异常处理示例

原文: https://howtodoinjava.com/resteasy/exception-handling-in-jax-rs-resteasy-with-exceptionmapper/

学习使用 resteasy ExceptionMapper接口实现创建和处理自定义异常。 ExceptionMapper是供应器的契约,该供应器将 Java 异常映射到Response对象。

必须使用@Provider注解ExceptionMapper接口的实现才能正常工作。

1. Resteasy ExceptionMapper - 自定义异常处理器

ExceptionMapper的示例实现供应器类如下所示:

package com.howtodoinjava.exception;

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

@Provider
public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException> 
{
	@Override
	public Response toResponse(MyApplicationException exception) 
	{
		return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();	
	}
}

自定义异常类MyApplicationException.java的编写方式为:

package com.howtodoinjava.exception;

import java.io.Serializable;

public class MyApplicationException extends Exception implements Serializable
{
	private static final long serialVersionUID = 1L;

	public MyApplicationException()	{
		super();
	}
	public MyApplicationException(String msg)	{
		super(msg);
	}
	public MyApplicationException(String msg, Exception e)	{
		super(msg, e);
	}
}

2. Resteasy REST API

为了测试ExceptionMapper实现,我编写了以下 resteasy REST API。

package com.howtodoinjava.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.spi.validation.ValidateRequest;

import com.howtodoinjava.exception.MyApplicationException;

@Path("/rest")
public class UserService 
{
	@Path("/users/{id}")
	@GET
	@ValidateRequest
	public Response getUserBId	( @PathParam("id") String id ) throws MyApplicationException
	{
		//validate mandatory field
		if(id == null)
		{
			throw new MyApplicationException("id is not present in request !!");
		}
		//Validate proper format
		try
		{
			Integer.parseInt(id);
		}
		catch(NumberFormatException e)
		{
			throw new MyApplicationException("id is not a number !!");
		}
		//Process the request
		return Response.ok().entity("User with ID " + id + " found !!").build();
	}
}

3. RESTEasy ExceptionMapper演示

上面的 API 接受Integer格式的用户'id'参数。 如果我们以无法解析为Integer的其他格式传递 id,则会抛出MyApplicationException。 我们的异常映射器应该能够处理这个问题。

3.1 有效请求

在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/1

Valid request to REST API

REST API 的有效请求

3.2 无效请求 - 引发异常

在浏览器中访问http://localhost:8080/RESTEasyExceptionMapperDemo/rest/users/abc

Invalid request to REST API

REST API 的无效请求

要使用ExceptionMapper接口下载此 Resteasy 客户端异常处理示例的源代码,请遵循以下给定的链接。

源码下载

学习愉快!

使用 ETag 的 RESTEasy 缓存控制示例

原文: https://howtodoinjava.com/resteasy/jax-rs-resteasy-cache-control-with-etag-example/

ETags 或实体标签是很有用的 HTTP 标头,它们可以通过最小化系统上的服务器负载来帮助构建超快速的应用。 ETag 设置为对客户端的响应,因此客户端可以对条件请求使用各种控制请求标头,例如If-MatchIf-None-Matchjavax.ws.rs.core.Response.ResponseBuilder#tag()javax.ws.rs.core.EntityTag是用于 ETag 的实用类。

在服务器端,不变的 ETag(HTTP 请求附带的 ETag 与为请求的资源计算的 ETag 之间的匹配)只是意味着,资源与上次请求时间相比没有变化,因此只需发送 HTTP 304 标头[未修改]就足够了, 客户端可以使用本地可用的资源副本而不必担心。

为了演示该示例,我在服务类中有两个 REST API。

a)GET http://localhost:8080/RESTEasyEtagDemo/user-service/users/1

此 API 将获取用户资源,该资源将附加有 ETag。 服务器将使用此 ETag 来验证用户详细信息是否已在上次请求中更新。

b)PUT http://localhost:8080/RESTEasyEtagDemo/user-service/users/1

此 API 将对服务器上的用户资源进行一些更新,这将强制服务器再次返回新的资源副本。

让我们逐步构建示例。

步骤 1)使用 maven 创建一个新的 Java Web 项目并添加以下依赖项。

<repositories>
	<repository>
	  <id>jboss</id>
	  <url>http://repository.jboss.org/maven2</url>
	</repository>
</repositories>
<dependencies>
	<!-- core library -->
	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		<artifactId>resteasy-jaxrs</artifactId>
		<version>2.3.1.GA</version>
	</dependency>
	<!-- JAXB support -->
	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		<artifactId>resteasy-jaxb-provider</artifactId>
		<version>2.3.1.GA</version>
	</dependency>
	<dependency>
		<groupId>net.sf.scannotation</groupId>
		<artifactId>scannotation</artifactId>
		<version>1.0.2</version>
	</dependency>
</dependencies>

步骤 2)制作一个类来表示用户资源

确保提供一些逻辑来验证修改此资源后的最后更新时间。 我添加了一个日期类型为lastModied的字段。

package com.howtodoinjava.demo.rest.model;

import java.io.Serializable;
import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "user")
public class User implements Serializable 
{
	@XmlAttribute(name = "id")
	private int id;

	@XmlAttribute(name="uri")
	private String uri;

	@XmlElement(name = "firstName")
	private String firstName;

	@XmlElement(name = "lastName")
	private String lastName;

	@XmlElement(name="last-modified")
	private Date lastModified;

	//Setters and Getters

步骤 3)在 DAO 层添加访问和修改资源的方法

我出于示例目的使用了静态HashMap。 在实时应用中,它将是一个数据库。 例如,我在映射中仅添加了一个用户。

package com.howtodoinjava.demo.rest.data;

import java.util.Date;
import java.util.HashMap;

import com.howtodoinjava.demo.rest.model.User;

public class UserDatabase 
{
	public static HashMap<Integer, User> users = new HashMap<Integer, User>();
	static 
	{
		User user = new User();
		user.setId(1);
		user.setFirstName("demo");
		user.setLastName("user");
		user.setUri("/user-management/users/1");
		user.setLastModified(new Date());
		users.put(1, user);
	}

	public static User getUserById(Integer id)
	{
		return users.get(id);
	}

	public static void updateUser(Integer id)
	{
		User user = users.get(id);
		user.setLastModified(new Date());
	}

	public static Date getLastModifiedById(Integer id)
	{
		return users.get(id).getLastModified();
	}
}

步骤 4)编写 Restful API 以访问和修改资源

这是主要步骤。 我已经在上面描述了两个 API。 GET API 返回附加了 ETag 的用户资源。 此 ETag 是在用户资源的最后修改日期计算的。 这将确保每次用户更新时,都会生成一个新的 ETag。

package com.howtodoinjava.demo.rest.service;

import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;

import com.howtodoinjava.demo.rest.data.UserDatabase;

@Path("/user-service")
public class UserService 
{
	@GET
	@Path("/users/{id}")
	public Response getUserById(@PathParam("id") int id, @Context Request req) 
	{
		//Create cache control header
		 CacheControl cc = new CacheControl();
		 //Set max age to one day
	     cc.setMaxAge(86400);

		Response.ResponseBuilder rb = null;

		//Calculate the ETag on last modified date of user resource  
		EntityTag etag = new EntityTag(UserDatabase.getLastModifiedById(id).hashCode()+"");

		//Verify if it matched with etag available in http request
        rb = req.evaluatePreconditions(etag);

        //If ETag matches the rb will be non-null; 
        //Use the rb to return the response without any further processing
        if (rb != null) 
        {
            return rb.cacheControl(cc).tag(etag).build();
        }

        //If rb is null then either it is first time request; or resource is modified
        //Get the updated representation and return with Etag attached to it
        rb = Response.ok(UserDatabase.getUserById(id)).cacheControl(cc).tag(etag);
		return rb.build();
	}

	@PUT
	@Path("/users/{id}")
	public Response updateUserById(@PathParam("id") int id) 
	{
		//Update the User resource
		UserDatabase.updateUser(id);
		return Response.status(200).build();
	}
}

警告:HTTP 标头中使用的日期的粒度不如数据源中使用的某些日期那么精确。 例如,数据库行中日期的精度可以定义为毫秒。 但是,HTTP 标头字段中的日期仅精确到秒。 在求值 HTTP 前提条件时,如果将java.util.Date对象直接与 HTTP 标头中的日期进行比较,则精度差异可能会产生意外结果。

为避免此问题,请使用日期对象的哈希码或使用某些规范化形式。

测试示例代码

1)首次请求:GET http://localhost:8080/RESTEasyEtagDemo/user-service/users/1

User resource request first time

用户资源的第一次请求

2)后续请求:GET http://localhost:8080/RESTEasyEtagDemo/user-service/users/1

User resource subsequent  requests

用户资源的后续请求

3)修改请求:PUT http://localhost:8080/RESTEasyEtagDemo/user-s:rvice/users/1

User resource Updated using PUT API

使用 PUT API 更新的用户资源

4)更新资源:GET http://localhost:8080/RESTEasyEtagDemo/user-service/users/1

Update User resource retrieved

检索更新的用户资源

要下载以上示例的源代码,请单击下面给出的链接。

祝您学习愉快!

RESTEasy – 启用 Gzip 压缩内容编码

原文: https://howtodoinjava.com/resteasy/enable-gzip-compression-content-encoding-in-resteasy/

JAX-RS Resteasy 具有自动 GZIP 压缩支持。 如果客户端框架或 JAX-RS 服务接收到具有“gzip”内容编码的消息正文,它将自动对其进行解压缩。 客户端框架自动将Accept-Encoding标头设置为“gzip, deflate”。 因此,您不必自己设置此标头。

要使用 gzip 压缩,请按以下方式使用@GZIP注解。

	//Output compression
	@GET
	@Path("/users")
	@GZIP
	@Produces("application/xml")
	public Users getAllUsers() 
	{
		//more code....
	}

	//OR

	//Input compression
	@POST
	@Path("/users")
	@Consumes("application/vnd.com.demo.user-management.user+xml;charset=UTF-8;version=1")
	public Response createUser(@GZIP User user,
			@DefaultValue("false") @QueryParam("allow-admin") boolean allowAdmin)
			throws URISyntaxException 
	{
		//More code...
	}

用法示例

在上面的 GET REST API 上调用时,没有 gzip 压缩的示例 API 输出将如下所示:

	Date: Sat, 03 Aug 2013 06:18:41 GMT
	Server: Apache-Coyote/1.1
	Content-Length: 277
	Content-Type: application/vnd.com.demo.user-management.users+xml;version="1";charset=UTF-8

RESTEasy example without gzip compression

不带 gzip 压缩得 RESTEasy 示例

使用@GZIP注解进行 gzip 压缩的示例 API 输出

Date: Sat, 03 Aug 2013 06:31:21 GMT
Content-Encoding: gzip
Server: Apache-Coyote/1.1
Content-Length: 165
Content-Type: application/vnd.com.demo.user-management.users+xml;version="1";charset=UTF-8

RESTEasy example with gzip compression

带有 gzip 压缩的 RESTEasy 示例

给我留言,帖子中还不清楚。

祝您学习愉快!

比较 SOAP 与 RESTful Web 服务

原文: https://howtodoinjava.com/resteasy/comparing-soap-vs-restful-web-services/

尽管 SOAPRESTful Web 服务 – 都具有相同的目的,即基于 SOA(面向服务的架构)构建应用,但是它们在如何帮助实现最终输出的方式上,有着很大程度上不同。 让我们记下基于 SOAP 和 REST 的 API 之间最明显的区别

SOAP REST
SOAP 是基于 XML 的消息传递协议 REST 不是协议而是建筑风格
SOAP 具有用于状态实现的规范 REST 仅遵循无状态模型
最少的工具/中间件是必需的。 仅需要 HTTP(主要是基于 HTTP)的支持 URL 通常引用正在访问/删除/更新的资源
定义良好的机制来描述接口,例如 WSDL + XSD,WS-Policy 正式描述标准尚未广泛使用。 每个人都自己解释
有效负载必须符合 SOAP 模式 有效负载无限制
内置错误处理 尽管可以使用 HTTP 错误代码,但没有错误处理
SMTP 和 HTTP 都是有效的应用层协议,用作 SOAP 传输 绑定到 HTTP 传输模型
SOAP Web 服务完全忽略 Web 缓存机制 RESTful Web 服务充分利用了 Web 缓存机制,因为它们基本上基于 URL。
很难学 易于学习,因为每个人都了解 HTTP
通过 WS-SECURITY 对 SOAP 安全性进行了很好的标准化 HTTP 协议层提供了安全性,例如基本认证和通过 TLS 的通信加密
当您向外界发布复杂或可能会更改的 API 时,SOAP 将更加有用 除此之外,REST 通常是更好的选择

如果您知道这些差异,请随时添加。 它也会帮助其他人。

祝您学习愉快!

Jersey 教程

Jersey HelloWorld 例子

原文: https://howtodoinjava.com/jersey/jax-rs-jersey-hello-world-example/

我已经写了很多关于 JAX-RS RESTEasy 概念以及原理的文章。 现在,我开始探索 Jersey,这是另一个制作 RESTFul 应用的流行框架。 首先,我将在本文中编写我的 HelloWorld 应用,在下一篇文章中将对其进行修改,以显示 Jersey 提供的其他功能的演示。

步骤 1)使用 Maven 创建一个 Eclipse Web 项目

在此处学习制作 Eclipse Maven 项目

步骤 2)更新pom.xml文件中的 Jersey 依赖项

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.howtodoinjava</groupId>
  <artifactId>JerseyHelloWorld</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>JerseyHelloWorld Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <repositories>
		<repository>
			<id>maven2-repository.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/2/</url>
			<layout>default</layout>
		</repository>
	</repositories>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-server</artifactId>
		<version>1.17.1</version>
	</dependency>
	<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-core</artifactId>
		<version>1.17.1</version>
	</dependency>
	<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-servlet</artifactId>
		<version>1.17.1</version>
	</dependency>
  </dependencies>

  <build>
    <finalName>JerseyHelloWorld</finalName>
	    <plugins>
		    <plugin>
		      <artifactId>maven-compiler-plugin</artifactId>
		        <configuration>
		          <source>1.6</source>
		          <target>1.6</target>
		        </configuration>
		    </plugin>
	  </plugins>
  </build>
</project>

步骤 3)更新web.xml文件。将 servlet 映射到com.sun.jersey.spi.container.servlet.ServletContainer

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

  <display-name>Archetype Created Web Application</display-name>

  <servlet>
		<servlet-name>jersey-serlvet</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.howtodoinjava.rest</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest-points/*</url-pattern>
	</servlet-mapping>

</web-app>

步骤 4)编写第一个 REST 服务类

由于 JAX-RS 使用了通用注解,因此服务类看起来与 RESTEasy 完全一样。

package com.howtodoinjava.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/show-on-screen")
public class JerseyHelloWorldService
{
	@GET
	@Path("/{message}")
	public Response getMsg(@PathParam("message") String msg)
	{
		String output = "Message requested : " + msg;
		//Simply return the parameter passed as message
		return Response.status(200).entity(output).build();
	}
}

测试应用

要在浏览器中的 URL 下面测试应用类型:http://localhost:8080/JerseyHelloWorld/rest-points/show-on-screen/HowToDoInJava_Dot_Com

这将在服务类中调用 REST API 方法,并打印作为路径参数传递的消息。

Jersey HelloWorld message

Jersey HelloWorld 消息

要下载以上文章的来源,请单击下面的链接。

祝您学习愉快!

Jersey2 HelloWorld 示例 – Jersey2 教程

原文: https://howtodoinjava.com/jersey/jersey2-hello-world-example/

我已经发布了许多教程,以使用 RESTEasy 开发 REST api。 在本 Jersey2 教程中,我将详细介绍配置步骤,以设置 Jersey2 示例 Web 应用项目。

Table of Contents

1\. What changed from Jersey 1.x to Jersey2.x
2\. Jersey2 maven dependencies
3\. web.xml Changes
4\. Jersey rest api code

1. 从 Jersey 1.x 到 Jersey2.x 改变了什么

开发了 Jersey 1.x 的 Jersey 团队加入了新组织 GlassFish ,并且所有新的升级版本均从 2.x 开始发布。 它改变了框架功能的许多方面。 您可以在官方迁移指南中查看更改列表。

尽管他们在指南中涵盖了许多更改,但是您可能会面临许多其他更改,并且可能会很难解决这些问题。 记住。

2. Jersey2 Maven 依赖项

首先更改,您需要在 jersey 1.x 应用中创建 pom.xml。 依赖项发生了变化。 在 Jersey2.x 项目中使用以下依赖项。 我正在使用 Jersey2.19(最新日期)。

我的pom.xml文件如下所示。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.howtodoinjava.jersey</groupId>
	<artifactId>JerseyDemos</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<repositories>
		<repository>
			<id>maven2-repository.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/2/</url>
			<layout>default</layout>
		</repository>
	</repositories>
	<properties>
		<jersey2.version>2.19</jersey2.version>
		<jaxrs.version>2.0.1</jaxrs.version>
	</properties>
	<dependencies>
		<!-- JAX-RS -->
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>${jaxrs.version}</version>
		</dependency>
		<!-- Jersey2.19 -->
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-server</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>JerseyDemos</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

3. Jersey2 示例 – web.xml更改

您需要在web.xml文件中进行第二次更改。 通常,更改是将旧的包名称替换为新的包名称。

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

  <display-name>Archetype Created Web Application</display-name>

  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>jersey.config.server.provider.packages</param-name>
             <param-value>com.howtodoinjava.jersey</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

4. Jersey2 示例 – REST API 代码

REST 服务代码将基本相同。 如果发现任何问题,只需参考迁移指南或给我评论。

package com.howtodoinjava.jersey;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/message")
public class JerseyService
{
    @GET
    public String getMsg()
    {
         return "Hello World !! - Jersey2";
    }
}

当您在 tomcat 8 服务器中的 Jersey2 应用上方运行并点击 URL“http://localhost:8080/JerseyDemos/rest/message”时,会显示以下消息。

jersey-2 HelloWorld

jersey-2 HelloWorld

If you find java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer exception in application start up, then find the solution in linked post.源码下载

学习愉快!

参考:Jersey 2 用户指南

jersey-quickstart-webapp HelloWorld 示例

原文: https://howtodoinjava.com/jersey/jersey-quickstart-archetype-hello-world-application-example/

在此示例中,我们将使用 Eclipse 中的jersey-quickstart-webapp maven 原型创建一个 jersey RESTful API Web 应用。

Table of Contents

Install remote archetypes in eclipse
Create new maven project using jersey-quickstart-webapp
Generated Files
Run The Application

在 Eclipse 中安装远程原型

在创建实际的 Maven 快速入门应用之前,第一步是在 Eclipse 中安装快速入门定义。 这是非常简单的过程,我已经在上一教程中介绍了此信息。

阅读更多:如何在 Eclipse 中导入 Maven 远程原型目录

使用jersey-quickstart-webapp创建新的 Maven 项目

现在,我们创建一个新的 Maven 项目。

Create new maven project

创建新的 maven 项目

选择默认/其他工作区。

Select workspace location

选择工作区位置

选择jersey-quickstart-webapp版本。

Select jersey quick start version

选择jersey-quickstart-webapp版本

填写工件 ID 和组 ID。

Fill Artifact id and Group Id

填写工件 ID 和组 ID

点击“确定”以创建该项目。 项目将在工作区中创建。

生成的文件

让我们看一下生成的文件。

文件夹结构

Default Generated Files

默认生成的文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details https://jax-rs-spec.java.net/ -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://www.oracle.com/technetwork/java/index.html; version="2.5">
  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.howtodoinjava.demo</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/webapi/*</url-pattern>
  </servlet-mapping>
</web-app>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.howtodoinjava.demo</groupId>
    <artifactId>JerseyDemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>JerseyDemo</name>

    <build>
        <finalName>JerseyDemo</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <!-- uncomment this to get JSON support
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        -->
    </dependencies>
    <properties>
        <jersey.version>2.20</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

MyResource.java

package com.howtodoinjava.demo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * Root resource (exposed at "myresource" path)
 */
@Path("myresource")
public class MyResource {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return "Got it!";
    }
}

运行应用

为了打招呼,您无需在此项目中做任何事情。 一切都已配置。 只需部署应用。

匹配网址:http://localhost:8080/JerseyDemo/webapi/myresource

Application Output

应用输出

将我的问题放在评论部分。

祝您学习愉快!