Restful Web Service没有回答

时间:2013-12-06 07:35:23

标签: java web-services

我是网络服务编程新手并遇到麻烦。在网上搜索了两天后,我完全感到困惑,我的例子没有向我提供任何数据。

我想编写一个应该在tomcat 7或glassfish 4上运行的restful Web服务。

这是我的代码:

SimpleService.class

@Path("say")
public class SimpleService {

    @Path("hello")
    @GET
    public String doGreet() {
        return "Hello Stranger, the time is "+ new Date();
    }
}

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>test002</display-name>
  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/you/*</url-pattern>
  </servlet-mapping>
</web-app>

http.//localhost:8070/test002/you/say/hello上的请求获得404.

3 个答案:

答案 0 :(得分:1)

我的建议。在Tomcat上部署应用程序,并使用Tomcat管理器应用程序检查您的应用程序是否正在运行。

确保在URL路径中使用WAR文件的EXACT名称:

http://localhost:8070/<Name of WAR-file>/you/say/hello

另请注意,tomcat默认使用端口8080。

对于Tomcat,您还必须在web.xml中更改servlet类定义。 现在你正在使用Glassfish之一。也许您可以考虑使用Jersey,因为它是Oracle的JAX-RS参考实现。

在这种情况下,您必须指定

com.sun.jersey.spi.container.servlet.ServletContainer

作为你的servlet类。

从您的网址格式和您使用的网址中删除you

使用您返回的数据注释您的服务方法并不是一个坏习惯,在您的情况下它是纯文本:

@Produces(MediaType.TEXT_PLAIN)

您的SimpleService不需要实现接口。看起来很正确。

如果它适用于Tomcat,那么将它用于Glassfish就不会那么难......

答案 1 :(得分:1)

您必须在服务中配置完整资源路径:

SimpleService.class

@Path("/you/say")
public class SimpleService {

    @Path("/hello")
    @GET
    public String doGreet() {
        return "Hello Stranger, the time is "+ new Date();
    }
}

答案 2 :(得分:1)

从一个干净的平板开始可能是最明智的:https://jersey.java.net/documentation/latest/getting-started.html如果Maven不是一个选项,无论如何都要创建Maven项目并在Eclipse中加载它。然后将类路径设置和“maven依赖项”复制到您自己的项目中。

如果你弄清楚哪里出错了,也许可以在这里发布,以便其他人可以受益。