我是REST服务的新手,我在过去两周内遇到了问题。我正在使用泽西岛。我试图使用一个简单的REST客户端来调用POST方法,该方法接受JSON对象作为参数并将其存储到数据库。我的方法不起作用,但我决定退后一步,所以现在我使用更简单的客户端和更简单的提供程序,以便只测试我的POST和GET方法。奇怪的是,虽然我能够调用POST方法:
@POST
@Path("/store")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String storeData(String str) throws SQLException {
String query = "insert into myDB.test (id, name) values ('1', '" + str + "')";
MyDB db = new MyDB();
db.runQuery(query);
return responseCode.toString();
}
这很好用!
但是在同一个类中,@ GET方法不起作用并返回404错误。 我的代码如下:
@GET
@Path("/retrieve")
@Produces(MediaType.TEXT_PLAIN)
public String getResponse() {
return "Hello!";
}
我知道我的问题对很多人来说可能很简单......但是我试图找出我做错了什么,以便继续我的实际实施......
提前多多感谢。
码头
这是我的客户端代码
public class TestClient {
public static void main(String[] args) {
ClientConfig clientConfig = new DefaultClientConfig();
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/server_classes/rest/server/retrieve");
System.out.println(webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, "hello"));
}
}
这是我的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_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>server_classes</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>server_classes</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
我的包名为server_classes,资源的路径是@Path(“/ server”)
我从一开始就再次尝试了vogella教程,只是改变了注释路径和方法(不只是给出了“Hello Jersey”响应)。但是现在,我无法运行任何东西。只有404错误!
O还删除了Tomcat的实例,然后整个tomcat安装并重新安装它,问题依然如故。我正在研究Ubuntu 12.04,如果这有帮助..谢谢!
答案 0 :(得分:0)
尝试将您的请求从post
更改为get
,因为您的servlet映射需要:
webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);