如何“扔"JSF2 404 错误? [英] How to "throw" JSF2 404 error?
问题描述
假设我有一个管理用户的应用程序.您可以添加新用户、删除它们、编辑详细信息等.每个用户都有一个 ID 并且在 URL 上有详细信息页面,如下所示:
Let's say that I have an application which manages users. You can add new user, delete them, edit detail etc. Each user has na ID and has detail page on URL like this:
..../user/detail.jsf?id=123
现在,如果 ID 为 123 的用户不存在怎么办?我认为自然反应将是 404 标准错误.与在 URL(如/user/dtail.jsf)中输入拼写错误时输出的完全相同.那么问题来了:有这种方法吗?
Now, what should happen if user with ID 123 does not exists? I think that natural reaction would be 404 standard error. Exactly the same as is outputed when you make some typo in URL (like /user/dtail.jsf). So the question is: is there such method?
或者这个反应 (404) 是否合适?
Or maybe is this reaction (404) appropriate?
谢谢.
推荐答案
只需将验证器附加到 id 视图参数,如果验证失败,则在响应中设置错误代码 404.
Just attach a validator to the id view parameter and if validation fails, set error code 404 on the response.
例如
考虑这个简单的 Facelet:
Consider this simple Facelet:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<f:metadata>
<f:viewParam id="id" name="id" value="#{myBean.id}" validator="#{myBean.validate}"/>
</f:metadata>
<h:body>
<h:outputText value="#{myBean.id}"/>
</h:body>
</html>
以及以下支持 bean:
And the following backing bean:
@ManagedBean
@ViewScoped
public class MyBean {
private Long id;
public void validate(FacesContext context, UIComponent component, Object object) {
// Do some validation
// And if failed:
context.getExternalContext().setResponseStatus(404);
context.responseComplete();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
这篇关于如何“扔"JSF2 404 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!