【问题标题】:Getting HttpServletRequest.getParts() to work with jersey让 HttpServletRequest.getParts() 与球衣一起使用
【发布时间】:2020-11-16 23:26:40
【问题描述】:

我有

@MultipartConfig(location="/tmp", fileSizeThreshold=1048576,
        maxFileSize=20848820, maxRequestSize=418018841)
@Path("/helloworld")
public class HelloWorld extends HttpServlet {

@POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    //@Consumes()
    @Produces("text/plain")
    public void doPost(@Context HttpServletRequest httpRequest) {
        System.out.println("pinged");
       //...
    }
}

我想访问这些部件并获取文件。但是当我做 httpRequest.getPart("token") 我得到java.lang.IllegalStateException: Request.getPart is called without multipart configuration. 我如何让它工作?我正在使用 Jersey,我知道使用 FormDataMultiPart 可以更好地执行此操作,但我的目标是编写一个函数,该函数采用 HttpServletRequest 并提取一些数据并将其转换为自定义对象。 (这里使用 jersey 服务器纯粹是随机的。我希望我的函数能够与我没有 FormDataMultiPart 但有 HttpServletRequest 的其他 java 服务器一起使用。

【问题讨论】:

    标签: java servlets jersey


    【解决方案1】:

    首先,这不是应该如何使用 JAX-RS。不要将 JAX-RS 注释与 Servlet 混合使用。您需要做的是将多部分配置添加到 web.xml 中。

    <servlet>
        <servlet-name>com.example.AppConfig</servlet-name>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
            <max-file-size>10485760</max-file-size>
            <max-request-size>20971520</max-request-size>
            <file-size-threshold>5242880</file-size-threshold>
        </multipart-config>
    </servlet>
    <servlet-mapping>
        <servlet-name>com.example.AppConfig</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
    

    注意 servlet-name 是 Application 子类的完全限定类。

    其余的都是我用来测试的

    import javax.ws.rs.core.Application;
    
    // if you're using `@ApplicationPath`, remove it
    public class AppConfig extends Application {
    
    }
    
    @Path("upload")
    public class FileUpload {
        @POST
        @Path("servlet")
        public Response upload(@Context HttpServletRequest request)
                throws IOException, ServletException {
            Collection<Part> parts = request.getParts();
            StringBuilder sb = new StringBuilder();
            for (Part part: parts) {
                sb.append(part.getName()).append("\n");
            }
            return Response.ok(sb.toString()).build();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 2012-10-28
      • 1970-01-01
      相关资源
      最近更新 更多