Jersey的简单Web应用程序返回404

时间:2015-05-07 15:37:45

标签: java rest jersey

我正在尝试使用Jersey-服务器端实现一个非常简单的Web应用程序。我没有使用Maven或eclipse或任何其他工具。我打电话给下面的网址:

http://server:port/RestfulExample/hello

我跟踪日志文件,这就是我所看到的:

GET / RestfulExample / hello HTTP / 1.1" 404 5

我查看了很多其他帖子,我试图确保我的url模式与我在main.java,web.xml和我调用的url中的匹配。 我最初关注的是vogella的教程here

main.java类:

package com.unitask.web;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


//Sets the path to base URL + /hello
@Path("/hello")

public class main{

   @GET
   @Produces(MediaType.TEXT_PLAIN)
   public String sayPlainTextHello(){
      return "Hello Jersey";
   }//end of hello

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  }

}//end of class

web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>

 <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

  <display-name>Restful Application Example</display-name>
      <description>
          Restful Server App Sample using Jersey.
      </description>

    <servlet>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <servlet-name>Jersey Web App</servlet-name>
         <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>com.unitask.web.main</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web App</servlet-name>
       <url-pattern>/*</url-pattern>
    </servlet-mapping>

 </web-app>

1 个答案:

答案 0 :(得分:0)

因为你有两个单@Path("/hello")模式的方法映射。所以它含糊不清。

使用@Path将每个方法映射到不同的URL模式。像

@Path("/hello")
public class main{

   @Path("/sayPlain")
   @GET
   @Produces(MediaType.TEXT_PLAIN)
   public String sayPlainTextHello(){
      return "Hello Jersey";
   }//end of hello


  @Path("/sayHTML")
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  }

}//end of class