Apache Wicket is a populair web framework. There are a many reasons why I like to use Wicket, for instance: it offers a great mark-up/logic separation and using Wicket it’s very easy to implement AJAX functionality without writing one line of Javascript.

To provide you with simple and short tips and tricks for Wicket I write this series of blogs. In this first blog of the series I will show you how to create a download link in several ways.

The first option is to serve a static file as download with the standard component: DownloadLink.

File file = new File("static.pdf");
DownloadLink downloadlink = new DownloadLink("link1", file, "download.pdf");
add(downloadlink);

If you want to use dynamic content and only create / generate the file when the users click the download link, you have to create a Model which will return the file. When you override the onClick method, you can get the file from the Model and create a resourcestream containing the downloadable file.

IModel<File> fileModel = new AbstractReadOnlyModel<File>() {

    @Override
    public File getObject() {
        return generateFile();
    }
};

DownloadLink dynamicDownloadlink = new DownloadLink("link2", fileModel) {

    @Override
    public void onClick() {

        File file = (File)getModelObject();
        IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));

        getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream, file.getName()));

    }
};

add(dynamicDownloadlink);

A third method is to serve a byte array when the download link is clicked. This method is useful when you want to serve a file which is stored in an external source, like a database.

Link<Void> streamDownloadLink = new Link<Void>("link3") {

    @Override
    public void onClick() {

        AbstractResourceStreamWriter rstream = new AbstractResourceStreamWriter() {

            @Override
            public void write(OutputStream output) throws IOException {
                output.write(getContent());
            }
        };

        ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(rstream, "file.pdf");
        getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
    }
};

add(streamDownloadLink);

These code examples are written in Wicket 6.7. In next blog I will show you how to use the ListView component and how to style your list.

shadow-left