Jersey GET POST PUT DELETE
原创转载请注明出处:http://agilestyle.iteye.com/blog/2322905
Project Directory
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>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.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.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>
JsonUtils.java
package org.fool.jersey.util;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static <K, V> Map<K, V> jsonToMap(String jsonData, Class<K> keyType, Class<V> valueType) {
JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, keyType, valueType);
try {
Map<K, V> map = MAPPER.readValue(jsonData, javaType);
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
ActionResponse.java
package org.fool.jersey.blog;
/*
* to demonstrate the DELETE method
*/
public class ActionResponse {
private String actionStatus;
private String additionalMessage;
public String getActionStatus() {
return actionStatus;
}
public void setActionStatus(String actionStatus) {
this.actionStatus = actionStatus;
}
public String getAdditionalMessage() {
return additionalMessage;
}
public void setAdditionalMessage(String additionalMessage) {
this.additionalMessage = additionalMessage;
}
}
BlogPostRequest.java
package org.fool.jersey.blog;
/*
* to demonstrate the POST and PUT method
*/
public class BlogPostRequest {
private String postTitle;
private String postContent;
private String author;
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostContent() {
return postContent;
}
public void setPostContent(String postContent) {
this.postContent = postContent;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
BlogPostResponse.java
package org.fool.jersey.blog;
import java.util.List;
import com.google.common.collect.Lists;
/*
* to demonstrate the GET method
*/
public class BlogPostResponse {
private String postName;
private String postTitle;
private String postContent;
private String author;
private String dateValue;
private String blogCategory;
private List<String> blogKeywords;
public BlogPostResponse() {
blogKeywords = Lists.newArrayList();
}
public String getPostName() {
return postName;
}
public void setPostName(String postName) {
this.postName = postName;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostContent() {
return postContent;
}
public void setPostContent(String postContent) {
this.postContent = postContent;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDateValue() {
return dateValue;
}
public void setDateValue(String dateValue) {
this.dateValue = dateValue;
}
public String getBlogCategory() {
return blogCategory;
}
public void setBlogCategory(String blogCategory) {
this.blogCategory = blogCategory;
}
public List<String> getBlogKeywords() {
return blogKeywords;
}
public void setBlogKeywords(List<String> blogKeywords) {
this.blogKeywords = blogKeywords;
}
}
BlogService.java
package org.fool.jersey.blog;
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 org.fool.jersey.util.JsonUtils;
@Path("/blog")
public class BlogService {
@Path("/{year}/{month}/{day}/{postName}")
@GET
public String getBlogDetail(
@PathParam("year") int year,
@PathParam("month") int month,
@PathParam("day") int day,
@PathParam("postName") String postName) {
BlogPostResponse bpr = new BlogPostResponse();
bpr.setPostName(postName);
bpr.setAuthor("Mr Big");
bpr.setBlogCategory("My Favorite");
bpr.setDateValue(String.format("%d/%d/%d", month, day, year));
bpr.setPostContent("Jesey, so fucking awesome, why do you still use spring mvc?");
bpr.setPostTitle("My very first blog post. Hello world!");
bpr.getBlogKeywords().add("hello");
bpr.getBlogKeywords().add("world");
bpr.getBlogKeywords().add("first post");
bpr.getBlogKeywords().add("awesome");
String result = JsonUtils.objectToJson(bpr);
return result;
}
@Path("/{year}/{month}/{day}/{postName}")
@DELETE
public String deleteBlogPost(
@PathParam("year") int year,
@PathParam("month") int month,
@PathParam("day") int day,
@PathParam("postName") String postName) {
ActionResponse ar = new ActionResponse();
ar.setActionStatus("Successfully");
ar.setAdditionalMessage(String.format("Blog post [%s] created on [%d/%d/%d] was deleted. Operation is successful.", postName, month, day, year));
String result = JsonUtils.objectToJson(ar);
return result;
}
@Path("/{year}/{month}/{day}/{postName}")
@POST
@Consumes("text/plain")
public String createNewBlogPost(
@PathParam("year") int year,
@PathParam("month") int month,
@PathParam("day") int day,
@PathParam("postName") String postName,
String requestBody) {
BlogPostRequest request = JsonUtils.jsonToPojo(requestBody, BlogPostRequest.class);
System.out.println(request.getAuthor());
System.out.println(request.getPostTitle());
System.out.println(request.getPostContent());
BlogPostResponse response = new BlogPostResponse();
response.setAuthor(request.getAuthor());
response.setBlogCategory("[no category]");
response.setDateValue(String.format("%d/%d/%d", month, day, year));
response.setPostContent(request.getPostContent());
response.setPostName(postName);
response.setPostTitle(request.getPostTitle());
String result = JsonUtils.objectToJson(response);
return result;
}
@Path("/{year}/{month}/{day}/{postName}")
@PUT
@Consumes("text/plain")
public String updateBlogPost(@PathParam("year") int year,
@PathParam("month") int month,
@PathParam("day") int day,
@PathParam("postName") String postName,
String requestBody) {
BlogPostRequest request = JsonUtils.jsonToPojo(requestBody, BlogPostRequest.class);
System.out.println(request.getAuthor());
System.out.println(request.getPostTitle());
System.out.println(request.getPostContent());
ActionResponse response = new ActionResponse();
response.setActionStatus("Successful");
response.setAdditionalMessage(String.format("Blog post [%s] created on [%d/%d/%d] was updated. Operation is successful.", postName, month, day, year));
String result = JsonUtils.objectToJson(response);
return result;
}
}
Test
GET
DELETE
POST
PUT
参考资料:《RESTFul Web Service Development with Jersey 2.x》—— Han Bo Sun