原创转载请注明出处:http://agilestyle.iteye.com/blog/2323184
Project Diretory
Maven Dependency
<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>org.fool.jersey</groupId> <artifactId>jersey</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>jersey Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-server</artifactId> <version>2.23.2</version> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>2.23.2</version> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.23.2</version> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-client</artifactId> <version>2.23.2</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> </dependencies> <build> <finalName>jersey</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.3.11.v20160721</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <httpConnector> <port>8888</port> </httpConnector> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>jersey</display-name> <servlet> <servlet-name>jerseyservlet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>org.fool.jersey</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jerseyservlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
UserProfile.java
package org.fool.jersey.json; public class UserProfile { private boolean primary; private String firstName; private String lastName; private int age; private long secretCode; public boolean isPrimary() { return primary; } public void setPrimary(boolean primary) { this.primary = primary; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public long getSecretCode() { return secretCode; } public void setSecretCode(long secretCode) { this.secretCode = secretCode; } }
UserDetail.java
package org.fool.jersey.json; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class UserDetail { private int userId; private String userName; private String userEmail; private Date createDate; private Date updateDate; private UserProfile userProfile; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public UserProfile getUserProfile() { return userProfile; } public void setUserProfile(UserProfile userProfile) { this.userProfile = userProfile; } }
OperationStatus.java
package org.fool.jersey.json; public enum OperationStatus { SUCCESS, FAILURE, EXCEPTION }
AddUserException.java
package org.fool.jersey.json; public class AddUserException extends Exception { private static final long serialVersionUID = 1L; public AddUserException() { super(); } public AddUserException(String errMsg) { super(errMsg); } public AddUserException(String errMsg, Throwable t) { super(errMsg, t); } }
AddUserRequest.java
package org.fool.jersey.json; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class AddUserRequest { private String userName; private String userEmail; private String lastName; private String firstName; private int age; private long secretCode; private Date addDate; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public long getSecretCode() { return secretCode; } public void setSecretCode(long secretCode) { this.secretCode = secretCode; } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") public Date getAddDate() { return addDate; } public void setAddDate(Date addDate) { this.addDate = addDate; } }
AddUserResponse.java
package org.fool.jersey.json; public class AddUserResponse { private OperationStatus operationStatus; private int transactionId; private String userId; private String additionalInfo; public OperationStatus getOperationStatus() { return operationStatus; } public void setOperationStatus(OperationStatus operationStatus) { this.operationStatus = operationStatus; } public int getTransactionId() { return transactionId; } public void setTransactionId(int transactionId) { this.transactionId = transactionId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getAdditionalInfo() { return additionalInfo; } public void setAdditionalInfo(String additionalInfo) { this.additionalInfo = additionalInfo; } }
ErrorResponse.java
package org.fool.jersey.json; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class ErrorResponse { private String errorId; private String exceptionType; private String exceptionMsg; private Date occurrenceDatetime; public String getErrorId() { return errorId; } public void setErrorId(String errorId) { this.errorId = errorId; } public String getExceptionType() { return exceptionType; } public void setExceptionType(String exceptionType) { this.exceptionType = exceptionType; } public String getExceptionMsg() { return exceptionMsg; } public void setExceptionMsg(String exceptionMsg) { this.exceptionMsg = exceptionMsg; } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss") public Date getOccurrenceDatetime() { return occurrenceDatetime; } public void setOccurrenceDatetime(Date occurrenceDatetime) { this.occurrenceDatetime = occurrenceDatetime; } }
UserService.java
package org.fool.jersey.json; import java.text.SimpleDateFormat; import java.util.Date; import javax.ws.rs.Consumes; import javax.ws.rs.GET; 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; @Path("/api/json") public class UserService { @GET @Path("/userDetail") @Produces(MediaType.APPLICATION_JSON) public UserDetail getUserDetail() throws Exception { UserProfile up = new UserProfile(); up.setAge(30); up.setFirstName("Mr"); up.setLastName("Big"); up.setSecretCode(9876543210L); up.setPrimary(true); UserDetail ud = new UserDetail(); ud.setCreateDate(new Date()); ud.setUpdateDate(new Date()); ud.setUserEmail("test@test.org"); ud.setUserId(666); ud.setUserName("MrBig"); ud.setUserProfile(up); return ud; } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/addUser") @Produces(MediaType.APPLICATION_JSON) public AddUserResponse addUser(AddUserRequest request) { System.out.println(String.format("First Name: %s", request.getFirstName())); System.out.println(String.format("Last Name: %s", request.getLastName())); System.out.println(String.format("Email: %s", request.getUserEmail())); System.out.println(String.format("User Name: %s", request.getUserName())); System.out.println(String.format("User Age: %d", request.getAge())); System.out.println(String.format("Secret Code: %d", request.getSecretCode())); SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); System.out.println(String.format("Add Date: %s", formatter.format(request.getAddDate()))); System.out.println("-----------------------------"); AddUserResponse response = new AddUserResponse(); response.setAdditionalInfo("Operation completed successfully"); response.setOperationStatus(OperationStatus.SUCCESS); response.setTransactionId(576987); response.setUserId("666"); return response; } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("/addUser2") @Produces(MediaType.APPLICATION_JSON) public Response addUser2(AddUserRequest request) throws AddUserException { System.out.println(String.format("First Name: %s", request.getFirstName())); System.out.println(String.format("Last Name: %s", request.getLastName())); System.out.println(String.format("Email: %s", request.getUserEmail())); System.out.println(String.format("User Name: %s", request.getUserName())); System.out.println(String.format("User Age: %d", request.getAge())); System.out.println(String.format("Secret Code: %d", request.getSecretCode())); System.out.println("-----------------------------"); if (request.getSecretCode() == 111111L) { Exception exception = new AddUserException("Error created for User 111111"); ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setErrorId(String.valueOf(Response.Status.FORBIDDEN.getStatusCode())); errorResponse.setExceptionMsg(exception.getMessage()); errorResponse.setExceptionType(exception.getClass().getTypeName()); errorResponse.setOccurrenceDatetime(new Date()); return Response.status(Response.Status.FORBIDDEN).entity(errorResponse).build(); } AddUserResponse response = new AddUserResponse(); response.setAdditionalInfo("Operation completed successfully"); response.setOperationStatus(OperationStatus.SUCCESS); response.setTransactionId(576328); response.setUserId("7364364"); return Response.status(Response.Status.OK).entity(response).build(); } }
JsonClient.java
package org.fool.jersey.json; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.common.collect.Lists; public class JsonClient { public static void main(String[] args) { AddUserRequest exceptionRequest = new AddUserRequest(); AddUserRequest validRequest = new AddUserRequest(); exceptionRequest.setAge(32); exceptionRequest.setFirstName("Mr"); exceptionRequest.setLastName("Big"); exceptionRequest.setSecretCode(111111L); exceptionRequest.setUserEmail("test@test.org"); exceptionRequest.setUserName("MrBig"); exceptionRequest.setAddDate(new Date()); validRequest.setAge(30); validRequest.setFirstName("Mr"); validRequest.setLastName("Small"); validRequest.setSecretCode(111112L); validRequest.setUserEmail("test@test.org"); validRequest.setUserName("MrSmall"); validRequest.setAddDate(new Date()); Client client = ClientBuilder.newClient(); WebTarget webTarget = client.target("http://localhost:8888").path("/rest/api/json/addUser2"); Response exceptionResponse = webTarget.request(MediaType.APPLICATION_JSON).post(Entity.entity(exceptionRequest, MediaType.APPLICATION_JSON)); Response validResponse = webTarget.request(MediaType.APPLICATION_JSON).post(Entity.entity(validRequest, MediaType.APPLICATION_JSON)); List<Response> responseList = Lists.newArrayList(); responseList.add(exceptionResponse); responseList.add(validResponse); for (Response response : responseList) { if (response.getStatus() == 200) { AddUserResponse aur = response.readEntity(AddUserResponse.class); System.out.println(String.format("Additional Info: %s", aur.getAdditionalInfo())); System.out.println(String.format("Transaction id: %d", aur.getTransactionId())); System.out.println(String.format("User id: %s", aur.getUserId())); System.out.println(String.format("operation status: %s", aur.getOperationStatus().toString())); } else { ErrorResponse err = response.readEntity(ErrorResponse.class); System.out.println(String.format("Error Id: %s", err.getErrorId())); System.out.println(String.format("Error Message: %s", err.getExceptionMsg())); System.out.println(String.format("Error Type: %s", err.getExceptionType())); SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyy HH:mm:ss"); System.out.println(String.format("Occured Date: %s", formatter.format(err.getOccurrenceDatetime()))); } } } }
Test
这里我们先用Postman来测试第一和第二个方法
http://localhost:8888/rest/api/json/userDetail
http://localhost:8888/rest/api/json/addUser
最后一个我们用Jersey Client来测试第三个方法
参考资料:《RESTFul Web Service Development with Jersey 2.x》—— Han Bo Sun
相关推荐
赠送jar包:jackson-jaxrs-json-provider-2.7.8.jar; 赠送原API文档:jackson-jaxrs-json-provider-2.7.8-javadoc.jar; 赠送源代码:jackson-jaxrs-json-provider-2.7.8-sources.jar; 赠送Maven依赖信息文件:...
java运行依赖jar包
赠送jar包:jersey-json-1.9.jar; 赠送原API文档:jersey-json-1.9-javadoc.jar; 赠送源代码:jersey-json-1.9-sources.jar; 赠送Maven依赖信息文件:jersey-json-1.9.pom; 包含翻译后的API文档:jersey-json-...
3. **Jackson和JSON-P集成**: Jersey可以与流行的JSON库,如Jackson和JSON Processing (JSON-P) API进行集成,提供更灵活的JSON处理选项。例如,Jackson提供了高性能的JSON解析和生成,而JSON-P是Java EE平台的一...
赠送jar包:jersey-json-1.9.jar; 赠送原API文档:jersey-json-1.9-javadoc.jar; 赠送源代码:jersey-json-1.9-sources.jar; 赠送Maven依赖信息文件:jersey-json-1.9.pom; 包含翻译后的API文档:jersey-json-...
综上所述,"完整jersey包和jackson-all-1.9.2.jar"的组合意味着开发者可以利用Jersey构建RESTful服务,并利用Jackson高效地处理JSON数据。这种组合在开发基于Java的Web服务时非常常见,尤其是在需要与前端交互大量...
赠送jar包:jersey-json-1.19.jar; 赠送原API文档:jersey-json-1.19-javadoc.jar; 赠送源代码:jersey-json-1.19-sources.jar; 赠送Maven依赖信息文件:jersey-json-1.19.pom; 包含翻译后的API文档:jersey-...
maven-soapui-extension-plugin.zip,此插件为SmartBear SoapUI Pro Maven插件/SoapUI-Maven-Plugin添加了新功能和错误修复。此插件为SmartBear插件添加了新功能和错误修复:SoapUI Pro Maven插件和SoapUI Maven插件...
Java使用Jersey框架构建 RESTful Web服务返回json数据所需的jar包。Jackson-core-asl.jar / Jackson-jaxrs.jar / Jackson-mapper-asl.jar / Jackson-xc.jar / jersey-media-json-Jackson.jar
Jersey提供了一个名为`jersey-media-json-jackson`的模块,用于支持JSON序列化和反序列化。在项目中引入这个模块后,可以使用`@Produces`和`@Consumes`注解来指定资源方法能接收和返回的媒体类型。 5. **创建...
java运行依赖jar包
java运行依赖jar包
java运行依赖jar包
java运行依赖jar包
jsrsey实现Restful需要的jar包 jersey-json-1.3.jar
赠送jar包:jersey-json-1.19.jar; 赠送原API文档:jersey-json-1.19-javadoc.jar; 赠送源代码:jersey-json-1.19-sources.jar; 赠送Maven依赖信息文件:jersey-json-1.19.pom; 包含翻译后的API文档:jersey-...
jersey-json-1.9.jar
4. **jersey-media-json-jackson**:提供对JSON的支持,利用Jackson库进行序列化和反序列化。 5. **jersey-core**:基础组件,包含HTTP绑定、URI处理和异常处理等。 6. **jersey-guava**:与Google Guava库的集成,...
在`jersey-jackson-msgpack`项目中,Jackson被用来处理JSON数据,以便在客户端和服务端之间进行通信。 MsgPack(MessagePack)是一种轻量级的二进制序列化格式,它的目标是比JSON更快、更小。MsgPack通常用于需要...
该项目"GAE-Jersey-Jackson-Objectify"是一个基于Google App Engine(GAE)的演示应用,它结合了三个关键的技术栈:Jersey、Jackson和Objectify。这是一份详细的介绍,将深入探讨这些技术以及它们如何在Java环境中...