在JSF中提供文件下载,例如download.jsf?id = 123

时间:2017-02-20 14:19:44

标签: jsf

我正试图以

的风格提供下载链接(也应该适用于img标签中的图像)
http://www.domain.example/download.jsf?id=123

我的解决方案到目前为止看起来像这样:(从这里复制:How to provide a file download from a JSF backing bean?

GetFile.java

@ManagedBean
@ViewScoped
public class GetFile{

// property and getter

public void setId(String id) {

    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset();
    ec.setResponseContentType(contentType); 
    ec.setResponseContentLength(contentLength);
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    try (OutputStream output = ec.getResponseOutputStream()) {
        // Now you can write the InputStream of the file to the above
        // OutputStream the usual way.
        // ...

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fc.responseComplete(); 
}

我的 download.xhtml 如下所示:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core">

    <f:metadata>
        <f:viewParam name="id" value="#{getFile.id}" />
    </f:metadata>

</html>

到目前为止这是有效的。但是,当我想添加其他参数,如

http://www.domain.example/download.jsf?id=123&format=txt

然后我必须考虑参数的设置顺序,并在最后一个setter中执行此操作。这可行,但我没有找到一个非常漂亮的解决方案,所以我的问题是,有没有更好的方法来实现这一目标?

任何提示都非常感谢!

1 个答案:

答案 0 :(得分:0)

在setter中启动下载通常不是一个非常好的设计,只应该做主要目的,设置一个变量(可能还有一些与设置相关的检查/转换/等)。

要开始下载,您应该在辅助bean中创建一个处理下载并使用该方法的新方法。所以你的bean应该是这样的:

<强> GetFile.java

@ManagedBean
@ViewScoped
public class GetFile {

    // properties, getter and setter

    public void download() {
        // your download code goes here
    }
}

通过这种方式,您可以根据需要使用任意数量的参数,并按照您的方式传递它们。在 download.xhtml 中,您可以在传递如下参数后调用您的bean方法:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core">

    <f:metadata>
        <f:viewParam name="id" value="#{getFile.id}" />
        <!-- your other parameters come here -->
    </f:metadata>
    #{getFile.download()}
</html>