如何从其他网络项目中调用rest api

时间:2018-10-06 13:44:06

标签: javascript java

我创建了两个项目:

  1. 具有所有客户端代码的网络项目。
  2. 项目具有服务器端代码,例如rest API等。

使用tomcat服务器,当我尝试从Web项目中调用rest API时,它无法访问API。如何从其他项目访问rest API?

给出错误: HTTP状态404-/ clientSide / rest / hello

  1. 客户端代码

    <a href="/rest/hello">Click Here</a>

  2. 服务器端代码

Hello.java

@Path("/hello")

public class Hello {
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello Jersey Plain";
  }
  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</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 HTML" + "</h1></body>" + "</html> ";
  }

}

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" 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>flatMateWeb</display-name>
   <servlet>  
    <servlet-name>Jersey REST Service</servlet-name>  
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  
    <init-param>  
        <param-name>jersey.config.server.provider.packages</param-name>  
        <param-value>com.javatpoint.rest</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>

1 个答案:

答案 0 :(得分:1)

您犯的错误是,您没有指定资源的完整路径IpAddress:port/War-name/url-pattern/resource-name,而是资源路径是/clientSide/rest/hello

例如,我创建了一个Rest API,并构建了一个战争名称War_name,并将其部署在tomcat上,其在端口locally上运行8080。现在,我创建了一个客户端代码,如下所示。请注意href部分。

<html>

    <body>

        <h1>Test</h1>

        <a href="http://localhost:8080/War_Name/rest/names">Link</a>
    </body>

</html>

您可以看到我如何提到full-path to the resource- http://localhost:8080/War_Name/rest/names 。在指定了IpAddress和端口之后,我有了war_name,然后有了url-pattern,最后是指向@Path批注中指定的资源的路径。

单击Link时,我可以看到Rest-Api返回的输出。