我已经创建了我的第一个基本的休息api。它的工作找到并使用此URL给我输出xml
http://localhost:8080/Webservice/Test/RestClient
现在,我在想如果我希望我的api只向服务器询问特定数据,那么我如何在api url中使用相同的参数。
这是我的小更新代码
package RestClient;
//import javax.servlet.annotation.WebServlet;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.annotation.XmlRootElement;
@Path("/RestClient")
@XmlRootElement
public class Restwebclient {
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello(@PathParam("x") int x, @PathParam("y") int y) {
String output = "";
if (x == 1 && y == 1) {
output = "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
else if (x == 2 && y == 2) {
output = "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}
return output;
}
}
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>Webservice</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>JAVA WS</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>RestClient</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAVA WS</servlet-name>
<url-pattern>/Test/*</url-pattern>
</servlet-mapping>
</web-app>
但是当运行这样的url传递参数时,输出
中没有任何内容http://localhost:8080/Webservice/Test/RestClient?x=1&y=1
注意:如果条件
,则url中上述参数的预期输出应该是第一个我可以知道为了达到这个目的我还缺少什么吗?
答案 0 :(得分:0)
您要在查询中发送参数,因此您应使用@QueryParam
而不是@PathParam
。改变方法:
public String sayXMLHello(@QueryParam("x") int x, @QueryParam("y") int y) {
查询参数:
http://localhost:8080/Webservice/Test/RestClient?x=1&y=1
路径参数需要改变路径:
@Path("{x}/{y}/RestClient")
http://localhost:8080/Webservice/Test/1/1/RestClient