Getting HttpServletRequest.getParts() to work with jersey

别说谁变了你拦得住时间么 提交于 2021-01-28 05:21:09

问题


I have

@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");
       //...
    }
}

and I want to access the parts and get the files. But when I do httpRequest.getPart("token") I get java.lang.IllegalStateException: Request.getPart is called without multipart configuration. How do i get this to work? I am using Jersey and I know there is a better way to do this with FormDataMultiPart but my goal is to write a function that takes a HttpServletRequest and extracts some data and turns it into a custom object. (The use of a jersey server here is purely random. I want my function to work with other java servers that my not have FormDataMultiPart but do have HttpServletRequest).


回答1:


First of all this is not how JAX-RS is supposed to be used. You don't mix the JAX-RS annotations with a Servlet. What you need to do is add the multipart config into the 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>

Notice the servlet-name is the fully qualified class of the Application subclass.

And the rest I used to test

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();
    }
}


来源:https://stackoverflow.com/questions/64867167/getting-httpservletrequest-getparts-to-work-with-jersey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!