Why do I get Error method has more than one entity. You must use only one entity parameter

Viewed 27

I am developing a servlet for JAVA EE and keep getting this error "Error Viewerpage.index method has more than one entity. You must use only one entity parameter."

@ApplicationPath("REST2")
@Path("/viewer")
public class Viewerpage extends Application {
private GlobalConfiguration globalConfiguration;
private ViewerService viewerService;

@GET
@Path(value = "/viewer")
public Response index(String filename, String page, HttpServletResponse response) throws IOException {
    // set headers before we write to response body
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MediaType.TEXT_HTML);

    // render a page of a file based on a parameters from request
    renderPage(filename, response.getOutputStream());

    // complete response
    response.flushBuffer();
     String value = "redirect:index";
    return Response.status(Response.Status.OK).entity(value).build();

}

private void renderPage(String filename, OutputStream outputStream) {
    String filepath = "storage/" + filename;

    // render first page
    MemoryPageStreamFactory pageStreamFactory = new MemoryPageStreamFactory(outputStream);
    HtmlViewOptions viewOptions = HtmlViewOptions.forEmbeddedResources(pageStreamFactory);

    Viewer viewer = new Viewer(filepath);
    viewer.view(viewOptions);
    viewer.close();
}
}

Any ideas what cause this error?

2 Answers

Think of the HTTP response that gets streamed to the client. You are sending it with

response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.TEXT_HTML);
renderPage(filename, response.getOutputStream());
response.flushBuffer();

But then, afterwards (when the response stream at most should be closed), you try to do something that looks like building a second response:

Response.status(Response.Status.OK).entity(value).build();

As every response can have only one set of header and body you cannot go back setting headers or sending a second response entity. That is what the error is about.

When you declare a resource method, you can only have one parameter that is the request entity. The parameter without any annotations is considered the entity body. All other parameters must have some kind of annotation that specifies what it is and what should be injected. If they are query parameters, use @QueryParam. If it is a path parameter, use @PathParam. If it some other non-Param injectable (that is supported), then use @Context. Other supported "Param" injectable types are @HeaderParam, @FormParam, @CookeParam, @MatrixParam`, etc.

Related