搜索词>>Jersey 耗时0.0150
  • spring boot整合Jersey2.x实现JAX-RS webservice

    spring boot整合Jersey2.x实现JAX-RS webservicespring boot整合Jersey2.x实现JAX-RS webservice<br /> <br /> jersey常用注解解释: <table class="table table-bordered table-hover"> <tbody> <tr> <td>Annotation</td> <td>作用</td> <td>说明</td> </tr> <tr> <td>@GET</td> <td>查询请求</td> <td>相当于数据库的查询数据操作</td> </tr> <tr> <td>@POST</td> <td>插入请求</td> <td>相当于数据库的插入数据操作</td> </tr> <tr> <td>@PUT</td> <td>更新请求</td> <td>相当于数据库的更新数据操作</td> </tr> <tr> <td>@DELETE</td> <td>删除请求</td> <td>相当于数据的删除数据操作</td> </tr> <tr> <td>@Path</td> <td>uri路径</td> <td>定义资源的访问路径,client通过这个路径访问资源。比如:@Path("user")</td> </tr> <tr> <td>@Produces</td> <td>指定返回MIME格式</td> <td>资源按照那种数据格式返回,可取的值有:MediaType.APPLICATION_XXX。比如:@Produces(MediaType.APPLICATION_XML)</td> </tr> <tr> <td>@Consumes</td> <td>接受指定的MIME格式</td> <td>只有符合这个参数设置的请求再能访问到这个资源。比如@Consumes("application/x-www-form-urlencoded")</td> </tr> <tr> <td>@PathParam</td> <td>uri路径参数</td> <td>写在方法的参数中,获得请求路径参数。比如:@PathParam("username") String userName</td> </tr> <tr> <td>@QueryParam</td> <td>uri路径请求参数</td> <td>写在方法的参数中,获得请求路径附带的参数。比如:@QueryParam("desc") String desc</td> </tr> <tr> <td>@DefaultValue</td> <td>设置@QueryParam参数的默认值</td> <td>如果@QueryParam没有接收到值,就使用默认值。比如:@DefaultValue("description") @QueryParam("desc") String desc</td> </tr> <tr> <td>@FormParam</td> <td>form传递的参数</td> <td>接受form传递过来的参数。比如:@FormParam("name") String userName</td> </tr> <tr> <td>@BeanParam</td> <td>通过Bena的形式传递参数</td> <td>接受client传递的bean类型的参数,同时这个bean可以在属性上配置@FormParam用以解决client的属性名称和bean的属性名称不一致的问题。比如:@BeanParam User user</td> </tr> <tr> <td>@Context</td> <td>获得一些系统环境信息</td> <td>通过@Context可以获得以下信息:UriInfo、ServletConfig、ServletContext、HttpServletRequest、HttpServletResponse和HttpHeaders等</td> </tr> <tr> <td>@XmlRootElement</td> <td>将bean转换为xml</td> <td>如果要讲bean以xml或json的格式返回,必须要这个注解。比如:<br /> @XmlRootElement<br /> public class User{...}</td> </tr> </tbody> </table> <br /> 项目文件清单<br /> pom.xml <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <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.leftso</groupId> <artifactId>demo-webservice-jersey</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo-webservice-jersey</name> <description>demo-webservice-jersey</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> </code></pre> <br /> JerseyResourceConfig.java <pre> <code class="language-java">package com.leftso.config; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.spring.scope.RequestContextFilter; /** * 继承ResourceConfig,并添加一些配置信息 * * @author leftso * */ public class JerseyResourceConfig extends ResourceConfig { public JerseyResourceConfig() { register(RequestContextFilter.class); // 配置那个包下面的会被Jersey扫描 packages("com.leftso.rest"); } } </code></pre> <br /> JerseyConfig.java <pre> <code class="language-java">package com.leftso.config; import org.glassfish.jersey.servlet.ServletContainer; import org.glassfish.jersey.servlet.ServletProperties; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 配置Jersey * * @author leftso * */ @Configuration public class JerseyConfig { @Bean public ServletRegistrationBean jerseyServlet() { ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/rest/*"); // our rest resources will be available in the path /rest/* registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyResourceConfig.class.getName()); return registration; } } </code></pre> <br /> RestResource.java(测试资源类) <pre> <code class="language-java">package com.leftso.rest; import java.util.HashMap; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/") public class RestResource { @Path("/hello") // 具体路径 @GET // 请求方式 @Produces(MediaType.APPLICATION_JSON) // 返回的格式 // @Consumes()//接受指定的MIME格式 public Map<String, Object> hello() { Map<String, Object> map = new HashMap<String, Object>(); map.put("code", "1"); map.put("codeMsg", "success"); return map; } } </code></pre> <br /> Application.java <pre> <code class="language-java">package com.leftso; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } </code></pre> <br /> 启动项目,访问地址:http://127.0.0.1:8080/rest/hello<br /> <br /> 显示内容: <pre> <code>{"code":"1","codeMsg":"success"}</code></pre> <br /> 项目下载:<br /> GITHUB:<a href="https://github.com/leftso/demo-webservice-jersey" rel="external nofollow" target="_blank">https://github.com/leftso/demo-webservice-jersey</a><br />  
  • spring boot Jersey基于角色的安全控制使用JAX-RS的注解

    Spring Boot 基于角色的安全控制使用JAX-RS的注解,spring boot,Jersey<h2>一、摘要说明</h2>     学习使用spring boot和Jersey框架来创建JAX-RS 2.0 REST APIs,并且使用JAX-RS注解来添加基于角色的安全控制。例如注解<code>@PermitAll</code>, <code>@RolesAllowed</code> 或者 <code>@DenyAll。</code><br />    <br />     本博客学习纲要: <ul> <li>项目结构    </li> <li>创建REST api</li> <li>使用jax-rs注释的安全REST api</li> <li>使用jax-rs容器请求过滤器编写安全过滤器</li> <li>一个例子演示</li> </ul> <h2>二、项目结构</h2> 本教程中创建的应用程序的项目结构如下:<br /> <img alt="项目结构" class="img-thumbnail" src="/resources/assist/images/blog/1d2312c3dc4d48f79fb04f5094b9a000.png" /> <h2>三、创建 REST APIs</h2> 1.去 Spring Initializr网站,创建一个spring boot项目并且添加 Jersey (JAX-RS) 依赖<br /> <img alt="创建项目" class="img-thumbnail" src="/resources/assist/images/blog/27643e1e52c3445ca3c603d6184b69bb.png" />2.导入项目到eclipse中<br /> 以zip文件的格式生成项目。在你电脑的某个地方把它取出来。将该项目作为“Existing maven application”导入eclipse。<br /> <br /> 3.检查maven的依赖<br /> 检查maven的依赖文件中必须有<strong>spring-boot-starter-jersey</strong> <pre> <code class="language-xml"><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies></code></pre> 4.创建 REST APIs<br /> 现在创建一些jax-rs资源,我们将访问测试阶段。我已经创建了UserResource类。<br /> <br /> <strong>UserResource.java</strong> <pre> <code class="language-java"> import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "users") @Path("/users") public class UserResource { private static Map<Integer, User> DB = new HashMap<>(); @GET @Produces("application/json") public Users getAllUsers() { Users users = new Users(); users.setUsers(new ArrayList<>(DB.values())); return users; } @POST @Consumes("application/json") public Response createUser(User user) throws URISyntaxException { if(user.getFirstName() == null || user.getLastName() == null) { return Response.status(400).entity("Please provide all mandatory inputs").build(); } user.setId(DB.values().size()+1); user.setUri("/user-management/"+user.getId()); DB.put(user.getId(), user); return Response.status(201).contentLocation(new URI(user.getUri())).build(); } @GET @Path("/{id}") @Produces("application/json") public Response getUserById(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user == null) { return Response.status(404).build(); } return Response .status(200) .entity(user) .contentLocation(new URI("/user-management/"+id)).build(); } @PUT @Path("/{id}") @Consumes("application/json") @Produces("application/json") public Response updateUser(@PathParam("id") int id, User user) throws URISyntaxException { User temp = DB.get(id); if(user == null) { return Response.status(404).build(); } temp.setFirstName(user.getFirstName()); temp.setLastName(user.getLastName()); DB.put(temp.getId(), temp); return Response.status(200).entity(temp).build(); } @DELETE @Path("/{id}") public Response deleteUser(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user != null) { DB.remove(user.getId()); return Response.status(200).build(); } return Response.status(404).build(); } static { User user1 = new User(); user1.setId(1); user1.setFirstName("John"); user1.setLastName("Wick"); user1.setUri("/user-management/1"); User user2 = new User(); user2.setId(2); user2.setFirstName("Harry"); user2.setLastName("Potter"); user2.setUri("/user-management/2"); DB.put(user1.getId(), user1); DB.put(user2.getId(), user2); } }</code></pre> <strong>Users.java</strong> <pre> <code class="language-java"> import java.util.ArrayList; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "users") public class Users { @XmlElement(name="user") private ArrayList<User> users; public ArrayList<User> getUsers() { return users; } public void setUsers(ArrayList<User> users) { this.users = users; } }</code></pre> <strong>User.java</strong> <pre> <code class="language-java"> 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; @XmlAttribute(name="uri") private String uri; @XmlElement(name = "firstName") private String firstName; @XmlElement(name = "lastName") private String lastName; // Getters and Setters }</code></pre> 5.配置Jersey<br /> 现在我们有了一个jax-rs资源,我们希望从spring启动应用程序中访问它,其中包括Jersey依赖项。让我们将这个资源注册为泽西资源。 <pre> <code class="language-java">import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; @Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(SecurityFilter.class); register(UserResource.class); } }</code></pre>   <ul> <li>查看@component注释。它使这个类可以注册,而spring引导自动扫描源文件夹中的java类。</li> <li>资源econfig提供了简化jax-rs组件注册的高级功能。</li> <li>SecurityFilter类是实际的auth细节处理器,我们将在本教程后面看到。</li> </ul> <br /> 使用SpringBootServletInitializer扩展spring应用程序 <pre> <code class="language-java">import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class JerseydemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { new JerseydemoApplication().configure(new SpringApplicationBuilder(JerseydemoApplication.class)).run(args); } }</code></pre> <h2>四、使用JAX-RS Annotations创建安全的REST APIs</h2> 现在,当我们的api准备好时,我们将开始保护它们。让我们使用jax-rs注释对api进行注释,基于它们所需的访问级别和允许访问它们的用户角色。 <pre> <code class="language-java">@XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "users") @Path("/users") public class UserResource { private static Map<Integer, User> DB = new HashMap<>(); @GET @PermitAll @Produces("application/json") public Users getAllUsers() { Users users = new Users(); users.setUsers(new ArrayList<>(DB.values())); return users; } @POST @Consumes("application/json") @RolesAllowed("ADMIN") public Response createUser(User user) throws URISyntaxException { if(user.getFirstName() == null || user.getLastName() == null) { return Response.status(400).entity("Please provide all mandatory inputs").build(); } user.setId(DB.values().size()+1); user.setUri("/user-management/"+user.getId()); DB.put(user.getId(), user); return Response.status(201).contentLocation(new URI(user.getUri())).build(); } @GET @Path("/{id}") @Produces("application/json") @PermitAll public Response getUserById(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user == null) { return Response.status(404).build(); } return Response .status(200) .entity(user) .contentLocation(new URI("/user-management/"+id)).build(); } @PUT @Path("/{id}") @Consumes("application/json") @Produces("application/json") @RolesAllowed("ADMIN") public Response updateUser(@PathParam("id") int id, User user) throws URISyntaxException { User temp = DB.get(id); if(user == null) { return Response.status(404).build(); } temp.setFirstName(user.getFirstName()); temp.setLastName(user.getLastName()); DB.put(temp.getId(), temp); return Response.status(200).entity(temp).build(); } @DELETE @Path("/{id}") @RolesAllowed("ADMIN") public Response deleteUser(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user != null) { DB.remove(user.getId()); return Response.status(200).build(); } return Response.status(404).build(); } static { User user1 = new User(); user1.setId(1); user1.setFirstName("John"); user1.setLastName("Wick"); user1.setUri("/user-management/1"); User user2 = new User(); user2.setId(2); user2.setFirstName("Harry"); user2.setLastName("Potter"); user2.setUri("/user-management/2"); DB.put(user1.getId(), user1); DB.put(user2.getId(), user2); } }</code></pre> 你可以看到注解 角色注解@RolesAllowed <h2>五、使用JAX-RS ContainerRequestFilter来编写security filter</h2>   现在是编写我们的安全过滤器的时候了,它将检查传入的请求,获取授权信息(在本例中是基本身份验证),然后将匹配用户名和密码,最后它将通过它的角色来验证用户的访问级别。如果一切都匹配,API将被访问,否则用户将获得访问被拒绝的响应。 <pre> <code class="language-java">import java.lang.reflect.Method; import java.util.Arrays; import java.util.Base64; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import javax.annotation.security.DenyAll; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ResourceInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; /** * This filter verify the access permissions for a user based on * user name and password provided in request * */ @Provider public class SecurityFilter implements javax.ws.rs.container.ContainerRequestFilter { private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String AUTHENTICATION_SCHEME = "Basic"; private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED).build(); private static final Response ACCESS_FORBIDDEN = Response.status(Response.Status.FORBIDDEN).build(); private static final Response SERVER_ERROR = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); @Context private ResourceInfo resourceInfo; @Override public void filter(ContainerRequestContext requestContext) { Method method = resourceInfo.getResourceMethod(); //Access allowed for all if( ! method.isAnnotationPresent(PermitAll.class)) { //Access denied for all if(method.isAnnotationPresent(DenyAll.class)) { requestContext.abortWith(ACCESS_FORBIDDEN); return; } //Get request headers final MultivaluedMap<String, String> headers = requestContext.getHeaders(); //Fetch authorization header final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY); //If no authorization information present; block access if(authorization == null || authorization.isEmpty()) { requestContext.abortWith(ACCESS_DENIED); return; } //Get encoded username and password final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", ""); //Decode username and password String usernameAndPassword = null; try { usernameAndPassword = new String(Base64.getDecoder().decode(encodedUserPassword)); } catch (Exception e) { requestContext.abortWith(SERVER_ERROR); return; } //Split username and password tokens final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); //Verifying Username and password if(!(username.equalsIgnoreCase("admin") && password.equalsIgnoreCase("password"))){ requestContext.abortWith(ACCESS_DENIED); return; } //Verify user access if(method.isAnnotationPresent(RolesAllowed.class)) { RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class); Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value())); //Is user valid? if( ! isUserAllowed(username, password, rolesSet)) { requestContext.abortWith(ACCESS_DENIED); return; } } } } private boolean isUserAllowed(final String username, final String password, final Set<String> rolesSet) { boolean isAllowed = false; //Step 1. Fetch password from database and match with password in argument //If both match then get the defined role for user from database and continue; else return isAllowed [false] //Access the database and do this part yourself //String userRole = userMgr.getUserRole(username); String userRole = "ADMIN"; //Step 2. Verify user role if(rolesSet.contains(userRole)) { isAllowed = true; } return isAllowed; } }</code></pre>   <h2>六、例子演示</h2> 运行这个项目作为Spring引导应用程序。现在测试rest资源。<br /> <strong>访问 GET /users resource<br /> <img alt="例子演示" class="img-thumbnail" src="/resources/assist/images/blog/9d1d46f7425a422b9cb44730e13285fd.png" /><br /> 使用POST方式并且没有认证信息去访问/users 资源接口</strong><br /> 可以看到返回的状态 status code 401.<br /> <img alt="401" class="img-thumbnail" src="/resources/assist/images/blog/90e9626483b4473fa79578ab2fa6b1e6.png" /><br /> <strong>使用POST方式并且添加认证信息去访问/users 资源接口</strong><br /> 使用<a href="http://www.leftso.com/tools/url.html" rel="external nofollow" target="_blank">此链接</a>生成base64编码的用户名和密码组合,以传递到授权头。<br /> <img alt="成功访问user" class="img-thumbnail" src="/resources/assist/images/blog/5cf84a5bba9c4178be76a13e5e2e7716.png" /><br />  
  • Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ

    Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ<h2>一.项目结构<br /> 本教程创建的应用程序结构如下:</h2> <strong><img alt="Spring-Boot-Jersey-Project-Structure" class="img-thumbnail" src="/resources/assist/images/blog/034cb03ceabf43fea761e136b7e97a9b.png" /></strong> <h2>二.从Spring Initializr创建Spring boot应用程序</h2> <strong>1.访问Spring Initializr网站,并通过 Jersey (JAX-RS)依赖创建spring boot项目</strong><br /> <img alt="创建spring boot项目" class="img-thumbnail" src="/resources/assist/images/blog/9eee2ca48f664f0e8949e824feb21a90.png" /><br /> <strong>2.创建zip文件的项目。解压到自己电脑的某个地方。通过eclipse中的导入maven 已经存在的项目导入该项目</strong><br /> <strong>3.检查项目的maven依赖文件,看是否有加入spring-boot-starter-jersey的依赖。</strong> <pre> <code class="language-xml"><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies></code></pre> <h2>四.创建JAX-RS REST资源文件</h2> 现在创建一些JAX-RS资源用来做测试。我这里创建了一个UserResource class.<br /> <strong>UserResource.java:</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "users") @Path("/users") public class UserResource { private static Map<Integer, User> DB = new HashMap<>(); @GET @Produces("application/json") public Users getAllUsers() { Users users = new Users(); users.setUsers(new ArrayList<>(DB.values())); return users; } @POST @Consumes("application/json") public Response createUser(User user) throws URISyntaxException { if(user.getFirstName() == null || user.getLastName() == null) { return Response.status(400).entity("Please provide all mandatory inputs").build(); } user.setId(DB.values().size()+1); user.setUri("/user-management/"+user.getId()); DB.put(user.getId(), user); return Response.status(201).contentLocation(new URI(user.getUri())).build(); } @GET @Path("/{id}") @Produces("application/json") public Response getUserById(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user == null) { return Response.status(404).build(); } return Response .status(200) .entity(user) .contentLocation(new URI("/user-management/"+id)).build(); } @PUT @Path("/{id}") @Consumes("application/json") @Produces("application/json") public Response updateUser(@PathParam("id") int id, User user) throws URISyntaxException { User temp = DB.get(id); if(user == null) { return Response.status(404).build(); } temp.setFirstName(user.getFirstName()); temp.setLastName(user.getLastName()); DB.put(temp.getId(), temp); return Response.status(200).entity(temp).build(); } @DELETE @Path("/{id}") public Response deleteUser(@PathParam("id") int id) throws URISyntaxException { User user = DB.get(id); if(user != null) { DB.remove(user.getId()); return Response.status(200).build(); } return Response.status(404).build(); } static { User user1 = new User(); user1.setId(1); user1.setFirstName("John"); user1.setLastName("Wick"); user1.setUri("/user-management/1"); User user2 = new User(); user2.setId(2); user2.setFirstName("Harry"); user2.setLastName("Potter"); user2.setUri("/user-management/2"); DB.put(user1.getId(), user1); DB.put(user2.getId(), user2); } }</code></pre> <strong>Users.java</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import java.util.ArrayList; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.NONE) @XmlRootElement(name = "users") public class Users { @XmlElement(name="user") private ArrayList<User> users; public ArrayList<User> getUsers() { return users; } public void setUsers(ArrayList<User> users) { this.users = users; } }</code></pre> <strong>User.java</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; 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; @XmlAttribute(name="uri") private String uri; @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; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } }</code></pre> <h2>五.Jersey配置</h2> <br /> <strong>1.现在我们有一个jax - rs资源,我们想从spring boot应用程序中访问它,其中包括Jersey依赖。让我们将此资源注册为Jersey资源。</strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; @Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(UserResource.class); } }</code></pre> 查看@ component注释。它允许在spring引导自动扫描源文件夹中的java类时注册这个类。<br /> <br /> <strong>2.ResourceConfig提供了简化jax - rs组件注册的高级功能。</strong><br /> <br /> <strong>3.通过<code>SpringBootServletInitializer扩展spring boot项目</code></strong> <pre> <code class="language-java">package com.howtodoinjava.jerseydemo; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class JerseydemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { new JerseydemoApplication().configure(new SpringApplicationBuilder(JerseydemoApplication.class)).run(args); } }</code></pre> <h2>六.demo</h2> 启动spring boot项目,并测试资源<br /> <strong>Access /users resource<br /> <img alt="Access /users resource" class="img-thumbnail" src="/resources/assist/images/blog/fdc261ca174b41cf88e9884c46db3762.png" /><br /> Access /users/1 resource<br /> <img alt="Access /users/1 resource" class="img-thumbnail" src="/resources/assist/images/blog/0fb858b938bf41129a695db1e9d85a68.png" /></strong><br />