正在验证JSF视图参数和错误消息



我有一个JSF2页面,其中包含必须在数据库中查找的视图参数。然后在页面上显示该实体的属性。

现在我想处理视图参数丢失/无效的情况

<f:metadata>
    <f:viewParam name="id" value="#{fooBean.id}" />
    <f:event type="preRenderView" listener="#{fooBean.init()}" />
</f:metadata>

init()代码如下:

String msg = "";
if (id == null) {
    msg = "Missing ID!";
}
else {
    try {
        entity = manager.find(id);
    } catch (Exception e) {
        msg = "No entity with id=" + id;
    }
}
if (version == null) {
    FacesUtils.addGlobalMessage(FacesMessage.SEVERITY_FATAL, msg);
    FacesContext.getCurrentInstance().renderResponse();
}

现在我的问题是,重映射页面仍然被呈现,并且我在应用程序服务器日志中收到错误,指出实体为null(因此一些元素没有正确呈现)。我只希望显示错误消息。

我是否应该返回一个字符串,以便向错误页面发出POST?但是,如果我选择这种方式,如何添加自定义错误消息?将字符串作为视图传递参数似乎根本不是一个好主意。

在我看来,在这些情况下,最好的做法是发送一个带有适当错误代码的HTTP响应(404表示未找到/无效,403代表禁止,等等):

添加到你的FacesUtils这个实用程序方法:

public static void responseSendError(int status, String message)
                           throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    facesContext.getExternalContext().responseSendError(status, message);
    facesContext.responseComplete();
}

然后,将preRenderView侦听器更改为:

public void init() throws IOException {
    if (id == null || id.isEmpty()) {
        FacesUtils.responseSendError(404, "URL incomplete or invalid!");
    }
    else {
        try {
            entity = manager.find(id);
        } catch (Exception e) { // <- are you sure you want to do that? ;)
            FacesUtils.responseSendError(404, "No entity found!");
        }
    }  
}

相关内容

最新更新