How to process binary stream in Wicket like Servlet?

為{幸葍}努か 提交于 2019-12-11 02:47:13

问题


Using Servlet, I can do the following to process binary stream:

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    InputStream inputStream = req.getInputStream();
    byte[] data = IOUtils.toByteArray(inputStream);

    // ...
    Result result = process(data);       
    // ...

    ServletOutputStream op = resp.getOutputStream();
    result.writeTo(resp.getOutputStream());
}

How I can do this in Wicket? (I have no clue after creating a page extends WebPage class)


回答1:


You could do it like this:

public class OutputStreamPage extends WebPage { public OutputStreamPage( PageParameters p ) { }

@Override
protected final void onRender( MarkupStream markupStream )
{
    OutputStream os = getResponse().getOutputStream();
    BufferedWriter out = null;
    try
    {
        out = .....
        out.write( ..... );
    }
    catch ( IOException e )
    {
        // WHAT TO DO?
    }
    finally
    {
        if ( out != null )
        {
            try
            {
                out.close();
            }
            catch ( IOException e )
            {
            }
        }
    }
}

}




回答2:


This isn't really very natural to do in Wicket, but you can get access to the request and response objects as described in this wiki page and likely do this more or less as in your servlet code.

Or you can simply have your servlet configured in web.xml independently of wicket.

If you don't mind changing from a raw POST with binary data to a multipart form with an upload, the most natural wicket way of dealing with such is shown in the wicket examples upload.




回答3:


I am now using AbstractResourceStreamWriter to implement the solution:

public MyApiPage(final PageParameters pageParameters) {

    HttpServletRequest httpServletRequest = getHttpRequest();
    byte[] data = IOUtils.toByteArray(httpServletRequest.getInputStream());
    IResourceStream resourceStream = new MyApiResourceStream(data);
    getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream));
}

private class MyApiResourceStream extends AbstractResourceStreamWriter {

    private byte[] data;
    public MyApiResourceStream(byte[] data) {
        this.data = data;
    }

    @Override
    public void write(Response webResponse) {
        byte[] convertedData = // do some works here...
        webResponse.write(convertedData);

    }
}



回答4:


For such needs you should use a specialization of Wicket's org.apache.wicket.request.resource.IResource instead of a WebPage. Or plain Servlet if you don't need access to Wicket's Application/Session.



来源:https://stackoverflow.com/questions/8032469/how-to-process-binary-stream-in-wicket-like-servlet

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