Java Rest Request处理多个参数

时间:2017-05-26 22:33:47

标签: java rest http parameters

我的问题如下: 它有点难以解释,因为有这么多论坛正在处理这类问题,但没有一个答案可以解决这个问题。

我正在使用java,我想建立一个宁静的服务。我正在使用这个:

URI uri = new URIBuilder()
                .setScheme("http")
                .setHost("localhost")
                .setPort(8080)
                .setPath("/search")
                .setParameter("first", "hello")
                .setParameter("second", "world,out")
                .setParameter("third", "there")
                .build();

我得到的是URI = http://localhost:8081/search?first=hello&second=world%2Cout&third=there

所以现在我想在URI中访问这个数据:

@GET
@Path("search/")
@Produces(MediaType.TEXT_PLAIN)
public String test(@PathParam("first") String first, @PathParam("second") String second,@PathParam("third") String third) {
    return first+second+third;
}

但我得到的是:失败:HTTP错误代码:404

所以我认为这个请求的处理程序不是应该的样子。我尝试了很多不同的东西,但没办法。

我希望有人可以解释我如何以正确的方式访问数据。 谢谢你的帮助。

编辑:这是我的控制者:

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
          context.setContextPath("/");

          Server jettyServer = new Server(8081);
          jettyServer.setHandler(context);

          ServletHolder jerseyServlet = context.addServlet(
               org.glassfish.jersey.servlet.ServletContainer.class, "/*");
          jerseyServlet.setInitOrder(0);

          jerseyServlet.setInitParameter(
             "jersey.config.server.provider.classnames",
             RestfulFarmingGameService.class.getCanonicalName());

使用码头和球衣。这就是我所拥有的一切。

2 个答案:

答案 0 :(得分:0)

如果您使用JAX-RS那么您也可以尝试这种方式。

矩阵参数的概念是它们是嵌入的任意一组名称 - 值对 一个uri路径段。矩阵参数示例为:

GET http://host.com/library/book;name=EJB 3.0;author=Bill Burke

矩阵参数的基本思想是它代表可以通过它们寻址的资源 属性以及它们的原始id。 @MatrixParam注释允许您注入URI矩阵 参与方法调用

 @GET
public String getBook(@MatrixParam("name") String name, @MatrixParam("author") String
author) {...}

当输入请求正文的类型为" application / x-www-form-urlencoded",a.k.a。和HTML 表单,您可以将请求正文中的各个表单参数注入方法参数 值。

<form method="POST" action="/resources/service">
First name:
<input type="text" name="firstname">
<br>
Last name:
<input type="text" name="lastname">
</form>

   @Path("/resources/service")
@POST
public void addName(@FormParam("firstname") String first, 
        @FormParam("lastname") String
last) {...}

答案 1 :(得分:0)

您正在使用 @PathParam ,因此您的参数必须如下所示进入网址:http://localhost:8080/search/first/second/third

如果你想使用url params发送,例如?first = somethin&amp; second =其他......等等你必须使用 @RequestParam 而不是 @PathVariable

@GET
@Path("search/")
@Produces(MediaType.TEXT_PLAIN)
public String test(@RequestParam("first") String first, @RequestParam("second") String second,@RequestParam("third") String third) {
    return first+second+third;
}
相关问题