如何在Servlet中处理Wicket中的二进制流?

时间:2011-11-07 03:33:07

标签: wicket

使用Servlet,我可以执行以下操作来处理二进制流:

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

我如何在Wicket中做到这一点? (创建页面扩展WebPage类后我没有任何线索)

4 个答案:

答案 0 :(得分:1)

你可以这样做:

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 )
            {
            }
        }
    }
}

@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 ) { } } } }

答案 1 :(得分:1)

这在Wicket中并不是很自然,但您可以按照this wiki page中的描述访问请求和响应对象,并且可能会像在servlet代码中那样或多或少地执行此操作。

或者您可以在web.xml中独立于wicket配置servlet。

如果您不介意从具有二进制数据的原始POST更改为带有上传的多部分表单,则the wicket examples upload中会显示处理此类问题的最自然的wicket方式。

答案 2 :(得分:1)

我现在使用AbstractResourceStreamWriter来实现解决方案:

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

    }
}

答案 3 :(得分:0)

对于这些需求,您应该使用Wicket的org.apache.wicket.request.resource.IResource而不是WebPage的专业化。如果您不需要访问Wicket的应用程序/会话,请使用简单的Servlet。