基本介绍

  • Jersey是JAX-RS的参考实现,它包含三个主要部分。

    • 核心服务器:通过JSR 311中标准化的注释和API标准化,可以直观方式开发Restful Web服务。

    • 核心客户端:Jersey客户端API帮助你与REST服务通信。

    • 继承:Jersey提供集成Spring、Guice、Apache Abdera的库。

前言

本文将学习如何使用Spring Boot和Jersey框架,去配置和创建JAX-RS 2.0 REST API接口;
这个示例应用使用的是Jersey的Servlet容器去部署REST API接口;

工程目录

本文例子中的工程代码结果如下:
【20181003】SpringBoot   Jersey - 图1

利用Spring Initializr工具创建Spring Boot应用Demo

1.访问Spring Initializr网站,添加Jersey (JAX-RS)依赖,点击生成代码;
【20181003】SpringBoot   Jersey - 图2
2.下载代码到本地,解压,导入代码到IDE中
3.检查下pom.xml代码里是否包含了spring-boot-starter-jersey依赖;

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-jersey</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-test</artifactId>
  9. <scope>test</scope>
  10. </dependency>
  11. </dependencies>

创建JAX-RS REST资源

现在,我们就可以开始创建JAX-RS REST资源了,创建完成后,可以进行测试;
先创建一个UserResource类,代码如下:
UserResource.java

  1. package com.howtodoinjava.jerseydemo;
  2. import java.net.URI;
  3. import java.net.URISyntaxException;
  4. import java.util.ArrayList;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import javax.ws.rs.Consumes;
  8. import javax.ws.rs.DELETE;
  9. import javax.ws.rs.GET;
  10. import javax.ws.rs.POST;
  11. import javax.ws.rs.PUT;
  12. import javax.ws.rs.Path;
  13. import javax.ws.rs.PathParam;
  14. import javax.ws.rs.Produces;
  15. import javax.ws.rs.core.Response;
  16. import javax.xml.bind.annotation.XmlAccessType;
  17. import javax.xml.bind.annotation.XmlAccessorType;
  18. import javax.xml.bind.annotation.XmlRootElement;
  19. @XmlAccessorType(XmlAccessType.NONE)
  20. @XmlRootElement(name = "users")
  21. @Path("/users")
  22. public class UserResource
  23. {
  24. private static Map<Integer, User> DB = new HashMap<>();
  25. @GET
  26. @Produces("application/json")
  27. public Users getAllUsers() {
  28. Users users = new Users();
  29. users.setUsers(new ArrayList<>(DB.values()));
  30. return users;
  31. }
  32. @POST
  33. @Consumes("application/json")
  34. public Response createUser(User user) throws URISyntaxException
  35. {
  36. if(user.getFirstName() == null || user.getLastName() == null) {
  37. return Response.status(400).entity("Please provide all mandatory inputs").build();
  38. }
  39. user.setId(DB.values().size()+1);
  40. user.setUri("/user-management/"+user.getId());
  41. DB.put(user.getId(), user);
  42. return Response.status(201).contentLocation(new URI(user.getUri())).build();
  43. }
  44. @GET
  45. @Path("/{id}")
  46. @Produces("application/json")
  47. public Response getUserById(@PathParam("id") int id) throws URISyntaxException
  48. {
  49. User user = DB.get(id);
  50. if(user == null) {
  51. return Response.status(404).build();
  52. }
  53. return Response
  54. .status(200)
  55. .entity(user)
  56. .contentLocation(new URI("/user-management/"+id)).build();
  57. }
  58. @PUT
  59. @Path("/{id}")
  60. @Consumes("application/json")
  61. @Produces("application/json")
  62. public Response updateUser(@PathParam("id") int id, User user) throws URISyntaxException
  63. {
  64. User temp = DB.get(id);
  65. if(user == null) {
  66. return Response.status(404).build();
  67. }
  68. temp.setFirstName(user.getFirstName());
  69. temp.setLastName(user.getLastName());
  70. DB.put(temp.getId(), temp);
  71. return Response.status(200).entity(temp).build();
  72. }
  73. @DELETE
  74. @Path("/{id}")
  75. public Response deleteUser(@PathParam("id") int id) throws URISyntaxException {
  76. User user = DB.get(id);
  77. if(user != null) {
  78. DB.remove(user.getId());
  79. return Response.status(200).build();
  80. }
  81. return Response.status(404).build();
  82. }
  83. static
  84. {
  85. User user1 = new User();
  86. user1.setId(1);
  87. user1.setFirstName("John");
  88. user1.setLastName("Wick");
  89. user1.setUri("/user-management/1");
  90. User user2 = new User();
  91. user2.setId(2);
  92. user2.setFirstName("Harry");
  93. user2.setLastName("Potter");
  94. user2.setUri("/user-management/2");
  95. DB.put(user1.getId(), user1);
  96. DB.put(user2.getId(), user2);
  97. }
  98. }

Users.java

  1. package com.howtodoinjava.jerseydemo;
  2. import java.util.ArrayList;
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5. import javax.xml.bind.annotation.XmlElement;
  6. import javax.xml.bind.annotation.XmlRootElement;
  7. @XmlAccessorType(XmlAccessType.NONE)
  8. @XmlRootElement(name = "users")
  9. public class Users {
  10. @XmlElement(name="user")
  11. private ArrayList<User> users;
  12. public ArrayList<User> getUsers() {
  13. return users;
  14. }
  15. public void setUsers(ArrayList<User> users) {
  16. this.users = users;
  17. }
  18. }

User.java

  1. package com.howtodoinjava.jerseydemo;
  2. import java.io.Serializable;
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5. import javax.xml.bind.annotation.XmlAttribute;
  6. import javax.xml.bind.annotation.XmlElement;
  7. import javax.xml.bind.annotation.XmlRootElement;
  8. @XmlAccessorType(XmlAccessType.NONE)
  9. @XmlRootElement(name = "user")
  10. public class User implements Serializable {
  11. private static final long serialVersionUID = 1L;
  12. @XmlAttribute(name = "id")
  13. private int id;
  14. @XmlAttribute(name="uri")
  15. private String uri;
  16. @XmlElement(name = "firstName")
  17. private String firstName;
  18. @XmlElement(name = "lastName")
  19. private String lastName;
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26. public String getFirstName() {
  27. return firstName;
  28. }
  29. public void setFirstName(String firstName) {
  30. this.firstName = firstName;
  31. }
  32. public String getLastName() {
  33. return lastName;
  34. }
  35. public void setLastName(String lastName) {
  36. this.lastName = lastName;
  37. }
  38. public String getUri() {
  39. return uri;
  40. }
  41. public void setUri(String uri) {
  42. this.uri = uri;
  43. }
  44. }

配置Jersey

到目前为止,我们已经创建了一个JAX-RS资源,现在我们想通过spring boot应用去访问它,步骤如下;
1.首先我们要注册改资源为Jersey资源,代码如下:

  1. package com.howtodoinjava.jerseydemo;
  2. import org.glassfish.jersey.server.ResourceConfig;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class JerseyConfig extends ResourceConfig
  6. {
  7. public JerseyConfig()
  8. {
  9. register(UserResource.class);
  10. }
  11. }

注意需要加上 @Component注解,以便Spring Boot能够扫描到;
2.其次JerseyConfig需要继承ResourceConfig,该类提供了很多高级功能,简化了JAX-RS组件的注册工作;
3.最后Spring Boot Application启动类需要继承SpringBootServletInitializer

  1. package com.howtodoinjava.jerseydemo;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.boot.builder.SpringApplicationBuilder;
  4. import org.springframework.boot.web.support.SpringBootServletInitializer;
  5. @SpringBootApplication
  6. public class JerseydemoApplication extends SpringBootServletInitializer
  7. {
  8. public static void main(String[] args)
  9. {
  10. new JerseydemoApplication().configure(new SpringApplicationBuilder(JerseydemoApplication.class)).run(args);
  11. }
  12. }

演示

启动Spring Boot应用,访问user 资源
【20181003】SpringBoot   Jersey - 图3
访问/users/1资源
【20181003】SpringBoot   Jersey - 图4