我创建了两个项目:
使用tomcat服务器,当我尝试从Web项目中调用rest API时,它无法访问API。如何从其他项目访问rest API?
给出错误: HTTP状态404-/ clientSide / rest / hello
客户端代码
<a href="/rest/hello">Click Here</a>
服务器端代码
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>
答案 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返回的输出。