使用HTTP PUT创建在同一Tomcat上运行的新缓存(ehCache)



我正在尝试发送一个HTTP PUT(以便创建一个新的缓存并用我生成的JSON填充它)使用我的Web服务访问ehCache,该Web服务位于同一本地tomcat实例上。

我是RESTfulWeb服务的新手,使用JDK1.6、Tomcat7、ehCache和JSON。

我的POJO定义如下:

个人POJO:

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String firstName;
private String lastName;
private List<House> houses;
// Getters & Setters
}

House POJO:

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class House {
private String address;
private String city;
private String state;
// Getters & Setters
}

使用PersonUtil类,我对POJO进行了如下硬编码:

public class PersonUtil {
public static Person getPerson() {
Person person = new Person();
person.setFirstName("John");
person.setLastName("Doe");
List<House> houses = new ArrayList<House>();
House house = new House();
house.setAddress("1234 Elm Street");
house.setCity("Anytown");
house.setState("Maine");
houses.add(house);
person.setHouses(houses);
return person;
}
}

我能够根据GET请求创建JSON响应:

@Path("")
public class MyWebService{
@GET
@Produces(MediaType.APPLICATION_JSON) 
public Person getPerson() {
return PersonUtil.getPerson();
}
}

将war部署到tomcat并将浏览器指向时

http://localhost:8080/personservice/

生成的JSON:

{ 
"firstName" : "John", 
"lastName" : "Doe",
"houses": 
[ 
{ 
"address" : "1234 Elmstreet",
"city"    : "Anytown",
"state"   : "Maine"
}
]
}

然而,到目前为止,一切都很好,我有一个不同的应用程序,它运行在同一个tomcat实例上(并支持REST):

http://localhost:8080/ehcache/rest/

当tomcat运行时,我可以发出这样的PUT:

echo "Hello World" |  curl -S -T -  http://localhost:8080/ehcache/rest/hello/1

当我"得到"它像这样:

curl http://localhost:8080/ehcache/rest/hello/1

将产生:

Hello World

我需要做的是创建一个POST,它将放入我的整个Person生成的JSON并创建一个新的缓存:

http://localhost:8080/ehcache/rest/person

当我在以前的URL上做"GET"时,它应该是这样的:

{ 
"firstName" : "John", 
"lastName" : "Doe",
"houses": 
[ 
{ 
"address" : "1234 Elmstreet",
"city"    : "Anytown",
"state"   : "Maine"
}
]
}

到目前为止,这就是我的PUT的样子:

@PUT
@Path("/ehcache/rest/person")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) 
public Response createCache() {
ResponseBuilder response = Response.ok(PersonUtil.getPerson(), MediaType.APPLICATION_JSON);
return response.build();
}

问题:

  1. 这是写PUT的正确方法吗
  2. 我应该在createCache()方法内部写些什么,让它将我生成的JSON放入http://localhost:8080/ehcache/rest/person
  3. 使用PUT时,命令行CURL注释会是什么样子

我希望PUT处理程序将Person作为参数,这样它就可以找到传递给它的内容。这就是JAX-RS方法。我还希望不必返回Response,因为我们只是用一个简单的值做一个200 OK的响应。

@PUT
@Path("/ehcache/rest/person")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) 
public Person createCache(Person who) {
// Stuff in here to store the person, filling out with whatever
// needs to be added...
return who;
}

当然,通常情况下,我还希望从路径中提取一个参数,以指示哪个人员正在被更新,也许还有一个@Context UriInfo uriInfo参数,以允许更详细地访问有关如何调用该方法的信息(包括合成相关URL的能力)。但这是技巧。

如果你正在寻找使用PUT的有效方法,你可以参考我的博客文章,我在文章中也试图提到post和PUT之间的区别http://ykshinde.wordpress.com/2014/12/05/rest-put-vs-post/

它还有返回适当HTTP代码的代码片段

希望能有所帮助。。。。。

最新更新