如何使用 Jersey 读取 RESTful 服务的 POST 参数?

发布于 2024-11-09 08:09:06 字数 849 浏览 0 评论 0 原文

我没有使用 JSON 或类似的东西。我有一个简单的表单来上传文件,我想读取表单的参数。下面的代码没有按预期工作。它不会显示任何参数。

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("{appNum}/{docId}/file")
public Response uploadDocFile(
        @PathParam("appNum") String appNum,
        @PathParam("docId") String docId,
        @Context HttpServletRequest req)
{

    try {

        log.info("POST Parameters:");

        Enumeration e = req.getParameterNames();

        while(e.hasMoreElements())
        {
            Object key = e.nextElement();
            log.info("Key: " + key);
            log.info("Val: " + req.getParameter(key.toString()));
        }


    }  catch (Exception e) {
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new StatusResponse(e)).build();
    }

    return Response.ok().build();
}

I am not using JSON or anything like that. I have a simple form to upload a file and I want to read the parameters of the form. The code below is not working as expected. It will not show any parameters.

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("{appNum}/{docId}/file")
public Response uploadDocFile(
        @PathParam("appNum") String appNum,
        @PathParam("docId") String docId,
        @Context HttpServletRequest req)
{

    try {

        log.info("POST Parameters:");

        Enumeration e = req.getParameterNames();

        while(e.hasMoreElements())
        {
            Object key = e.nextElement();
            log.info("Key: " + key);
            log.info("Val: " + req.getParameter(key.toString()));
        }


    }  catch (Exception e) {
        e.printStackTrace();
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new StatusResponse(e)).build();
    }

    return Response.ok().build();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风吹短裙飘 2024-11-16 08:09:06

仅供参考,您需要使用@FormParam。还要确保 INPUT HTML 类型使用 name= 而不是 id=。

FYI, You need to use @FormParam. Also make sure INPUT HTML types are using name= not id=.

甜味拾荒者 2024-11-16 08:09:06

我有同样的问题。对各个参数使用 @FormParam 注释是可行的,但从通过 @Context 注入的 HttpServletRequest 中读取它们则不行。我还尝试使用 Provider@RequestParameters> 通过 Guice 获取请求对象/参数。在这两种情况下都没有后置参数。

但是,可以通过向资源方法添加 MultivaluedMap 参数来获取参数映射。例子:

@POST
public void doSomething(MultivaluedMap<String, String> formParams) {
//...
}

I have the same problem. Using @FormParam annotation for individual parameters works, but reading them from HttpServletRequest injected through @Context doesn't. I also tried to get the request object/parameters through Guice using Provider<HttpServletRequest> and @RequestParameters<Map<String, String[]>>. In both cases there were no post parameters.

However, it is possible to get a map of parameters by adding a MultivaluedMap<String, String> parameter to resource method. Example:

@POST
public void doSomething(MultivaluedMap<String, String> formParams) {
//...
}
山有枢 2024-11-16 08:09:06

如果您在 JAVA 中使用 Jersey RESTful API,您可以查找 Jersey RESTful API。 java.net/documentation/latest/jaxrs-resources.html#d0e1433" rel="nofollow">参数注释 (@*Param)

示例:

依赖项:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.8</version>
</dependency>

代码:

package yourpack;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/path_to_data")
public class DataResource {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String urlparam) {
        int ok = 200;
        String result = "Jersey Data resource: " + urlparam;

        return Response.status(ok).entity(result ).build();
    }
}

注释列表: @MatrixParam@HeaderParam@CookieParam@FormParam@QueryParam@PathParam

If you are using Jersey RESTful API in JAVA you can look for Parameter Annotations (@*Param)

Example:

Dependency:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.8</version>
</dependency>

Code:

package yourpack;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/path_to_data")
public class DataResource {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String urlparam) {
        int ok = 200;
        String result = "Jersey Data resource: " + urlparam;

        return Response.status(ok).entity(result ).build();
    }
}

List of annotations: @MatrixParam, @HeaderParam, @CookieParam, @FormParam, @QueryParam, @PathParam

娇柔作态 2024-11-16 08:09:06

在某个时间点,Jersey ContainerServlet(或请求处理期间的其他 Jersey 对象)调用 request.getInputStream() 或 request.getReader(),将 'usingInputStream' 或 'usingReader' 设置为 TRUE。此状态可防止填充请求对象内的参数映射。像这样的事情:

parseParameters() {
    if (usingInputStream || usingReader) {
        return; 
    } else {
        parametersMap.putAll({actual parameters parsing from stream})
    }
} 

Map getParametersMap() {
    return parametersMap;
}

尝试在应用程序的第一个入口点(Jersey ServletContainer.service() 方法的开头)放置一个断点并评估 request.getParametersMap() 调用。你会得到你的参数。

At some point of time Jersey ContainerServlet (or other Jersey object during request processing) calls request.getInputStream() or request.getReader() which set 'usingInputStream' or 'usingReader' to TRUE. This state prevents populating of parameters map inside the request object. Something like this:

parseParameters() {
    if (usingInputStream || usingReader) {
        return; 
    } else {
        parametersMap.putAll({actual parameters parsing from stream})
    }
} 

Map getParametersMap() {
    return parametersMap;
}

Try putting a break point at the very first entry point (beginning of Jersey ServletContainer.service() method) of your application and evaluate request.getParametersMap() call. You'll get your parameters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文